Cut copied host buffers' CPU sync: page-at-a-time compare, log-gated copy in, merge only what may be written

The consumer's 4K boot on the RTX 5080 at the stock vm.max_map_count was
unusable past its import gate: about 680 MiB of live copies (2,934 made)
were compared whole at every commit and every completion, costing about
half a core on both sides. Until the GPU copy is wired, three exact cuts,
plus the dirty-log reports change 1 needs (the consumer's audit, A to C).

- Change 3, a page-at-a-time compare (copied.rs sync): each 4 KiB page is
  compared whole (slice equality, vectorized), and the byte-exact merge
  runs only inside a page that differs. Same bytes as before; unit-tested
  against the old routine on random data, both sides changed included.
- A, the copies' merge-back is reported: each copy keeps its pages'
  DirtySource and a writer id. sync collects the runs it wrote, and
  merge_back reports them with wrote_as before the completion is visible.
  Bytes a read-only copy drops are not reported.
- B, the runtime's own CPU writes into logged pages are reported:
  replaceRegion into a heap's shadow texture (texture/heap.rs), the argument
  encoder and copyParameterDataToBuffer, as buffer_texture.rs already did.
- C, GPU writes into logged pages imported in place are reported: each
  command buffer's written uses over memory with a dirty source, as writer 0
  (the consumer's own writes, which every copy counts). They are reported at
  commit, before signals in the completion turn, and at completion, minus the
  shadows' own copy-backs. Collection is on while copies or such imports are
  live. Past the use cap, each written import is reported whole. A texture's
  use is reported as its whole buffer or heap (correct, coarse). This also
  closes the texture-shadow gap for pages reached through two imports.
- Change 1, the log gates the copy in: where a copy's pages have a log
  (HostRam::with_dirty_pages, or the object's HostMemory::with_dirty_pages),
  a commit compares only the pages the log reports written since the copy
  last agreed. It uses one stamp per log and commit for every copy, waited
  for as the shadows' gated copy-in waits (DirtyPages::wait). A false wait,
  a copy's first copy in, bytes no log covers, and a copy that merged back
  1 MiB or more since its last copy in compare everything. The copy in now
  runs before the commit's second state-lock block, since it may wait up to
  the log's bound.
- Change 2, merge-back skips copies no finished batch may have written. Its
  "may write" is the bindings' write answers plus unnamed reach: a command
  buffer with a function that reads addresses (a root table), or one that
  executes an indirect command buffer, counts every copy as written.

WorkCounts (new): copied_copy_in_bytes_skipped, copied_merges_compared,
copied_merges_skipped. RUNTIME_VERSION 1705. Docs: copied.rs (Cost,
Coherence), dirty_pages.rs' trait doc (what the runtime reports), FAST-PATHS
(copied-host-pages known gap; the shadow gap closed), HOWTO copied host
buffers.

Measured, release, 680 MiB of live copies (2,049), median of 7, copy in /
merge back in ms:
- RTX 5080 laptop host (Core Ultra 9 275HX):
  - nothing changed: 231.8 / 231.6 before; 0.16 / 0.00 with all three;
  - 1% of pages changed: 233.7 / 233.8 before; 3.43 / 33.0;
  - one copy redrawn: 254.6 / 261.6 before; 29.4 / 34.1.
- M3 Max:
  - nothing changed: 314.5 / 314.0 before; 0.12 / 0.00;
  - 1% of pages changed: 321.4 / 321.4 before; 4.54 / 18.5;
  - one copy redrawn: 353.9 / 395.4 before; 39.4 / 54.9.
The merge-back figures are with the batch naming what it writes. A real
frame's skip rate was not measured; the new counters show it.

Verified:
- M3 Max, MoltenVK 1.4.2, --cfg m2v_gpu, under memcap and maclock: the
  runtime lib suite passes 1445, 2 skipped.
- RTX 5080 Laptop, NVIDIA 615.71.09, one 42 s hold: copied|dirty_pages|
  host_ram|event 101 pass.
- New tests: 6 plain gating and merge-skip tests; a contract test that a
  concurrent CPU write survives both ways, log on and off; 7 device tests of
  the B and C reports, the gated copy, a read-only batch skipped, and an
  unnamed write still merged back.
- Negative controls, each shown failing then passing once restored: gate
  forced off; A's report removed; C's registration or completion reports
  removed; the shadows' copy-backs not subtracted; B's heap report removed;
  merge skip forced off; unnamed reach ignored.
- clippy plain and --cfg m2v_gpu (Mac, and msi niced), rustdoc -D warnings,
  api_signatures, api_surface, fast_paths.

Lane commits: ws/cpusync-lane (180fc103c1 .. 59d82299ad, 9 commits).

One work packet, landed as 2 commits on archive/development-linear-2026-10-29: bb00ae47f6, then 2b8ad3ab58 (the re-pin).
This commit is contained in:
Anees Iqbal committed 2026-10-29 15:43:55 +02:00
1 parent fb591032fa
commit 3fd1f6672b
26 files changed
+2666 -114

No files matched your search

+4 -2
View File
@@ -292,8 +292,10 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
device that refuses their pointer.
- `HostMemory::with_dirty_pages` and its `DirtyPages` (with `DirtyStamp`): the consumer's log of
the writes to a no-copy object's pages, by which every copy of them into memory of the device's
own (a shadow of a texture over them) copies in only the pages changed since its last copy, on
every device. The runtime's own writes into the pages are reported back, naming their writer.
own (a shadow of a texture over them, a copied buffer or heap over them) copies in only the
pages changed since its last copy, on every device. The runtime's own writes into the pages are reported back: a copy's (a shadow's
copy back, a copied buffer's merge back) naming the copy as their writer, and the GPU's writes
into pages imported in place and the runtime's CPU writes into them as the consumer's.
A command that replaces every texel of such a shadow is merged back, as one that leaves some is:
copied in (the changed pages), kept, and only the words it changed written into the pages.
- `HostMemory::with_import_gate` and its `ImportGate` (with `ImportRequest`): the consumer's
@@ -90,6 +90,7 @@ use metal2vulkan::bind::{
};
use metal2vulkan::reflection::BufferBinding;
use metal2vulkan::Budget;
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::Arc;
@@ -459,7 +460,11 @@ impl ArgumentEncoder {
})?;
offsets.push(self.offset(call, index, ty)?);
}
// The bytes written, from the mapping's first: reported once written.
let mut wrote: Option<Range<u64>> = None;
for (offset, word) in offsets.into_iter().zip(words) {
let end = offset + ARGUMENT_HANDLE_BYTES;
wrote = Some(wrote.map_or(offset..end, |w| w.start.min(offset)..w.end.max(end)));
let bytes = word.to_le_bytes();
debug_assert_eq!(bytes.len() as u64, ARGUMENT_HANDLE_BYTES);
// SAFETY: `mapped` is the argument buffer's mapping at the arguments' offset, whose
@@ -475,6 +480,12 @@ impl ArgumentEncoder {
)
};
}
// A write of host pages a consumer logs is the runtime's own, which its log does not see:
// reported, so the copies of the pages take it (`dirty_pages.rs`).
if let (Some((buffer, _)), Some(wrote)) = (&self.target, wrote) {
let first = at.as_ptr() as u64;
buffer.wrote_host(first + wrote.start..first + wrote.end);
}
Ok(())
}
+62 -1
View File
@@ -26,7 +26,7 @@ use super::buffer_texture::TexelViews;
use super::churn_counts::Recycled;
use super::degradation::Degradation;
use super::device::{lock, DeviceShared};
use super::dirty_pages::DirtySource;
use super::dirty_pages::{DirtySource, PagesLog};
use super::error::{internal, invalid, nil, vulkan, Error, Problem};
use super::exit_guard;
use super::fresh_pages;
@@ -671,6 +671,38 @@ impl HostPages {
let _kept = self.dirty.set(dirty);
}
/// Keep the logs of the writes to them (`dirty_pages::PagesLog`), with their import.
pub(super) fn keep_log(&self, log: Arc<PagesLog>) {
self.import.keep_log(log);
}
/// The logs of the writes to them, where their memory came with one.
pub(super) fn log(&self) -> Option<&Arc<PagesLog>> {
self.import.log.get()
}
/// Name `key`, a buffer's (or a heap's bytes') lying in them, to their copy, where they are
/// one: its merges back compare the copy where a batch wrote that key (`copied.rs`).
pub(super) fn copied_as(&self, key: ResourceKey) {
if let Some(copied) = self.import.copied.get() {
copied.name(key);
}
}
/// Report the GPU's writes through the uses of `key`, a buffer's (or a heap's bytes') lying
/// in them, to their logs (`DirtyShadows::logged_in_place`), where they have one and lie in
/// an import the GPU writes in place: a copy reports its merges back instead (`copied.rs`),
/// and a read-only view takes no write.
pub(super) fn logged_as(&self, key: ResourceKey) {
let import = &self.import;
if import.copied.get().is_some() || import.drops_writes() {
return;
}
if let Some(log) = import.log.get() {
import.device.shared().dirty.logged_in_place(key, log);
}
}
/// Keep the guest RAM and the runs of it their caller resolved them to (`host_ram.rs`).
pub(super) fn keep_runs(&self, runs: (Arc<RamOnDevice>, Box<[Range<u64>]>)) {
let _kept = self.ram_runs.set(runs);
@@ -860,6 +892,9 @@ pub(super) struct HostImport {
/// Its place among its device's copied host buffers, where its memory is a copy of the
/// caller's pages, not their import (`copied.rs`): unregistered as it goes, before its memory.
copied: OnceLock<crate::copied::Copied>,
/// The logs of the writes to its pages, where their memory came with one
/// (`dirty_pages::PagesLog`): every buffer lying in it shares them.
log: OnceLock<Arc<PagesLog>>,
}
/// Where a host import's bytes lie in its `VkBuffer` and memory, which reading needs no
@@ -1037,6 +1072,7 @@ impl HostImport {
kept: Mutex::new(None),
after_free: Mutex::new(Vec::new()),
copied: OnceLock::new(),
log: OnceLock::new(),
}
}
@@ -1062,6 +1098,7 @@ impl HostImport {
kept: Mutex::new(None),
after_free: Mutex::new(Vec::new()),
copied: OnceLock::new(),
log: OnceLock::new(),
}
}
@@ -1085,6 +1122,16 @@ impl HostImport {
self.copied.get().is_some()
}
/// Keep the logs of the writes to its pages (set once, as its first buffer is made), which
/// its copy, where it is one, reports its merges back to (`copied.rs`).
pub(super) fn keep_log(&self, log: Arc<PagesLog>) {
if let Some(copied) = self.copied.get() {
copied.set_log(&log);
}
self.device.shared().dirty.note_logged();
let _ = self.log.set(log);
}
/// Whether its pages were imported through a read-only view of them, which drops the GPU's
/// writes (`read_only_view.rs`).
pub(super) fn drops_writes(&self) -> bool {
@@ -3239,6 +3286,20 @@ impl Buffer {
self.pages_cell()?.current()
}
/// The runtime wrote the host addresses `addresses` of the buffer's bytes through its
/// `contents` itself (a `replaceRegion`, an argument encoder's or a rasterization-rate map's
/// write): reported to the logs of the writes to its pages, where their memory came with one
/// (`dirty_pages::PagesLog`, writer 0), so every copy of the pages takes them. The pages are
/// looked at only on a device some of whose pages came with a log.
pub(super) fn wrote_host(&self, addresses: Range<u64>) {
if !self.0.device.shared().dirty.logged() {
return;
}
if let Some(log) = self.host_pages().as_ref().and_then(|pages| pages.log()) {
log.wrote_at(addresses);
}
}
/// The host imports `buffers` lie in now, each counted once however many lie in it
/// (`host_aliases.rs`): a committed command buffer's used buffers'
/// (`WorkCounts::host_imports_used`). Buffers over no host pages count none.
@@ -16,6 +16,7 @@ use super::buffer::{usage, Buffer, BufferParts, HostCell, Lying, Modes, Owner, R
use super::copied::NotCopied;
use super::degradation::Degradation;
use super::device::lock;
use super::dirty_pages::{DirtySource, PagesLog};
use super::error::MemoryKind;
use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap};
use super::heap::{Heap, HeapProblem};
@@ -25,7 +26,7 @@ use super::host_memory::{
refuse_unwritable, refused, unpinnable, Deallocator, HostMemory, HostParts, HostRelease,
ImportRequest, ImportWindow, Importer, KeepAlive, Source,
};
use super::host_ram::Routed;
use super::host_ram::{RamOnDevice, Routed};
#[cfg(unix)]
use super::host_residency::Again;
use super::memory::{ImportFailure, MemoryClass, Placement};
@@ -513,6 +514,11 @@ impl Device {
let address = self.place_window(placement, &window, length)?;
let buffer =
self.buffer_in_import(Arc::clone(&import), length, modes, address, release);
// The GPU's writes through it are reported to the import's logs, as through the
// buffer it was made for, over the same bytes (`dirty_pages.rs`).
if let Some(pages) = buffer.host_pages() {
pages.logged_as(buffer.identity().key);
}
shared
.aliases
.join(buffer.identity().key, made_over, class, &import);
@@ -533,6 +539,14 @@ impl Device {
let in_chunk = (routed.as_ref())
.and_then(|routed| unsafe { self.bind_in_chunk(importer, routed, &window, length) });
let kept_runs = routed.as_ref().map(Routed::kept);
// The logs of the writes to the pages, where their memory came with one or their guest
// RAM did (`dirty_pages::PagesLog`), kept with their import or copy.
let log = pages_log(
(pointer, length),
dirty.as_ref(),
kept_runs.as_ref(),
window.offset,
);
let (buffer, memory, again, unwritable) = match in_chunk {
Some((buffer, memory)) => (buffer, memory, None, false),
None => {
@@ -557,7 +571,7 @@ impl Device {
shared.counts.host_import_refused_by_host();
// SAFETY: the caller's contract.
let copied = unsafe { self.copied_buffer(copy, release, dirty, None) };
return copied.map(|buffer| kept_with(buffer, kept_runs));
return copied.map(|buffer| kept_with(kept_log(buffer, log), kept_runs));
}
// Only a buffer that imports its pages pins them, and so has their writability
// asked: one that lies in a live import pins none, that import's making asked for
@@ -603,7 +617,7 @@ impl Device {
// SAFETY: the caller's contract.
let copied =
unsafe { self.copied_buffer(copy, release, dirty, Some(error)) };
return copied.map(|buffer| kept_with(buffer, kept_runs));
return copied.map(|buffer| kept_with(kept_log(buffer, log), kept_runs));
}
Err(error) => return Err(error),
};
@@ -644,7 +658,7 @@ impl Device {
pages.keep_dirty(dirty);
}
}
let buffer = kept_with(buffer, kept_runs);
let buffer = kept_with(kept_log(buffer, log), kept_runs);
// A buffer over the bytes another no-copy buffer covers joins it (`host_aliases.rs`), and
// a later one lies in its import; one whose GPU writes are dropped joins none.
// A buffer just made lies in its pages (`HostCell::current`).
@@ -962,7 +976,17 @@ impl Device {
None if chunk_bound => {}
None => shared.counts.host_rebind_import_made(covered),
}
// The guest RAM and runs the caller resolved the pages to stay with them.
// The logs of the writes to them, and the guest RAM and runs the caller resolved
// them to, stay with them.
let log = pages_log(
(pointer, length),
dirty.as_ref(),
kept_runs.as_ref(),
window.offset,
);
if let Some(log) = log {
pages.keep_log(log);
}
if let Some(runs) = kept_runs {
pages.keep_runs(runs);
}
@@ -985,6 +1009,10 @@ impl Device {
if let Some(dirty) = dirty {
pages.keep_dirty(dirty);
}
// The GPU's writes through it from now on are reported to the new pages' logs, and
// merged back from a copy of them.
pages.logged_as(key);
pages.copied_as(key);
let (old, again) = shared
.rebinds
.replace(key, cell, Arc::clone(&pages))
@@ -1760,6 +1788,35 @@ impl Device {
}
}
/// `buffer`, the logs of the writes to its pages kept with them (`dirty_pages::PagesLog`), where
/// there are any, which hear of the GPU's writes through it where it lies in them in place; and
/// where its pages are a copy, its key named to the copy, whose merges back compare it where a
/// batch wrote that key (`copied.rs`).
fn kept_log(buffer: Buffer, log: Option<Arc<PagesLog>>) -> Buffer {
if let Some(pages) = buffer.host_pages() {
let key = buffer.identity().key;
if let Some(log) = log {
pages.keep_log(log);
pages.logged_as(key);
}
pages.copied_as(key);
}
buffer
}
/// The logs of the writes to the `length` bytes at `pointer` (`dirty_pages::PagesLog`): their
/// memory's own `dirty`, and the guest RAM's of the `runs` of it their import window is, the
/// bytes at its `offset`; `None` where neither has one.
fn pages_log(
(pointer, length): (NonNull<u8>, u64),
dirty: Option<&Arc<DirtySource>>,
runs: Option<&(Arc<RamOnDevice>, Box<[std::ops::Range<u64>]>)>,
offset: u64,
) -> Option<Arc<PagesLog>> {
let ram = runs.and_then(|(ram, runs)| Some((ram.dirty()?, &runs[..], offset)));
PagesLog::new((pointer.as_ptr() as u64, length), dirty, ram)
}
/// `buffer`, the guest RAM and runs its caller resolved its pages to (`host_ram.rs`) kept with
/// its pages, where there are any.
fn kept_with(
@@ -1634,15 +1634,8 @@ impl Texels {
}
// A write of host pages a consumer logs is the runtime's own, which its log does not see:
// reported, so the copies of the pages take it (`dirty_pages.rs`).
if let Some(pages) = self.buffer.host_pages() {
if let Some(dirty) = pages.dirty() {
let at = target as u64;
let range = dirty.offset_of(at).zip(dirty.offset_of(at + (end - start)));
if let Some((from, to)) = range {
dirty.wrote(from..to);
}
}
}
let at = target as u64;
self.buffer.wrote_host(at..at + (end - start));
self.buffer.upload(start..end)
}
@@ -125,6 +125,7 @@
use super::gate::Hold;
use super::CommandBufferShared;
use crate::copied::Written;
use crate::device::lock;
use crate::error::{CommandBufferError, Error, MemoryKind, VkResultCode};
use crate::event::EventShared;
@@ -406,8 +407,28 @@ fn finish(watch: &Watch, lists: &mut FenceLists, mut finished: Vec<(usize, Submi
};
// The GPU's writes into copied host buffers go back to the caller's pages before anything
// sees the batches complete: their event signals, the scheduler, a waiter, their completed
// handlers (`copied.rs`).
device.shared().copied.merge_back(&device.shared().counts);
// handlers (`copied.rs`). Only the copies the batches' command buffers may have written are
// compared.
let copied = &device.shared().copied;
if copied.any() {
let mut written = Written::default();
for (_, batch) in &finished {
let buffer = &batch.buffer;
if buffer.unnoted.load(Ordering::Relaxed) || lock(&buffer.state).reaches_unnamed {
written = Written::all();
break;
}
lock(&buffer.dirty).copies_written(&mut written);
}
copied.merge_back(&device.shared().counts, &written);
}
// So do their writes into logged host pages imported in place, to the pages' logs, again now
// they ran (`dirty_pages.rs`, `DirtyCommit::report_host_writes`).
if device.shared().dirty.in_place() {
for (_, batch) in &finished {
lock(&batch.buffer.dirty).report_host_writes();
}
}
// The holds of the batches that end no command buffer go first, their work completed: a
// detach that sees one of their signals detaches what only they held (`detach.rs`).
for (_, batch) in &mut finished {
@@ -488,6 +509,9 @@ fn fail(watch: &Watch, ending: Vec<Hold<CommandBufferShared>>, error: CommandBuf
let held = (ending.first().map(|buffer| buffer.device()))
.or_else(|| failed.first().map(|(_, batch)| batch.buffer.device()));
if let Some(device) = held {
// Their writes into copied host buffers are merged back by the next turn, which compares
// every copy (`copied.rs`).
device.shared().copied.owe();
device.drain_queues();
}
let failed = failed.into_iter().filter_map(|(queue, batch)| {
@@ -127,7 +127,7 @@ use own::{
use std::any::Any;
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
use std::ops::Range;
use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};
@@ -252,9 +252,15 @@ pub(super) struct CommandBufferShared {
/// synchronizes a pool's command buffers' recording externally.
reencoding: Mutex<()>,
/// What its commands did that the device's logs of host pages hear of at its commit
/// (`dirty_pages.rs`): collected only once the device copied a shadow over logged pages in.
/// Apart from the state, which no encoder holds while it records.
/// (`dirty_pages.rs`), and its copied host buffers' merges back (`copied.rs`): collected
/// only while the device copied a shadow over logged pages in, imports logged pages in place,
/// or keeps a copied host buffer. Apart from the state, which no encoder holds while it
/// records.
pub(super) dirty: Mutex<DirtyCommit>,
/// A command's uses went unnoted, nothing collecting them then (no copied host buffer, and
/// no log of host pages, lived): the merge back of copied host buffers takes every copy as
/// written by it (`copied.rs`).
pub(super) unnoted: AtomicBool,
/// The `VkCommandBuffer`s of its pool its recordings ended ([`CommandBuffer::end_raw`]):
/// where they are every one the pool handed out and it completed, it gives the pool back
/// with none recording (`spares.rs`).
@@ -726,6 +732,11 @@ pub(super) struct State {
/// submission, which that submission points at the set as it lies then
/// (`first_submission.rs`).
replay_tables: Vec<ReplayTable>,
/// A command of it may write memory no use it noted names: a root table (a function that
/// reaches buffers through addresses), a root table of work on the GPU alone, or work its
/// host steps resolve from records (`Deferred::reaches_unnamed`). The merge back of copied
/// host buffers then takes every copy as written by it (`copied.rs`).
pub(super) reaches_unnamed: bool,
/// The ended encoders whose submissions failed so: no part of one goes to a queue with work
/// (`submit.rs` holds it to that).
unrunnable: BTreeSet<usize>,
@@ -830,6 +841,7 @@ impl State {
/// recorded after the first submission searches the set as it lay as it was recorded, which
/// the submitted command buffer holds.
pub(super) fn replay_table(&mut self, table: ReplayTable) {
self.reaches_unnamed = true;
if !self.submitted {
self.replay_tables.push(table);
}
@@ -1002,6 +1014,7 @@ impl State {
noted: NotedTable,
ranges: Vec<ResidentRange>,
) -> Result<(), Error> {
self.reaches_unnamed = true;
if self.status == CommandBufferStatus::NotEnqueued {
self.root_ranges.extend(ranges);
self.root_tables.push(noted);
@@ -1860,6 +1873,7 @@ impl CommandBuffer {
failing: Vec::new(),
rebound_use: None,
replay_tables: Vec::new(),
reaches_unnamed: false,
unrunnable: BTreeSet::new(),
submitted_holds: Vec::new(),
failed_at_commit: None,
@@ -1881,6 +1895,7 @@ impl CommandBuffer {
reencode: AtomicU64::new(0),
reencoding: Mutex::new(()),
dirty: Mutex::new(DirtyCommit::default()),
unnoted: AtomicBool::new(false),
raws_ended: AtomicU64::new(0),
kernel: KernelTimes::default(),
status: AtomicU8::new(status_word(CommandBufferStatus::NotEnqueued)),
@@ -1930,10 +1945,15 @@ impl CommandBuffer {
}
/// Note a command's `uses` for the device's logs of host pages, where it keeps any
/// (`dirty_pages.rs`): its writes let go, at the commit, of the holds of the shadows they meet.
/// (`dirty_pages.rs`): its writes let go, at the commit, of the holds of the shadows they meet,
/// and those into logged pages imported in place are reported to their logs; and for its
/// copied host buffers, where any lives, whose merges back compare those its writes reach
/// (`copied.rs`).
pub(super) fn note_dirty(&self, uses: &[Use<ResourceKey>]) {
if self.0.device.shared().dirty.any() {
lock(&self.0.dirty).note(uses);
let shared = self.0.device.shared();
match shared.dirty.collects() || shared.copied.any() {
true => lock(&self.0.dirty).note(uses, &shared.dirty),
false => self.0.unnoted.store(true, Ordering::Relaxed),
}
}
@@ -2686,13 +2706,16 @@ impl CommandBuffer {
if let Some(residency) = &mut state.residency {
residency.sync_heaps();
}
let (segments, places) = state
let (segments, places): (Vec<(Deferred, bool)>, Vec<usize>) = state
.recorded
.iter()
.filter(|recorded| runs(recorded.encoder))
.flat_map(|recorded| (recorded.segments.iter()).map(|at| (at, recorded.encoder)))
.map(|(segment, encoder)| ((segment.work.clone(), segment.needs_step()), encoder))
.unzip();
if segments.iter().any(|(work, _)| work.reaches_unnamed()) {
state.reaches_unnamed = true;
}
// What of it the live buffers list once used, held weakly: the device's registries'
// locks, which take no other, inside this one.
let reached = state.reached(device.shared(), runs);
@@ -2700,7 +2723,7 @@ impl CommandBuffer {
// order, and of the shadows its end left holding their truth (`dirty_pages.rs`).
// One that waits for an event or a semaphore may run after work committed later,
// whose writes no commit before it noted: its copies in count on no hold.
if device.shared().dirty.any() {
if device.shared().dirty.collects() {
let held = match (&failure, &state.shadow_carry) {
(None, Some(carry)) => carry.held_whole(),
_ => Vec::new(),
@@ -2769,6 +2792,10 @@ impl CommandBuffer {
.filter(|(_, prepared)| prepared.pipelines)
.map(|((work, _), _)| work.clone())
.collect();
// Every byte the CPU changed in a copied host buffer's pages is in its copy before any of
// this command buffer's work is submitted (`copied.rs`): copied in with no lock of the
// command buffer's held, as a copy over logged pages waits for the log's publication.
shared.copied.copy_in(&shared.counts, shared.dirty.tally());
let (waits, away, reaches, unreplayable, reset) = {
let mut state = self.state();
state.committing = false;
@@ -2804,9 +2831,6 @@ impl CommandBuffer {
let ticket = state.heaps.commit(device);
state.retained.push(Box::new(ticket));
}
// Every byte the CPU changed in a copied host buffer's pages is in its copy before any
// of this command buffer's work is submitted (`copied.rs`).
device.shared().copied.copy_in(&device.shared().counts);
state.status = CommandBufferStatus::Committed;
// Its set-0 cache is shut here, before anything records again: from the commit on it
// holds what its commands took only weakly (below), so no handle a kept set holds is
@@ -4412,9 +4436,10 @@ impl CommandBufferShared {
}
(None, None) => result,
};
// The logs of host pages hear of its shadows' copies back again, now they ran, and
// let go of the holds a failed one's copies in set (`dirty_pages.rs`).
if self.device.shared().dirty.any() {
// The logs of host pages hear of its shadows' copies back and its writes in place
// again, now they ran, and let go of the holds a failed one's copies in set
// (`dirty_pages.rs`).
if self.device.shared().dirty.collects() {
let dirty = lock(&self.dirty);
(self.device.shared().dirty).completed(&dirty, result.is_err());
}
+508 -29
View File
@@ -21,9 +21,28 @@
//! signaled, the scheduler is told, its handlers run or a waiter returns, every byte the GPU
//! changed in the copy is written back into the pages, where the CPU did not change that byte
//! since ([`CopiedBuffers::merge_back`]): a byte both changed keeps the CPU's, which the next
//! commit copies in. Bytes are compared 8 at a time and merged one at a time where they differ,
//! so a merge writes no byte the GPU did not change. Each batch ends with a barrier that makes
//! its writes visible to the host (`tracker::Barrier::to_host`).
//! commit copies in. The completion compares only the copies its batches may have written: one
//! whose buffer's (or heap's) key a use of their command buffers' commands wrote, and every
//! copy where one of those may have written memory no use names (a function's loaded
//! addresses, an indirect command buffer's executions; `Written`), or kept its writes not all
//! apart. Counted: `WorkCounts::copied_merges_compared`, `copied_merges_skipped`. Bytes are compared a page (4 KiB) at a time, and inside a page that
//! differs 8 at a time and then one at a time, so a merge writes no byte the GPU did not change
//! ([`sync`]). Each batch ends with a barrier that makes its writes visible to the host
//! (`tracker::Barrier::to_host`). Where the pages' memory came with a log of the writes to them
//! (`HostMemory::with_dirty_pages`, or its guest RAM's, `HostRam::with_dirty_pages`), each merge
//! back reports the blocks it wrote to the log as the copy's own writes
//! (`DirtyPages::wrote_as`, a writer of the copy's own) before it returns: the log sees no
//! write the runtime makes, and every other copy and shadow of the pages takes them.
//! - **Copies in the log gates.** Where the pages' memory came with such a log, a commit's copy
//! in compares only the pages the log reports written since the copy's last copy in, and the
//! bytes no log keeps (a guest RAM's runs that miss some of them): a stamp of each log is asked
//! at the commit, once for every copy, its publication waited for (bounded) with no lock of
//! the copies' or the command buffer's held, and the copy synced to it
//! ([`CopiedBuffers::copy_in`]); every write made before the commit is in that publication,
//! the GPU's in place through other imports of the pages and the runtime's own CPU writes among
//! them, which the runtime reports (`dirty_pages.rs`). A copy compares every byte at its first
//! copy in after its watch began, and where a log cannot say. Counted:
//! `WorkCounts::copied_copy_in_bytes_skipped`.
//! - **Pages the process cannot write** (read-only pages, as a consumer's alias of a read-only
//! replace, `replaceBackingWithRanges:readOnly:`, maps them), asked of the system as the copy is
//! made ([`mapped_writable`]): the GPU's writes to the copy are dropped, as Metal drops the GPU's
@@ -38,10 +57,16 @@
//! wait for them is held on the host until that turn (`event_timeline.rs`), so the GPU's writes
//! before a signal are in the pages once its value is seen, as Metal's are. No submission is
//! added; a reader sees the value a completion turn later than the semaphore's counter shows it.
//! - **Cost.** Every live copy is compared whole at each commit and at each batch's completion,
//! whichever buffers the work names: O(bytes) per commit and per batch, a fallback's cost
//! (`docs/FAST-PATHS.md`, known gaps). Counted: `WorkCounts::copied_copy_in_bytes`,
//! `WorkCounts::copied_merge_back_bytes`, `WorkCounts::copied_dropped_bytes`.
//! - **Cost.** A copy is compared whole at each batch's completion that may have written it, and
//! at each commit where its pages carry no log: O(bytes) per such batch, and per commit without
//! a log, a fallback's cost (`docs/FAST-PATHS.md`, known gaps). A command buffer whose
//! functions read addresses may write every copy. A page that agrees costs one read of each
//! side and a slice comparison: 680 MiB of copies that agree took 28-30 ms each way on an M3
//! Max, 52-53 ms on a Core Ultra 9 275HX; their logged copy in took 0.15 ms (0.3) where no page
//! changed, and 4.6 ms (3.5) where 1% of the pages changed on each side; a merge back of no
//! copy written, none (`tests/copied_bench.rs`). Counted:
//! `WorkCounts::copied_copy_in_bytes`, `WorkCounts::copied_merge_back_bytes`,
//! `WorkCounts::copied_dropped_bytes`.
//! - **Heaps and rebinds.** A no-copy heap's own buffer is copied as a buffer is, where the heap's
//! textures could lie, with a heap's hazard identity; its buffers lie in the copy at their
//! offsets, and its textures are shadows of its bytes (`AliasRoute::MemoryShadow` or Metal's
@@ -55,10 +80,16 @@
//! before. A texture made over a copied buffer is a shadow of its bytes (`shadowed-texture`).
use crate::device::lock;
use crate::dirty_pages::{new_writer, DirtySource, DirtyTally, PagesLog};
use crate::host_memory::{mapped_readable, mapped_writable};
use crate::key_hash::KeyMap;
use crate::resource::ResourceKey;
use crate::work_counts::Counters;
use crate::DirtyStamp;
use std::num::NonZeroU64;
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
/// A device's live copied host buffers, compared at each commit and each batch's completion.
@@ -69,6 +100,45 @@ pub(crate) struct CopiedBuffers {
live: AtomicUsize,
/// The next copy's id.
next: AtomicU64,
/// A batch finished with no merge back (a failed wait): the next merge back compares every
/// copy, whatever its batches wrote.
owed: AtomicBool,
}
/// What the batches a completion turn finishes may have written ([`CopiedBuffers::merge_back`]):
/// the keys their command buffers' commands wrote (`DirtyCommit::copies_written`), or every copy.
#[derive(Default)]
pub(crate) struct Written {
keys: KeyMap<ResourceKey, ()>,
all: bool,
}
impl Written {
/// Every copy may have been written.
pub(crate) fn all() -> Written {
Written {
keys: KeyMap::default(),
all: true,
}
}
/// A command wrote the bytes of `key`.
pub(crate) fn wrote(&mut self, key: ResourceKey) {
if !self.all {
self.keys.insert(key, ());
}
}
/// Some command may have written a copy no use of it names.
pub(crate) fn wrote_all(&mut self) {
self.all = true;
self.keys.clear();
}
/// Whether a command may have written the copy whose uses take `keys`.
fn meets(&self, keys: &[ResourceKey]) -> bool {
self.all || keys.iter().any(|key| self.keys.contains_key(key))
}
}
/// Why a copy was not made ([`CopiedBuffers::add`]).
@@ -92,8 +162,42 @@ struct Entry {
/// The process cannot write the pages: the GPU's writes to the copy are dropped, never merged
/// back.
drops_writes: bool,
/// The logs of the writes to the pages, where their memory came with one, and the writer its
/// merges back are reported as ([`Copied::set_log`]).
log: Option<CopyLog>,
/// The keys whose uses' writes reach the copy: the buffer's, or the heap's bytes' (whose
/// buffers' and textures' uses carry it), the buffer's again after a rebind
/// ([`Copied::name`]).
keys: Vec<ResourceKey>,
}
/// A copy's logs of its pages, and its writer in them.
struct CopyLog {
pages: Arc<PagesLog>,
writer: NonZeroU64,
/// Its watches of the pages in each log, held while the copy lives.
_watches: Vec<Box<dyn Send + Sync>>,
/// The copy's bytes no log keeps the writes to: every copy in compares them.
unlogged: Arc<[Range<u64>]>,
/// The stamps, one of each log in [`PagesLog::sources`]' order, as of which the copy holds
/// every byte the CPU wrote in the pages: a copy in compares only the pages the logs report
/// written since. `None` until a copy in compared every byte after the watches began, and
/// after one some log could not answer for.
since: Option<Arc<[DirtyStamp]>>,
/// The bytes its merges back wrote into the pages since `since`: at [`ASKS_APART`] or more,
/// its copy in asks the logs for the pages any writer but it wrote
/// ([`DirtyPages::changed_except`](crate::DirtyPages)), where a copy otherwise takes the
/// pages every writer wrote, asked once per log and stamp for every copy, and compares again
/// the pages it merged.
merged: u64,
}
/// The bytes a copy's merges back wrote since its last copy in from which its copy in asks the
/// logs apart, for every writer's pages but its own (one more question of each log, which a
/// consumer answers by a pass over its watches), rather than compare its own writes again
/// (about 40 µs a MiB on an M3 Max). Both are exact.
const ASKS_APART: u64 = 1 << 20;
// SAFETY: the pointers name the caller's pages, which stay mapped while the buffer's import lives
// (`HostMemory::new`), and the copy's mapped memory, which the import holds; both are reached only
// under the registry's lock, which the import's drop takes before either goes ([`Copied`]).
@@ -112,15 +216,67 @@ impl Copied {
pub(crate) fn drops_writes(&self) -> bool {
self.drops_writes
}
/// Keep `log`, the logs of the writes to the copy's pages (`dirty_pages::PagesLog`), with a
/// writer of its own: each merge back reports the bytes it wrote to them as that writer's
/// ([`CopiedBuffers::merge_back`]). Set once.
///
/// Its pages are watched in each log from here on ([`DirtyPages::watch`](crate::DirtyPages)),
/// asked with no lock of the copies' held: its copies in compare every byte until one did
/// after the watches began ([`CopiedBuffers::copy_in`]).
pub(crate) fn set_log(&self, log: &Arc<PagesLog>) {
let Some(writer) = new_writer() else {
return;
};
let watches = log.watch();
let unlogged: Arc<[Range<u64>]> = log.unlogged().into();
let mut entries = lock(&self.buffers.entries);
let entry = entries.iter_mut().find(|entry| entry.id == self.id);
let unkept = match entry {
Some(entry) if entry.log.is_none() => {
entry.log = Some(CopyLog {
pages: Arc::clone(log),
writer,
_watches: watches,
unlogged,
since: None,
merged: 0,
});
None
}
_ => Some(watches),
};
// A watch's end is the consumer's call: made with no lock of the copies' held.
drop(entries);
drop(unkept);
}
/// The uses of `key` (a buffer's or a heap's bytes' lying in the copy) write the copy: a
/// completion turn merges it back only where a batch it finishes wrote one of its keys, or
/// may have written memory its uses do not name ([`CopiedBuffers::merge_back`]).
pub(crate) fn name(&self, key: ResourceKey) {
let mut entries = lock(&self.buffers.entries);
if let Some(entry) = entries.iter_mut().find(|entry| entry.id == self.id) {
if !entry.keys.contains(&key) {
entry.keys.push(key);
}
}
}
}
impl Drop for Copied {
fn drop(&mut self) {
let mut entries = lock(&self.buffers.entries);
if let Some(index) = entries.iter().position(|entry| entry.id == self.id) {
entries.swap_remove(index);
self.buffers.live.fetch_sub(1, Ordering::Relaxed);
}
let removed = match entries.iter().position(|entry| entry.id == self.id) {
Some(index) => {
self.buffers.live.fetch_sub(1, Ordering::Relaxed);
Some(entries.swap_remove(index))
}
None => None,
};
// Its watches end with no lock of the copies' held: a watch's end is the consumer's call.
drop(entries);
drop(removed);
}
}
@@ -193,6 +349,8 @@ impl CopiedBuffers {
copy,
snapshot,
drops_writes,
log: None,
keys: Vec::new(),
});
self.live.fetch_add(1, Ordering::Relaxed);
Ok(Copied {
@@ -204,16 +362,75 @@ impl CopiedBuffers {
/// At a commit: write into each copy the bytes the CPU changed in its pages since they last
/// agreed, before any of the command buffer's work is submitted.
pub(crate) fn copy_in(&self, counts: &Counters) {
///
/// A copy whose pages' memory came with a log of the writes to them ([`Copied::set_log`])
/// compares only the pages the log reports written since the stamp its last copy in synced
/// to, and the bytes no log keeps: a stamp of each log is asked now, once for every copy
/// (`DirtyPages::request`), and its publication waited for (`DirtyPages::wait`, bounded),
/// with no lock of the copies' held; the pages written since are asked once per log and
/// stamp for every copy (`DirtyPages::changed`), but by a copy whose merges back wrote
/// [`ASKS_APART`] bytes or more of the pages since, which asks for every writer's but its
/// own (`DirtyPages::changed_except`).
/// Every write made before this call is in a publication the wait found, so the copy takes
/// each. Every byte is compared where the copy has no earlier copy in to count on, or a log
/// answered `false`. `tally` counts the stamps and waits (`WorkCounts::dirty_stamps_asked`
/// and kin).
pub(crate) fn copy_in(&self, counts: &Counters, tally: &DirtyTally) {
if self.live.load(Ordering::Relaxed) == 0 {
return;
}
let mut moved = 0u64;
let asked: Vec<Asked> = (lock(&self.entries).iter())
.filter_map(|entry| {
let log = entry.log.as_ref()?;
Some(Asked {
id: entry.id,
length: entry.snapshot.len() as u64,
pages: Arc::clone(&log.pages),
writer: log.writer,
unlogged: Arc::clone(&log.unlogged),
since: log.since.clone(),
merged: log.merged,
})
})
.collect();
let plans = planned(asked, tally);
let (mut moved, mut skipped) = (0u64, 0u64);
for entry in lock(&self.entries).iter_mut() {
// SAFETY: the entry's pointers are live while it is registered (`Entry`).
moved += unsafe { sync(entry.pages, entry.copy, &mut entry.snapshot, false) };
let plan = match &entry.log {
Some(_) => (plans.binary_search_by_key(&entry.id, |(id, _)| *id).ok())
.map(|at| &plans[at].1),
None => None,
};
let (pages, copy, length) = (entry.pages, entry.copy, entry.snapshot.len());
match plan.and_then(|plan| plan.bytes.as_ref()) {
Some(bytes) => {
let mut compared = 0u64;
for range in bytes {
let (start, end) = (range.start as usize, range.end as usize);
// SAFETY: the entry's pointers are live while it is registered
// (`Entry`), and `start..end` lies in its bytes (`blocks`).
moved += unsafe {
sync(
NonNull::new_unchecked(pages.as_ptr().add(start)),
NonNull::new_unchecked(copy.as_ptr().add(start)),
&mut entry.snapshot[start..end],
false,
)
};
compared += range.end - range.start;
}
skipped += length as u64 - compared;
}
// SAFETY: the entry's pointers are live while it is registered (`Entry`).
None => moved += unsafe { sync(pages, copy, &mut entry.snapshot, false) },
}
if let (Some(log), Some(plan)) = (&mut entry.log, plan) {
log.since = plan.stamps.clone();
log.merged = 0;
}
}
counts.copied_copied_in(moved);
counts.copied_copy_in_skipped(skipped);
}
/// At a batch's completion: write back into each copy's pages the bytes the GPU changed in the
@@ -221,31 +438,215 @@ impl CopiedBuffers {
/// the batch complete. A copy of pages the process cannot write takes back instead the bytes
/// they last agreed on wherever the GPU changed it: the GPU's writes are dropped, and nothing
/// is written to the pages.
pub(crate) fn merge_back(&self, counts: &Counters) {
///
/// Only the copies the finished batches may have written are compared (`written`): one a
/// use of their command buffers' commands wrote by one of its keys ([`Copied::name`]), and
/// every copy where a command may have written memory no use names (its function's loaded
/// addresses, an indirect command buffer's executions), or where its command buffer's writes
/// were not all kept apart. Each batch's writes are done by its own completion turn, which
/// compares what they reach; a copy no batch wrote since its last comparison holds what its
/// pages do, but for the CPU's writes, which the next commit copies in. After a batch finished
/// with no merge (a failed wait, [`CopiedBuffers::owe`]), the next compares every copy.
/// Counted: `WorkCounts::copied_merges_compared`, `copied_merges_skipped`.
///
/// The bytes written into pages whose memory came with a log are reported to it, as the
/// copy's own writes ([`DirtyPages::wrote_as`](crate::DirtyPages::wrote_as)), a block of
/// [`SYNC_BLOCK`] bytes at a time, before this returns: the log sees no write the runtime
/// makes, and every other copy and shadow of those pages must take them, while the copy's
/// own copies in need not.
pub(crate) fn merge_back(&self, counts: &Counters, written: &Written) {
if self.live.load(Ordering::Relaxed) == 0 {
return;
}
let owed = self.owed.swap(false, Ordering::AcqRel);
let (mut moved, mut dropped) = (0u64, 0u64);
let (mut compared, mut skipped) = (0u64, 0u64);
let mut reports = Vec::new();
for entry in lock(&self.entries).iter_mut() {
match entry.drops_writes {
if !owed && !written.meets(&entry.keys) {
skipped += 1;
continue;
}
compared += 1;
let (copy, pages) = (entry.copy, entry.pages);
match (entry.drops_writes, &mut entry.log) {
// SAFETY: the entry's copy is live while it is registered (`Entry`).
true => dropped += unsafe { restore(entry.copy, &entry.snapshot) },
// SAFETY: the entry's pointers are live while it is registered (`Entry`).
false => {
moved += unsafe { sync(entry.copy, entry.pages, &mut entry.snapshot, true) }
(true, _) => dropped += unsafe { restore(copy, &entry.snapshot) },
(false, Some(log)) => {
let mut blocks = Vec::new();
// SAFETY: the entry's pointers are live while it is registered (`Entry`).
moved +=
unsafe { sync_noting(copy, pages, &mut entry.snapshot, true, &mut blocks) };
if !blocks.is_empty() {
let wrote: u64 = blocks.iter().map(|bytes| bytes.end - bytes.start).sum();
log.merged = log.merged.saturating_add(wrote);
reports.push((Arc::clone(&log.pages), log.writer, blocks));
}
}
// SAFETY: as above.
(false, None) => moved += unsafe { sync(copy, pages, &mut entry.snapshot, true) },
}
}
// Reported with no lock of the copies' held.
for (log, writer, blocks) in reports {
for bytes in blocks {
log.wrote_as(bytes, writer);
}
}
counts.copied_merged_back(moved);
counts.copied_dropped(dropped);
counts.copied_merges(compared, skipped);
}
/// A batch finished with no merge back (its queue's wait failed): the next merge back
/// compares every copy.
pub(crate) fn owe(&self) {
self.owed.store(true, Ordering::Release);
}
}
/// What a logged copy asks its logs at a copy in ([`CopiedBuffers::copy_in`]).
struct Asked {
id: u64,
length: u64,
pages: Arc<PagesLog>,
writer: NonZeroU64,
unlogged: Arc<[Range<u64>]>,
since: Option<Arc<[DirtyStamp]>>,
merged: u64,
}
/// A logged copy's copy in, as its logs answered: the bytes it compares (`None`: every byte),
/// and the stamps it syncs to (`None`: a log could not say).
struct Plan {
bytes: Option<Vec<Range<u64>>>,
stamps: Option<Arc<[DirtyStamp]>>,
}
/// One stamp of a log at a copy in, and whether its publication was found.
struct Stamped {
source: Arc<DirtySource>,
stamp: DirtyStamp,
published: bool,
}
/// The copies in of the copies `asked`, by their ids, in order: a stamp of each log asked, then
/// waited for (counted in `tally`); the pages each log reports written since a copy's stamp
/// asked once per log and stamp (or for one copy, of a copy whose merge back wrote its pages),
/// with no lock of the copies' held.
fn planned(asked: Vec<Asked>, tally: &DirtyTally) -> Vec<(u64, Plan)> {
let mut stamped: Vec<Stamped> = Vec::new();
for source in asked.iter().flat_map(|asked| asked.pages.sources()) {
if !stamped.iter().any(|s| Arc::ptr_eq(&s.source, source)) {
stamped.push(Stamped {
source: Arc::clone(source),
stamp: source.request(tally),
published: false,
});
}
}
for stamp in &mut stamped {
stamp.published = stamp.source.wait(stamp.stamp, tally);
}
// The pages each log reports written since a stamp, by every writer: asked once per log and
// stamp.
let mut written: Vec<(*const DirtySource, DirtyStamp, Vec<Range<u64>>)> = Vec::new();
let mut plans: Vec<(u64, Plan)> = Vec::with_capacity(asked.len());
for asked in asked {
let of: Vec<&Stamped> = (asked.pages.sources())
.filter_map(|source| stamped.iter().find(|s| Arc::ptr_eq(&s.source, source)))
.collect();
let now: Option<Vec<DirtyStamp>> = (of.iter())
.map(|stamped| stamped.published.then_some(stamped.stamp))
.collect();
// Copies over the same logs sync to one set of stamps.
let stamps: Option<Arc<[DirtyStamp]>> =
now.map(
|now| match plans.last().and_then(|(_, plan)| plan.stamps.as_ref()) {
Some(last) if last[..] == now[..] => Arc::clone(last),
_ => now.into(),
},
);
let bytes = match (&asked.since, &stamps) {
(Some(since), Some(_)) if since.len() == of.len() => {
let mut bytes: Vec<Range<u64>> = asked.unlogged.to_vec();
let mut own = Vec::new();
for (index, (stamped, since)) in of.iter().zip(since.iter()).enumerate() {
let changed: &[Range<u64>] = match asked.merged >= ASKS_APART {
true => {
own.clear();
let writer = Some(asked.writer);
stamped.source.changed(*since, writer, &mut own);
joined(&mut own);
&own
}
false => {
let key = (Arc::as_ptr(&stamped.source), *since);
let at = match (written.iter()).position(|w| (w.0, w.1) == key) {
Some(at) => at,
None => {
let mut runs = Vec::new();
stamped.source.changed(*since, None, &mut runs);
joined(&mut runs);
written.push((key.0, key.1, runs));
written.len() - 1
}
};
&written[at].2
}
};
asked.pages.bytes_of(index, changed, |run| bytes.push(run));
}
Some(blocks(bytes, asked.length))
}
_ => None,
};
plans.push((asked.id, Plan { bytes, stamps }));
}
plans.sort_by_key(|(id, _)| *id);
plans
}
/// `runs` sorted by start, those that meet or touch joined.
fn joined(runs: &mut Vec<Range<u64>>) {
runs.retain(|run| run.start < run.end);
runs.sort_by_key(|run| run.start);
let mut kept: Vec<Range<u64>> = Vec::with_capacity(runs.len());
for run in runs.drain(..) {
match kept.last_mut() {
Some(last) if run.start <= last.end => last.end = last.end.max(run.end),
_ => kept.push(run),
}
}
*runs = kept;
}
/// `bytes` of a copy of `length` bytes, each widened to the [`SYNC_BLOCK`]s it meets (counted
/// from the copy's first byte) and cut to the copy, sorted and joined.
fn blocks(mut bytes: Vec<Range<u64>>, length: u64) -> Vec<Range<u64>> {
let block = SYNC_BLOCK as u64;
for run in &mut bytes {
let start = run.start / block * block;
let end = run.end.div_ceil(block).saturating_mul(block).min(length);
*run = start.min(end)..end;
}
joined(&mut bytes);
bytes
}
/// The bytes [`sync`] reads of `from` at once and compares whole with the snapshot's: a host page.
pub(crate) const SYNC_BLOCK: usize = 4096;
/// Write into `to` each byte of `from` that differs from `snapshot`, and take it into `snapshot`;
/// where `keep_to`, a byte of `to` that differs from `snapshot` already (written since they last
/// agreed) is kept, though `snapshot` takes `from`'s, so the next copy the other way carries it.
/// The bytes written.
///
/// Read a block of [`SYNC_BLOCK`] bytes at a time, each read of `from` once and compared whole
/// with the snapshot's (slice equality, which the compiler vectorizes); only a block that differs
/// is looked into, 8 bytes at a time and then byte by byte, so no byte the comparison found equal
/// is written ([`merge_block`]).
///
/// # Safety
///
/// `from` and `to` are `snapshot.len()` bytes of mapped memory each.
@@ -254,23 +655,101 @@ pub(crate) unsafe fn sync(
to: NonNull<u8>,
snapshot: &mut [u8],
keep_to: bool,
) -> u64 {
// SAFETY: the caller's.
unsafe { sync_blocks(from, to, snapshot, keep_to, |_| {}) }
}
/// [`sync`], noting in `blocks` the bytes of each block it wrote a byte of, adjacent blocks
/// joined, in order.
///
/// # Safety
///
/// As [`sync`]'s.
pub(crate) unsafe fn sync_noting(
from: NonNull<u8>,
to: NonNull<u8>,
snapshot: &mut [u8],
keep_to: bool,
blocks: &mut Vec<Range<u64>>,
) -> u64 {
let note = |block: Range<u64>| match blocks.last_mut() {
Some(last) if last.end == block.start => last.end = block.end,
_ => blocks.push(block),
};
// SAFETY: the caller's.
unsafe { sync_blocks(from, to, snapshot, keep_to, note) }
}
/// [`sync`], telling `wrote` the bytes of each block it wrote a byte of.
///
/// # Safety
///
/// As [`sync`]'s.
unsafe fn sync_blocks(
from: NonNull<u8>,
to: NonNull<u8>,
snapshot: &mut [u8],
keep_to: bool,
mut wrote: impl FnMut(Range<u64>),
) -> u64 {
let (from, to) = (from.as_ptr(), to.as_ptr());
let mut written = 0u64;
let mut block = [0u8; SYNC_BLOCK];
let mut at = 0;
while at < snapshot.len() {
let span = (snapshot.len() - at).min(8);
let mut was = [0u8; 8];
was[..span].copy_from_slice(&snapshot[at..at + span]);
let mut now = [0u8; 8];
// SAFETY: `span` bytes at `at` lie in `from` (the caller's).
let span = (snapshot.len() - at).min(SYNC_BLOCK);
let now = &mut block[..span];
// SAFETY: `span` bytes at `at` lie in `from` (the caller's); `block` is this call's own.
unsafe { std::ptr::copy_nonoverlapping(from.add(at), now.as_mut_ptr(), span) };
let was = &mut snapshot[at..at + span];
if now != was {
// SAFETY: `span` bytes at `at` lie in `to` (the caller's).
let merged = unsafe { merge_block(now, to.add(at), was, keep_to) };
if merged > 0 {
wrote(at as u64..(at + span) as u64);
}
written += merged;
}
at += span;
}
written
}
/// [`sync`] inside one block whose bytes `now` (read of `from`) differ from the snapshot's `was`:
/// 8 bytes at a time, and in each 8 that differ, byte by byte, each byte of `now` that differs
/// from `was` written into `to` (where `keep_to`, unless `to`'s byte differs from `was` already)
/// and taken into `was`: eight in one store where all eight differ (and, where `keep_to`, none
/// of `to`'s does), so no byte that did not change is written. The bytes written.
///
/// # Safety
///
/// `to` is `now.len()` bytes of mapped memory, `was` as long.
unsafe fn merge_block(now: &[u8], to: *mut u8, was: &mut [u8], keep_to: bool) -> u64 {
let mut written = 0u64;
let mut at = 0;
while at < now.len() {
let span = (now.len() - at).min(8);
let (now, was) = (&now[at..at + span], &mut was[at..at + span]);
if now != was {
let mut there = [0u8; 8];
if keep_to {
// SAFETY: as above, in `to`.
// SAFETY: `span` bytes at `at` lie in `to` (the caller's).
unsafe { std::ptr::copy_nonoverlapping(to.add(at), there.as_mut_ptr(), span) };
}
// Eight bytes that all changed, none of them written in `to` since: the same bytes
// the loop below writes, in one store.
let every = now.iter().zip(was.iter()).all(|(now, was)| now != was);
if let (Ok(word), true) = (<[u8; 8]>::try_from(now), every) {
if !keep_to || there[..] == was[..] {
// SAFETY: as above; `[u8; 8]` is aligned to 1.
unsafe { to.add(at).cast::<[u8; 8]>().write_volatile(word) };
written += 8;
was.copy_from_slice(now);
at += span;
continue;
}
}
for byte in 0..span {
if now[byte] == was[byte] {
continue;
@@ -280,7 +759,7 @@ pub(crate) unsafe fn sync(
unsafe { to.add(at + byte).write_volatile(now[byte]) };
written += 1;
}
snapshot[at + byte] = now[byte];
was[byte] = now[byte];
}
}
at += span;
@@ -456,6 +456,21 @@ impl Deferred {
}
}
/// Whether its recording may write memory no use its command buffer noted names, so the merge
/// back of copied host buffers takes every copy as written by it (`copied.rs`): an indirect
/// command buffer's execution and a render pass that executes render commands, whose
/// commands its step resolves from records, an indirect dispatch and a scrub, which their
/// steps or submissions record. A dispatch whose pipelines were being made records the uses
/// its encoding noted, a gated copy in writes the shadow it names, and a loop's check records
/// nothing.
pub(super) fn reaches_unnamed(&self) -> bool {
match self {
Deferred::Execute(_) | Deferred::Dispatch(_) | Deferred::SparseScrub(_) => true,
Deferred::RenderPass(pass) => pass.executes(),
Deferred::GatedCopyIn(_) | Deferred::Pending(_) | Deferred::Loop(_) => false,
}
}
/// Whether a host step records it from what its calls resolved alone, nothing of the buffers
/// it names read again then: the buffers over host pages its commands used let their pages go
/// at the commit instead of keeping them until it completes (`CommandBuffer::commit`'s
+432 -27
View File
@@ -10,24 +10,38 @@
//! runtime asks for a stamp at a command buffer's commit ([`DirtyPages::request`]) where one of
//! its copies takes the pages again, and waits for that publication as the batch that holds
//! the copy is submitted, which records the copy then (`shadow::GatedCopyIn`,
//! [`DirtyPages::wait`]). A copy then syncs to that stamp: every write made after it is stamped
//! later.
//! [`DirtyPages::wait`]); a copied host buffer (`copied.rs`), whose copy in is the commit's
//! own, asks and waits at the commit, one stamp of each log for every copy. A copy then syncs
//! to that stamp: every write made after it is stamped later.
//! - **The pages changed** ([`DirtyPages::changed_except`]) since the stamp a copy synced to, by
//! any writer but that copy's own, are the only bytes it may lack: they are copied in, the rest
//! skipped.
//! - **The runtime's own writes** into the pages (a shadow's copy back or merge) are reported
//! ([`DirtyPages::wrote_as`]), naming the copy as their writer, so other copies of the same
//! skipped. Copied host buffers ask once per log and stamp for all of them, every writer's
//! ([`DirtyPages::changed`]), but one whose merges back wrote a MiB or more since, which asks
//! apart for every writer's but its own.
//! - **The runtime's own writes** into the pages (a shadow's copy back or merge, a copied host
//! buffer's merge back, `copied.rs`) are reported ([`DirtyPages::wrote_as`]), naming the copy
//! as their writer, so other copies of the same
//! pages see them as changed and the copy's own copies in, under a log that keeps writers
//! apart, do not.
//! apart, do not. So are the GPU's writes into pages imported in place, which no log of the
//! host's sees, and the runtime's CPU writes into the pages ([`DirtyPages::wrote`]).
//! - **The GPU's writes in place** are those a command buffer's commands name (their uses, of a
//! buffer over the pages, a heap's buffers or textures, a texture over a buffer's bytes: a
//! texture's use names its whole buffer or heap, and so does a command buffer that wrote more
//! than 64 ranges of one), reported at its commit, again before anything sees each of its
//! batches complete, and at its completion ([`DirtyCommit::report_host_writes`]), but for the
//! bytes its shadows' copies back report as their own. Metal's contract has a command reach a
//! resource only through a binding or a residency it named.
//! - **Correctness first.** A wait that answers `false`, a source that cannot say, and a copy
//! that holds nothing it may count on all copy every byte.
//!
//! [`HostMemory::with_dirty_pages`]: crate::HostMemory::with_dirty_pages
use super::copied::Written;
use super::device::lock;
use super::key_hash::KeyMap;
use super::resource::ResourceKey;
use super::shadow::ShadowCopies;
use super::tracker::Use;
use super::tracker::{Use, UseRange};
use ash::vk;
use std::fmt;
use std::num::NonZeroU64;
@@ -62,7 +76,8 @@ pub struct DirtyStamp(pub u64);
/// runtime takes every page as changed.
///
/// **Writers** (optional: both methods default to the plain ones). The runtime reports a copy's
/// own copy back or merge naming the copy as its writer ([`wrote_as`](Self::wrote_as)), and asks
/// own copy back or merge (a shadow's, or a copied host buffer's merge back of the GPU's writes,
/// `copied.rs`) naming the copy as its writer ([`wrote_as`](Self::wrote_as)), and asks
/// for that copy's copy in which pages changed by any writer but it
/// ([`changed_except`](Self::changed_except)): it already holds what it wrote, so a page only it
/// wrote since is no change to it. A writer is a [`NonZeroU64`] no other writer in the process
@@ -77,8 +92,8 @@ pub struct DirtyStamp(pub u64);
/// take: [`watch`](Self::watch) where a copy of the pages is made, [`request`](Self::request) on
/// the thread that commits a command buffer, [`wait`](Self::wait), [`changed`](Self::changed)
/// and [`changed_except`](Self::changed_except) on the thread that records its commands for the
/// GPU, [`wrote`](Self::wrote) and [`wrote_as`](Self::wrote_as) at the commit and at the
/// completion. A [`Watch`](Self::Watch) may be dropped on a completion thread, so its drop takes
/// GPU, and for copied host buffers on the thread that commits it, [`wrote`](Self::wrote) and
/// [`wrote_as`](Self::wrote_as) at the commit and at the completion. A [`Watch`](Self::Watch) may be dropped on a completion thread, so its drop takes
/// no lock the consumer holds while it calls the runtime.
///
/// [`HostMemory::with_dirty_pages`]: crate::HostMemory::with_dirty_pages
@@ -108,8 +123,12 @@ pub trait DirtyPages: Send + Sync {
/// stamped later than `since`, and of those whose continuous watch began after it.
fn changed(&self, since: DirtyStamp, out: &mut Vec<Range<u64>>);
/// The runtime wrote the memory's bytes `range` (offsets from its pointer) from the GPU (a
/// shadow's copy back, a merge), so other copies of the same pages see it as changed.
/// The runtime wrote the memory's bytes `range` (offsets from its pointer) itself: from the
/// GPU (a shadow's copy back, a merge, a copied host buffer's merge back, a command's write
/// into the pages imported in place, at the commit and again at the completion) or from the
/// CPU (a `replaceRegion` of a texture over them or of a heap's texture held in them, an
/// argument encoder's write, `copyParameterDataToBuffer`), so other copies of the same pages
/// see it as changed.
fn wrote(&self, range: Range<u64>);
/// [`wrote`](Self::wrote), naming its writer: the copy whose copy back or merge it is (the
@@ -141,6 +160,8 @@ pub(crate) trait DirtyHook: Send + Sync {
fn wrote_as_consumer(&self, range: Range<u64>);
/// [`DirtyPages::wrote_as`].
fn wrote_as(&self, range: Range<u64>, writer: NonZeroU64);
/// [`DirtyPages::changed`].
fn changed(&self, since: DirtyStamp, out: &mut Vec<Range<u64>>);
/// [`DirtyPages::changed_except`].
fn changed_except(&self, since: DirtyStamp, writer: NonZeroU64, out: &mut Vec<Range<u64>>);
}
@@ -168,6 +189,9 @@ where
fn wrote_as(&self, range: Range<u64>, writer: NonZeroU64) {
self.0.wrote_as(range, writer);
}
fn changed(&self, since: DirtyStamp, out: &mut Vec<Range<u64>>) {
self.0.changed(since, out);
}
fn changed_except(&self, since: DirtyStamp, writer: NonZeroU64, out: &mut Vec<Range<u64>>) {
self.0.changed_except(since, writer, out);
}
@@ -216,7 +240,7 @@ impl DirtySource {
}
/// [`DirtyPages::request`], counted in `tally`.
fn request(&self, tally: &DirtyTally) -> DirtyStamp {
pub(crate) fn request(&self, tally: &DirtyTally) -> DirtyStamp {
let stamp = self.hook.request();
self.requested
.fetch_max(stamp.0.saturating_add(1), Ordering::AcqRel);
@@ -234,7 +258,7 @@ impl DirtySource {
/// [`DirtyPages::wait`]'s answer for the latest stamp asked of the source, which every
/// commit's stamp asked so far is at or below, so one wait serves every command buffer
/// committed before it (counted in `tally`).
fn wait(&self, stamp: DirtyStamp, tally: &DirtyTally) -> bool {
pub(crate) fn wait(&self, stamp: DirtyStamp, tally: &DirtyTally) -> bool {
if self.published.load(Ordering::Acquire) > stamp.0 {
return true;
}
@@ -266,6 +290,20 @@ impl DirtySource {
self.hook.wrote_as_consumer(range);
}
}
/// The source's offsets of the watched pages changed since `since` ([`DirtyPages::changed`]),
/// by any writer but `writer` where given ([`DirtyPages::changed_except`]), into `out`.
pub(crate) fn changed(
&self,
since: DirtyStamp,
writer: Option<NonZeroU64>,
out: &mut Vec<Range<u64>>,
) {
match writer {
Some(writer) => self.hook.changed_except(since, writer, out),
None => self.hook.changed(since, out),
}
}
}
impl fmt::Debug for DirtySource {
@@ -304,14 +342,20 @@ impl ShadowLog {
/// Report a copy back or merge of the shadow into the `VkBuffer` bytes `range`
/// ([`DirtyPages::wrote_as`], the shadow its writer).
pub(crate) fn wrote_back(&self, range: Range<u64>) {
if let Some(offsets) = self.written(range) {
self.source.hook.wrote_as(offsets, self.writer);
}
}
/// The source's offsets a copy back or merge into the `VkBuffer` bytes `range` writes, cut to
/// the truth's; `None` where it writes none.
fn written(&self, range: Range<u64>) -> Option<Range<u64>> {
let range = self.offsets(range);
let (start, end) = (
range.start.max(self.truth.start),
range.end.min(self.truth.end),
);
if start < end {
self.source.hook.wrote_as(start..end, self.writer);
}
(start < end).then_some(start..end)
}
}
@@ -323,6 +367,24 @@ pub(crate) struct DirtyShadows {
/// Whether any log was ever made: a command buffer collects its writes only then.
any: AtomicBool,
tally: Arc<DirtyTally>,
/// Whether any host pages of the device's came with a log ([`PagesLog`]): the runtime's CPU
/// writes through a buffer's `contents` look for one only then.
logged: AtomicBool,
/// The logs of host pages imported in place (not copies), by the key their uses name ([`Imports`]),
/// which the GPU's writes through them are reported to: a command buffer collects its writes
/// once one is ([`DirtyShadows::collects`]).
imports: Mutex<Imports>,
imported: AtomicBool,
}
/// The logs of host pages imported in place, by the key of each buffer whose uses name them, held
/// weakly (the pages' import holds them): the GPU writes such pages in place, and the logs see none
/// of it but what the runtime reports ([`DirtyCommit::report_host_writes`]).
#[derive(Default)]
struct Imports {
by_key: KeyMap<ResourceKey, Vec<Weak<PagesLog>>>,
/// The keys past which the next registration lets go of those whose pages went.
prune_at: usize,
}
/// The gated copies in, as `WorkCounts::dirty_copies_in_gated` and kin count them.
@@ -339,9 +401,225 @@ pub(crate) struct DirtyTally {
pub(crate) wait_nanos: AtomicU64,
}
/// The writers no other shadow in the process is ever given.
/// The writers no other shadow or copy in the process is ever given.
static NEXT_WRITER: AtomicU64 = AtomicU64::new(1);
/// A writer no other shadow or copy in the process is ever given ([`DirtyPages::wrote_as`]).
pub(crate) fn new_writer() -> Option<NonZeroU64> {
NonZeroU64::new(NEXT_WRITER.fetch_add(1, Ordering::Relaxed))
}
/// Where an object's bytes over host pages (a no-copy buffer's, or a heap's own buffer's) lie in
/// the logs of the writes to those pages: its memory's own (`HostMemory::with_dirty_pages`),
/// whose offsets count from its pointer, and its guest RAM's (`HostRam::with_dirty_pages`), whose
/// offsets are host addresses, through the runs of the RAM its pages are. The runtime reports to
/// both what it writes into the pages itself (a copy's merge back, a `replaceRegion`, the GPU's
/// writes through an import of them); a copy of the bytes asks one of them which pages changed
/// (`copied.rs`). Kept with the pages' import, which every buffer lying in it shares.
pub(crate) struct PagesLog {
/// The host address of the object's byte 0 (its `contents`).
pointer: u64,
/// Its bytes.
length: u64,
logs: Vec<LogOf>,
}
/// One log of an object's pages ([`PagesLog`]).
struct LogOf {
source: Arc<DirtySource>,
/// The object's bytes in the source's offsets: runs, each its first byte of the object and
/// the source's offsets of it, in the object's order, apart.
runs: Box<[(u64, Range<u64>)]>,
}
impl LogOf {
/// Each run of the object's bytes that `changed` (the source's offsets, sorted by start and
/// apart) meets, to `each`, in the object's order.
fn bytes_of(&self, changed: &[Range<u64>], mut each: impl FnMut(Range<u64>)) {
for (first, offsets) in self.runs.iter() {
let from = changed.partition_point(|run| run.end <= offsets.start);
for run in changed[from..]
.iter()
.take_while(|run| run.start < offsets.end)
{
let (start, stop) = (run.start.max(offsets.start), run.end.min(offsets.end));
if start < stop {
each(first + (start - offsets.start)..first + (stop - offsets.start));
}
}
}
}
/// Each run of the source's offsets of the object's bytes `bytes`, to `each`.
fn each(&self, bytes: &Range<u64>, mut each: impl FnMut(Range<u64>)) {
for (first, offsets) in self.runs.iter() {
let end = first + (offsets.end - offsets.start);
let (start, stop) = (bytes.start.max(*first), bytes.end.min(end));
if start < stop {
each(offsets.start + (start - first)..offsets.start + (stop - first));
}
}
}
}
impl PagesLog {
/// The logs of the `length` bytes at host address `pointer`: `own`, their memory's log, and
/// `ram`, their guest RAM's log with the runs of the RAM (host addresses) their import window
/// is, in order, the bytes' first at `offset` of the window. `None` where neither is given or
/// a log holds none of the bytes.
pub(crate) fn new(
(pointer, length): (u64, u64),
own: Option<&Arc<DirtySource>>,
ram: Option<(&Arc<DirtySource>, &[Range<u64>], u64)>,
) -> Option<Arc<PagesLog>> {
let mut logs = Vec::new();
if let Some(source) = own {
if let Some(start) = source.offset_of(pointer) {
logs.push(LogOf {
source: Arc::clone(source),
runs: Box::new([(0, start..start.saturating_add(length))]),
});
}
}
if let Some((source, window, offset)) = ram {
let mut runs = Vec::new();
let mut at = 0u64;
for run in window {
let size = run.end.saturating_sub(run.start);
// The run's window bytes `at..at + size`, cut to the object's.
let (start, stop) = (at.max(offset), (at + size).min(offset + length));
if start < stop {
let host = run.start + (start - at)..run.start + (stop - at);
if let (Some(first), Some(last)) =
(source.offset_of(host.start), source.offset_of(host.end))
{
runs.push((start - offset, first..last));
}
}
at += size;
}
if !runs.is_empty() {
logs.push(LogOf {
source: Arc::clone(source),
runs: runs.into_boxed_slice(),
});
}
}
(!logs.is_empty()).then(|| {
Arc::new(PagesLog {
pointer,
length,
logs,
})
})
}
/// Its logs' sources, in its order.
pub(crate) fn sources(&self) -> impl Iterator<Item = &Arc<DirtySource>> {
self.logs.iter().map(|log| &log.source)
}
/// A watch of every run of the object's bytes in each log ([`DirtyPages::watch`]), held
/// while a copy of them asks the logs which pages changed.
pub(crate) fn watch(&self) -> Vec<Box<dyn Send + Sync>> {
(self.logs.iter())
.flat_map(|log| {
log.runs
.iter()
.map(|(_, offsets)| log.source.hook.watch(offsets.clone()))
})
.collect()
}
/// The object's bytes no log keeps the writes to, in order: every copy in compares them.
pub(crate) fn unlogged(&self) -> Vec<Range<u64>> {
let mut kept: Vec<Range<u64>> = (self.logs.iter())
.flat_map(|log| log.runs.iter())
.map(|(first, offsets)| *first..first + (offsets.end - offsets.start))
.collect();
kept.sort_by_key(|run| run.start);
let mut unlogged = Vec::new();
let mut at = 0;
for run in kept {
if at < run.start {
unlogged.push(at..run.start.min(self.length));
}
at = at.max(run.end);
}
if at < self.length {
unlogged.push(at..self.length);
}
unlogged
}
/// Each run of the object's bytes that `changed`, the runs log `index` (of [`sources`]'
/// order) reported changed, sorted by start and apart, meets, to `each`.
///
/// [`sources`]: Self::sources
pub(crate) fn bytes_of(
&self,
index: usize,
changed: &[Range<u64>],
each: impl FnMut(Range<u64>),
) {
if let Some(log) = self.logs.get(index) {
log.bytes_of(changed, each);
}
}
/// The runtime wrote the object's bytes `bytes` itself (writer 0, [`DirtyPages::wrote`]):
/// reported to every log, so every copy of the pages takes them.
pub(crate) fn wrote(&self, bytes: Range<u64>) {
for log in &self.logs {
log.each(&bytes, |run| log.source.wrote(run));
}
}
/// [`wrote`](Self::wrote), but for the source offsets `but` names of each source: what a
/// shadow over the same pages reports as its own write ([`DirtyCommit::report_host_writes`]).
fn wrote_but(&self, bytes: Range<u64>, but: &[(&Arc<DirtySource>, Range<u64>)]) {
for log in &self.logs {
log.each(&bytes, |run| {
let mut left = vec![run];
for (_, apart) in but.iter().filter(|(s, _)| Arc::ptr_eq(s, &log.source)) {
left = (left.into_iter())
.flat_map(|run| {
let before = run.start..run.end.min(apart.start);
let after = run.start.max(apart.end)..run.end;
[before, after].into_iter().filter(|r| r.start < r.end)
})
.collect();
}
for run in left {
log.source.wrote(run);
}
});
}
}
/// [`wrote`](Self::wrote) of the host addresses `addresses`, cut to the object's: a CPU write
/// of the runtime's own through its `contents` (a `replaceRegion`, an argument encoder's).
pub(crate) fn wrote_at(&self, addresses: Range<u64>) {
let start = addresses.start.saturating_sub(self.pointer);
let end = (addresses.end.saturating_sub(self.pointer)).min(self.length);
if start < end {
self.wrote(start..end);
}
}
/// The runtime wrote the object's bytes `bytes` as `writer`, a copy's merge back
/// ([`DirtyPages::wrote_as`]): reported to every log.
pub(crate) fn wrote_as(&self, bytes: Range<u64>, writer: NonZeroU64) {
for log in &self.logs {
log.each(&bytes, |run| {
if run.start < run.end {
log.source.hook.wrote_as(run, writer);
}
});
}
}
}
impl DirtyShadows {
/// The gated copies in so far.
pub(crate) fn tally(&self) -> &DirtyTally {
@@ -353,6 +631,50 @@ impl DirtyShadows {
self.any.load(Ordering::Acquire)
}
/// Host pages of the device's came with a log ([`PagesLog`]).
pub(crate) fn note_logged(&self) {
self.logged.store(true, Ordering::Release);
}
/// Whether any host pages of the device's came with a log ([`PagesLog`]).
pub(crate) fn logged(&self) -> bool {
self.logged.load(Ordering::Acquire)
}
/// Whether a command buffer collects its commands' writes ([`DirtyCommit::note`]): a shadow
/// over logged pages was copied in, or logged pages are imported in place.
pub(crate) fn collects(&self) -> bool {
self.any() || self.in_place()
}
/// Whether logged pages are imported in place ([`DirtyShadows::logged_in_place`]).
pub(crate) fn in_place(&self) -> bool {
self.imported.load(Ordering::Acquire)
}
/// Host pages imported in place whose writes `log` keeps lie under the uses of `key`, in the
/// bytes `log` keeps (a buffer's own, or a heap's, whose buffers' uses name its bytes): the
/// GPU's writes through it are reported to `log` ([`DirtyCommit::report_host_writes`]).
pub(crate) fn logged_in_place(&self, key: ResourceKey, log: &Arc<PagesLog>) {
let mut imports = lock(&self.imports);
if imports.by_key.len() >= imports.prune_at {
(imports.by_key).retain(|_, logs| {
logs.retain(|log| log.strong_count() > 0);
!logs.is_empty()
});
imports.prune_at = (2 * imports.by_key.len()).max(64);
}
let logs = imports.by_key.entry(key).or_default();
if !logs
.iter()
.any(|kept| std::ptr::eq(kept.as_ptr(), Arc::as_ptr(log)))
{
logs.push(Arc::downgrade(log));
}
drop(imports);
self.imported.store(true, Ordering::Release);
}
/// The log of `copies`, whose truth lies at `truth` of the `VkBuffer` `raw` in pages logged by
/// `source` (`raw`'s byte `v` at the host address `v + base`): kept, or made now, its watch
/// begun. A kept log of another source or `VkBuffer` (a rebind gave the buffer other pages)
@@ -400,13 +722,15 @@ impl DirtyShadows {
}
/// A command buffer whose commit was `commit` completed, `failed` or not: its shadows' copies
/// back and merges are reported again ([`DirtyPages::wrote_as`]), now they ran, so a stamp
/// asked between the commit and the GPU's write still finds them; where it failed, the holds
/// its copies in set are let go of, its copies having perhaps not run.
/// back and merges are reported again ([`DirtyPages::wrote_as`]), and its writes into logged
/// host pages imported in place ([`DirtyCommit::report_host_writes`]), now they ran, so a
/// stamp asked between the commit and the GPU's write still finds them; where it failed, the
/// holds its copies in set are let go of, its copies having perhaps not run.
pub(crate) fn completed(&self, commit: &DirtyCommit, failed: bool) {
for (log, range) in &commit.wrote {
log.wrote_back(range.clone());
}
commit.report_host_writes();
if !failed {
return;
}
@@ -439,6 +763,7 @@ impl DirtyShadows {
written,
gates,
wrote,
..
} = commit;
// One stamp per source and commit.
let mut stamps: Vec<(Arc<DirtySource>, DirtyStamp)> = Vec::new();
@@ -463,6 +788,7 @@ impl DirtyShadows {
for (log, range) in wrote {
log.wrote_back(range.clone());
}
commit.report_host_writes();
let logs: Vec<Arc<ShadowLog>> = lock(&self.logs).clone();
for log in &logs {
let Some(copies) = log.copies.upgrade() else {
@@ -487,26 +813,105 @@ impl DirtyShadows {
}
/// What a command buffer did that the logs' holds hear of at its commit
/// ([`DirtyShadows::committed`]): its commands' writes, its gated copies in, and its shadows'
/// copies back and merges into logged pages.
/// ([`DirtyShadows::committed`]): its commands' writes, its gated copies in, its shadows' copies
/// back and merges into logged pages, and its writes into logged pages imported in place.
#[derive(Default)]
pub(crate) struct DirtyCommit {
written: Vec<Use<ResourceKey>>,
gates: Vec<Arc<CopyInGate>>,
wrote: Vec<(Arc<ShadowLog>, Range<u64>)>,
/// Its writes were more than [`WRITES`]: `written` holds the first alone.
overflowed: bool,
/// Its writes into host pages imported in place whose memory is logged: each pages' logs,
/// and the bytes written, in order, at most [`HOST_RANGES`] of them, past which the pages
/// are written whole.
host: Vec<(Arc<PagesLog>, Vec<Range<u64>>)>,
}
/// The most writes a command buffer keeps apart, past which they are one write of everything.
const WRITES: usize = 4096;
/// The most ranges of one host pages' a command buffer keeps apart, past which it wrote them
/// whole.
const HOST_RANGES: usize = 64;
impl DirtyCommit {
/// Note a command's `uses`: its writes, each once.
pub(crate) fn note(&mut self, uses: &[Use<ResourceKey>]) {
/// Note a command's `uses`: its writes, each once; and of them, those into logged host pages
/// imported in place (`shadows`' [`Imports`]).
pub(crate) fn note(&mut self, uses: &[Use<ResourceKey>], shadows: &DirtyShadows) {
let imports = shadows.in_place().then(|| lock(&shadows.imports));
for used in uses.iter().filter(|used| !used.write.is_empty()) {
let seen = (self.written.iter().rev().take(8))
.any(|w| w.key == used.key && w.range == used.range);
if !seen && self.written.len() < WRITES {
self.written.push(used.clone());
match (seen, self.written.len() < WRITES) {
(true, _) => {}
(false, true) => self.written.push(used.clone()),
(false, false) => self.overflowed = true,
}
let Some(logs) = imports.as_ref().and_then(|i| i.by_key.get(&used.key)) else {
continue;
};
let bytes = match &used.range {
UseRange::Bytes(bytes) => bytes.clone(),
// An image's levels and layers, which name no bytes: all of them.
UseRange::Image { .. } => 0..u64::MAX,
};
for log in logs.iter().filter_map(Weak::upgrade) {
self.wrote_host(log, bytes.clone());
}
}
}
/// Its commands' writes, for the merge back of copied host buffers (`copied.rs`): the keys
/// they wrote, or every copy where it kept them not all apart.
pub(crate) fn copies_written(&self, into: &mut Written) {
if self.overflowed {
into.wrote_all();
return;
}
for used in &self.written {
into.wrote(used.key);
}
}
/// Note a write of `bytes` of the host pages `log` keeps the writes to.
fn wrote_host(&mut self, log: Arc<PagesLog>, bytes: Range<u64>) {
let at = match (self.host.iter()).position(|(kept, _)| Arc::ptr_eq(kept, &log)) {
Some(at) => at,
None => {
self.host.push((log, Vec::new()));
self.host.len() - 1
}
};
let ranges = &mut self.host[at].1;
let whole = 0..u64::MAX;
if ranges.first() == Some(&whole) || ranges.iter().rev().take(8).any(|r| *r == bytes) {
return;
}
match ranges.len() < HOST_RANGES {
true => ranges.push(bytes),
false => *ranges = vec![whole],
}
}
/// Report its writes into logged host pages imported in place to their logs, as the
/// consumer's writes (writer 0, [`DirtyPages::wrote`]): but for the bytes its shadows' copies
/// back and merges report as their own ([`ShadowLog::wrote_back`]), which every other copy
/// of the pages counts as changed already, and their own copies in must not. At the commit
/// ([`DirtyShadows::committed`]), again at each of its batches' completion turns, before
/// anything sees the batch complete (its event signals among them, `completion.rs`), and at
/// its completion ([`DirtyShadows::completed`]): a GPU write after a copy's sync at a stamp is
/// reported after it too, before work ordered after the write can look.
pub(crate) fn report_host_writes(&self) {
if self.host.is_empty() {
return;
}
let shadows: Vec<(&Arc<DirtySource>, Range<u64>)> = (self.wrote.iter())
.filter_map(|(log, range)| Some((&log.source, log.written(range.clone())?)))
.collect();
for (log, ranges) in &self.host {
for bytes in ranges {
log.wrote_but(bytes.clone(), &shadows);
}
}
}
+15 -4
View File
@@ -357,10 +357,21 @@ impl HostMemory {
/// The runtime reports its own writes into the pages back to the log: a shadow's copy back
/// or merge ([`DirtyPages::wrote_as`], the shadow its writer, at the commit and again at the
/// completion), which that shadow's own copies in leave out
/// ([`DirtyPages::changed_except`]), and a `replaceRegion` of a texture over them
/// ([`DirtyPages::wrote`]). A wait the log answers `false` makes the copy take every row, and
/// is not made again for a stamp at or below it. Such a shadow's copy in is never cut to the rectangle a pass's scissors bound, so its
/// image holds every texel for the next command buffer. Every other copy of the pages (a
/// ([`DirtyPages::changed_except`]), a copied host buffer's merge back of the GPU's writes
/// (`copied.rs`; [`DirtyPages::wrote_as`], the copy its writer, before the batch is seen
/// complete), the GPU's writes into them where they are imported in place
/// ([`DirtyPages::wrote`]: the bytes a command buffer's commands wrote through the buffers,
/// heaps and textures over them, at the commit, again before the batch is seen complete, and
/// at the completion), and its CPU writes into them ([`DirtyPages::wrote`]): a
/// `replaceRegion` of a texture over them or of a heap's texture held in them, an argument
/// encoder's writes, and `copyParameterDataToBuffer`. A wait the log answers `false` makes
/// the copy take every row, and is not made again for a stamp at or below it. Such a shadow's
/// copy in is never cut to the rectangle a pass's scissors bound, so its image holds every
/// texel for the next command buffer. A copied host buffer or heap over the pages
/// (`copied-host-pages`) compares at each commit only the pages the log reports written since
/// its last commit: a stamp asked of the log once per commit for every copy and waited for on
/// the committing thread, every byte compared at its first commit and where the wait answers
/// `false` (`WorkCounts::copied_copy_in_bytes_skipped`). Every other copy of the pages (a
/// shadow copied through a staging buffer, of another kind, or untracked) takes every byte,
/// as without a log. Counted:
/// `WorkCounts::dirty_copies_in_gated` and kin.
@@ -225,6 +225,12 @@ fn span_of(spans: &[Range<u64>], address: u64) -> Option<usize> {
}
impl RamOnDevice {
/// The RAM's log of the writes to its pages (`HostRam::with_dirty_pages`), where it came with
/// one: its offsets are host addresses.
pub(crate) fn dirty(&self) -> Option<&Arc<DirtySource>> {
self.ram.dirty.as_ref()
}
/// `ram`, none of its chunks imported.
fn new(ram: &Arc<HostRam>) -> RamOnDevice {
let slots = (chunk_spans(&ram.ranges).into_iter())
@@ -635,6 +635,10 @@ impl RasterizationRateMap {
bytes.len(),
)
};
// A write of host pages a consumer logs is the runtime's own, which its log does not see:
// reported, so the copies of the pages take it (`dirty_pages.rs`).
let first = contents.as_ptr() as u64 + offset;
buffer.wrote_host(first..first + bytes.len() as u64);
Ok(())
}
+163 -4
View File
@@ -5,7 +5,9 @@
//! copied all the same and others refused; on Linux, a mapping of a dma-buf (`VM_PFNMAP`), which
//! the kernel's read refuses, is copied (where `/dev/udmabuf` opens).
use crate::copied::{read_caller, restore, sync, CopiedBuffers, NotCopied};
use crate::copied::{read_caller, restore, sync, CopiedBuffers, NotCopied, Written};
use crate::dirty_pages::DirtyTally;
use crate::resource::ResourceKey;
use crate::work_counts::Counters;
use std::cell::Cell;
use std::ptr::NonNull;
@@ -100,12 +102,12 @@ fn copied_merge_back_of_unwritable_pages_drops_the_gpu_s_writes() {
assert!(copied.drops_writes());
// The GPU writes 100 bytes of the copy; the completion drops them.
copy[1000..1100].fill(0xEE);
buffers.merge_back(&counts);
buffers.merge_back(&counts, &Written::all());
assert_eq!(pages, original, "nothing written to the pages");
assert_eq!(copy, original, "the copy holds the pages' bytes again");
// A CPU write to the pages reaches the copy at the next commit.
pages[7] = !pages[7];
buffers.copy_in(&counts);
buffers.copy_in(&counts, &DirtyTally::default());
assert_eq!(copy[7], pages[7]);
drop(copied);
// A copy of writable pages merges the GPU's writes back.
@@ -117,11 +119,111 @@ fn copied_merge_back_of_unwritable_pages_drops_the_gpu_s_writes() {
let copied = copied.unwrap();
assert!(!copied.drops_writes());
other[0] = !other[0];
buffers.merge_back(&counts);
buffers.merge_back(&counts, &Written::all());
assert_eq!(writable[0], other[0], "merged back");
drop(copied);
}
/// The comparison as it was before it read a page at a time: 8 bytes at a time, each 8 that
/// differ byte by byte. [`sync`] must answer exactly as it does.
fn reference_sync(from: &[u8], to: &mut [u8], snapshot: &mut [u8], keep_to: bool) -> u64 {
let mut written = 0;
for at in (0..snapshot.len()).step_by(8) {
let span = (snapshot.len() - at).min(8);
if from[at..at + span] == snapshot[at..at + span] {
continue;
}
let there: Vec<u8> = to[at..at + span].to_vec();
for byte in at..at + span {
if from[byte] == snapshot[byte] {
continue;
}
if !keep_to || there[byte - at] == snapshot[byte] {
to[byte] = from[byte];
written += 1;
}
snapshot[byte] = from[byte];
}
}
written
}
/// A small deterministic generator (xorshift).
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n as u64) as usize
}
}
/// The page-at-a-time comparison writes, keeps and takes into the snapshot exactly the bytes the
/// byte-at-a-time one did, both ways: over lengths that end inside a block, inside an 8-byte
/// span and on either edge, with bytes changed on one side, on the other, and on both (the same
/// byte both changed, to the same and to different values), alone, in runs crossing a block's
/// edge, and over whole blocks.
#[test]
fn copied_sync_by_pages_answers_as_byte_by_byte() {
let mut rng = Rng(0x2545_F491_4F6C_DD1D);
let lengths = [
1,
7,
8,
9,
4095,
4096,
4097,
8191,
3 * 4096 + 5,
64 * 1024 + 3,
];
for round in 0..400 {
let length = lengths[round % lengths.len()];
let keep_to = round % 2 == 1;
let snapshot: Vec<u8> = (0..length).map(|_| rng.next() as u8).collect();
let (mut from, mut to) = (snapshot.clone(), snapshot.clone());
// Changes on each side: single bytes, runs that may cross a block's edge, a whole block.
for side in [&mut from, &mut to] {
for _ in 0..rng.below(12) {
let at = rng.below(length);
side[at] = side[at].wrapping_add(1 + rng.below(255) as u8);
}
if rng.below(3) == 0 {
let start = rng.below(length);
let end = (start + rng.below(9000)).min(length);
for byte in &mut side[start..end] {
*byte = rng.next() as u8;
}
}
}
// The same bytes changed on both sides, to the same value and to another.
for _ in 0..rng.below(4) {
let at = rng.below(length);
let value = snapshot[at].wrapping_add(1);
from[at] = value;
to[at] = match rng.below(2) {
0 => value,
_ => value.wrapping_add(1),
};
}
let (mut want_to, mut want_snapshot) = (to.clone(), snapshot.clone());
let want = reference_sync(&from, &mut want_to, &mut want_snapshot, keep_to);
let mut got_snapshot = snapshot.clone();
// SAFETY: three buffers of the snapshot's length.
let got = unsafe { sync(at(&mut from), at(&mut to), &mut got_snapshot, keep_to) };
assert_eq!(got, want, "round {round}: bytes written");
assert!(to == want_to, "round {round}: the bytes written");
assert!(got_snapshot == want_snapshot, "round {round}: the snapshot");
}
}
/// Where the kernel's read of the pages fails (a mapping it cannot pin), pages the process maps
/// readable are read with plain loads and copied; where a page is not mapped readable, the copy
/// is refused and nothing written; where the kernel reads them, no mapping is asked about.
@@ -341,3 +443,60 @@ impl Drop for DmaBufMapping {
assert_eq!(unmapped, 0);
}
}
/// A merge back compares only the copies its batches may have written: those whose keys a use
/// wrote, or every one where a command may have written memory no use names (`Written::all`),
/// and every one after a batch finished with no merge (`CopiedBuffers::owe`). A copy no batch
/// wrote keeps the GPU's change in the copy, unmerged, until a merge that takes it as written.
#[test]
fn a_merge_back_compares_only_the_copies_its_batches_wrote() {
let length = 4 * 4096;
let buffers = Arc::new(CopiedBuffers::default());
let counts = Counters::default();
let read = |pages: NonNull<u8>, into: &mut [u8]| {
// SAFETY: the test's pages, `into.len()` bytes.
unsafe { std::ptr::copy_nonoverlapping(pages.as_ptr(), into.as_mut_ptr(), into.len()) };
true
};
let (mut pages_x, mut pages_y) = (vec![1_u8; length], vec![2_u8; length]);
let (mut copy_x, mut copy_y) = (vec![0_u8; length], vec![0_u8; length]);
// SAFETY: the copies and the pages are the test's, of `length` bytes, live past the answers.
let x = unsafe { buffers.add_reading(at(&mut pages_x), at(&mut copy_x), length, read, false) };
// SAFETY: as above.
let y = unsafe { buffers.add_reading(at(&mut pages_y), at(&mut copy_y), length, read, false) };
let (x, y) = (x.unwrap(), y.unwrap());
let (key_x, key_y) = (ResourceKey::new(), ResourceKey::new());
x.name(key_x);
y.name(key_y);
let named = |keys: &[ResourceKey]| {
let mut written = Written::default();
for key in keys {
written.wrote(*key);
}
written
};
// The GPU writes both copies; the batch's uses wrote X alone.
copy_x[100] = 0xAA;
copy_y[100] = 0xBB;
buffers.merge_back(&counts, &named(&[key_x]));
assert_eq!(pages_x[100], 0xAA, "X merged back");
assert_eq!(pages_y[100], 2, "Y not compared");
buffers.merge_back(&counts, &named(&[key_y]));
assert_eq!(pages_y[100], 0xBB, "Y merged back once a batch wrote it");
// A command that may write memory no use names: every copy.
copy_y[200] = 0xCC;
buffers.merge_back(&counts, &Written::all());
assert_eq!(pages_y[200], 0xCC, "every copy compared");
// A batch finished with no merge: the next compares every copy, once.
copy_y[300] = 0xDD;
buffers.owe();
buffers.merge_back(&counts, &Written::default());
assert_eq!(
pages_y[300], 0xDD,
"every copy compared after a batch finished unmerged"
);
copy_y[400] = 0xEE;
buffers.merge_back(&counts, &Written::default());
assert_eq!(pages_y[400], 2, "and then none again");
drop((x, y));
}
@@ -0,0 +1,254 @@
//! The CPU cost of keeping copied host buffers coherent (`copied.rs`), on plain memory: a
//! commit's copy in and a batch completion's merge back over 680 MiB of live copies, the shape a
//! consumer's 4K desktop held (one 64 MiB surface and 2,048 copies of 308 KiB), in three cases:
//! (a) nothing changed, (b) 1% of the pages changed on each side, (c) the 64 MiB copy redrawn
//! whole by the GPU and its pages rewritten by the CPU. Each runs three times: with no log of the
//! pages' writes, each merge back taking every copy as written; with one log over every copy's
//! pages (a guest RAM's, its offsets host addresses, [`BenchLog`]) told of each CPU write, as a
//! consumer's dirty log would be, likewise; and logged, each merge back taking as written only
//! the copies the GPU wrote, as their command buffers' uses would name them (`Written`). Each
//! prints its median over its runs (`COPIED-BENCH`). Ignored: run it in release,
//! `cargo test --release -p metal2vulkan-runtime --lib copied_bench -- --ignored --nocapture`.
use crate::copied::{CopiedBuffers, Written};
use crate::dirty_pages::{hook, DirtySource, DirtyTally, PagesLog};
use crate::resource::ResourceKey;
use crate::work_counts::Counters;
use crate::{DirtyPages, DirtyStamp};
use std::num::NonZeroU64;
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
const PAGE: usize = 4096;
const BIG: usize = 64 << 20;
const SMALL: usize = 77 * PAGE;
const SMALLS: usize = 2048;
const RUNS: usize = 7;
/// One copy: the caller's pages and the copy, both the bench's own.
struct Pair {
pages: Vec<u8>,
copy: Vec<u8>,
}
/// A small deterministic generator (xorshift).
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
/// A log of every write it is told of, by host address, in stamp order: a stamp is published
/// once asked.
#[derive(Default)]
struct BenchLog {
next: AtomicU64,
writes: Mutex<Vec<(u64, Range<u64>, u64)>>,
}
impl BenchLog {
fn told(&self, range: Range<u64>, writer: u64) {
let stamp = self.next.fetch_add(1, Ordering::SeqCst) + 1;
self.writes.lock().unwrap().push((stamp, range, writer));
}
/// The writes stamped later than `since`, but `except`'s.
fn since(&self, since: DirtyStamp, except: Option<u64>, out: &mut Vec<Range<u64>>) {
let writes = self.writes.lock().unwrap();
let from = writes.partition_point(|w| w.0 <= since.0);
let later = writes[from..].iter().filter(|w| Some(w.2) != except);
out.extend(later.map(|w| w.1.clone()));
}
}
impl DirtyPages for BenchLog {
type Watch = ();
fn watch(&self, _range: Range<u64>) {}
fn request(&self) -> DirtyStamp {
DirtyStamp(self.next.fetch_add(1, Ordering::SeqCst) + 1)
}
fn wait(&self, _stamp: DirtyStamp) -> bool {
true
}
fn changed(&self, since: DirtyStamp, out: &mut Vec<Range<u64>>) {
self.since(since, None, out);
}
fn wrote(&self, range: Range<u64>) {
self.told(range, 0);
}
fn wrote_as(&self, range: Range<u64>, writer: NonZeroU64) {
self.told(range, writer.get());
}
fn changed_except(&self, since: DirtyStamp, writer: NonZeroU64, out: &mut Vec<Range<u64>>) {
self.since(since, Some(writer.get()), out);
}
}
fn median(mut times: Vec<f64>) -> f64 {
times.sort_by(f64::total_cmp);
times[times.len() / 2]
}
/// A change of one side of the pairs, telling `tell` the host addresses of the pages it wrote:
/// the pairs it changed.
type Change<'a> = &'a mut dyn FnMut(&mut [Pair], &mut Rng, &dyn Fn(Range<u64>)) -> Vec<usize>;
#[test]
#[ignore = "a release-mode benchmark"]
fn copied_bench() {
for (logged, named) in [(false, false), (true, false), (true, true)] {
bench(logged, named);
}
}
/// The three cases over copies whose pages are `logged` or not, their merges back taking as
/// written only the copies the GPU changed where `named`, else every copy.
fn bench(logged: bool, named: bool) {
let buffers = Arc::new(CopiedBuffers::default());
let (counts, tally) = (Counters::default(), DirtyTally::default());
let log = Arc::new(BenchLog::default());
let source = DirtySource::new(hook(Arc::clone(&log)), 0);
let mut pairs: Vec<Pair> = std::iter::once(BIG)
.chain(std::iter::repeat_n(SMALL, SMALLS))
.enumerate()
.map(|(i, length)| {
let pages: Vec<u8> = (0..length).map(|b| (b ^ i) as u8).collect();
Pair {
copy: vec![0; length],
pages,
}
})
.collect();
let total: usize = pairs.iter().map(|pair| pair.pages.len()).sum();
let mut kept = Vec::new();
let keys: Vec<ResourceKey> = pairs.iter().map(|_| ResourceKey::new()).collect();
for (pair, key) in pairs.iter_mut().zip(&keys) {
let pages = NonNull::new(pair.pages.as_mut_ptr()).unwrap();
let copy = NonNull::new(pair.copy.as_mut_ptr()).unwrap();
let read = |from: NonNull<u8>, into: &mut [u8]| {
// SAFETY: the pair's pages, `into.len()` bytes.
unsafe { std::ptr::copy_nonoverlapping(from.as_ptr(), into.as_mut_ptr(), into.len()) };
true
};
let length = pair.pages.len();
// SAFETY: both are the pair's own, live while the bench runs.
let copied = unsafe { buffers.add_reading(pages, copy, length, read, false) }.unwrap();
if logged {
let at = pages.as_ptr() as u64;
let pages_log = PagesLog::new((at, length as u64), Some(&source), None).unwrap();
copied.set_log(&pages_log);
}
copied.name(*key);
kept.push(copied);
}
let written = |changed: &[usize]| match named {
true => {
let mut written = Written::default();
for &pair in changed {
written.wrote(keys[pair]);
}
written
}
false => Written::all(),
};
let tell = |range: Range<u64>| log.told(range, 0);
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
let total_pages = total / PAGE;
let name = match (logged, named) {
(false, _) => "no log",
(true, false) => "logged",
(true, true) => "logged, named",
};
let mut report = |case: &str, change_cpu: Change<'_>, change_gpu: Change<'_>| {
let (mut ins, mut backs) = (Vec::new(), Vec::new());
for _ in 0..RUNS {
change_cpu(&mut pairs, &mut rng, &tell);
let started = Instant::now();
buffers.copy_in(&counts, &tally);
ins.push(started.elapsed().as_secs_f64() * 1e3);
let changed = change_gpu(&mut pairs, &mut rng, &|_| {});
let written = written(&changed);
let started = Instant::now();
buffers.merge_back(&counts, &written);
backs.push(started.elapsed().as_secs_f64() * 1e3);
}
eprintln!(
"COPIED-BENCH {name} {case}: {} copies, {} MiB: copy in {:.2} ms, merge back {:.2} ms (median of {RUNS})",
pairs.len(),
total >> 20,
median(ins),
median(backs),
);
};
// Every byte agrees first, and the logged copies hold a stamp.
buffers.copy_in(&counts, &tally);
buffers.merge_back(&counts, &Written::all());
buffers.copy_in(&counts, &tally);
let mut nothing = |_: &mut [Pair], _: &mut Rng, _: &dyn Fn(Range<u64>)| Vec::new();
let mut nothing_either = |_: &mut [Pair], _: &mut Rng, _: &dyn Fn(Range<u64>)| Vec::new();
report("(a) nothing changed", &mut nothing, &mut nothing_either);
// One byte in each of 1% of the pages, on each side.
let percent = |side: bool| {
move |pairs: &mut [Pair], rng: &mut Rng, tell: &dyn Fn(Range<u64>)| {
let mut changed = Vec::new();
for _ in 0..total_pages / 100 {
let mut page = (rng.next() as usize) % total_pages;
for (index, pair) in pairs.iter_mut().enumerate() {
let bytes = match side {
true => &mut pair.pages,
false => &mut pair.copy,
};
let pages = bytes.len() / PAGE;
if page < pages {
let at = page * PAGE + (rng.next() as usize) % PAGE;
bytes[at] = bytes[at].wrapping_add(1);
let start = bytes.as_ptr() as u64 + (page * PAGE) as u64;
tell(start..start + PAGE as u64);
changed.push(index);
break;
}
page -= pages;
}
}
changed
}
};
report(
"(b) 1% of pages changed",
&mut percent(true),
&mut percent(false),
);
// The 64 MiB copy redrawn whole, its pages rewritten whole.
let whole = |side: bool| {
move |pairs: &mut [Pair], rng: &mut Rng, tell: &dyn Fn(Range<u64>)| {
let value = rng.next() as u8;
let bytes = match side {
true => &mut pairs[0].pages,
false => &mut pairs[0].copy,
};
for byte in bytes.iter_mut() {
*byte = byte.wrapping_add(value | 1);
}
let start = bytes.as_ptr() as u64;
tell(start..start + bytes.len() as u64);
vec![0]
}
};
report("(c) one copy redrawn", &mut whole(true), &mut whole(false));
drop(kept);
}
@@ -1773,3 +1773,90 @@ fn copied_rebind_over_read_only_pages_whose_admitted_import_fails_drops_the_gpu_
drops_the_gpu_s_writes(&device, (&buffer, 0), &second);
eprintln!("COPIED-READ-ONLY-ADMITTED: the source's import failed, and the copy was made");
}
/// A batch that only reads a copied buffer leaves it uncompared at its merge back
/// (`copied_merges_skipped`), and one that writes it merges it back.
#[test]
fn a_merge_back_skips_a_copy_its_batch_only_read() {
let Some((device, _)) = device() else {
return;
};
let host = Host::new(11);
let asked = Arc::default();
let buffer = host.buffer(&device, Some(gate(&asked, false)));
assert!(buffer.copied(), "the buffer is a copy");
blit(&device, |encoder| {
encoder.fill_buffer(&buffer, 0..256, 0x3C).unwrap();
});
assert_eq!(&host.bytes()[..256], &[0x3C; 256], "a write merged back");
let before = device.work_counts();
let read = gpu_bytes(&device, &buffer);
let after = device.work_counts();
assert_eq!(read, host.bytes(), "the GPU reads the pages");
let skipped = after.copied_merges_skipped - before.copied_merges_skipped;
let compared = after.copied_merges_compared - before.copied_merges_compared;
eprintln!("COPIED: a reading batch's merge back: {compared} compared, {skipped} skipped");
assert_eq!(
(compared, skipped),
(0, 1),
"the copy a batch only read is not compared"
);
drop(buffer);
}
/// A kernel's stores through a copied buffer's address loaded from memory, with no use of the
/// buffer named (the buffer reached unnamed, as a command buffer's earlier use left it), still
/// merge back into the pages: its command may write memory no use names, so every copy is
/// compared.
#[test]
fn a_write_through_an_address_no_use_names_still_merges_back() {
let Some((device, _)) = device() else {
return;
};
let host = Host::new(13);
let asked = Arc::default();
let buffer = host.buffer(&device, Some(gate(&asked, false)));
assert!(buffer.copied(), "the buffer is a copy");
// A command buffer's use of it: the device's live buffers list it, reached unnamed from here.
let _ = gpu_bytes(&device, &buffer);
let function = super::encoder_holds::library(&device, "engine/ob2_loaded_pointer.ll")
.new_function_with_name("ob2_loaded_pointer")
.unwrap();
let state = device
.new_compute_pipeline_state_with_function(&function, &crate::PipelineOptions::default())
.unwrap();
let indices: Vec<u8> = (0..16u32).flat_map(u32::to_le_bytes).collect();
let out = device.new_buffer(32, ResourceOptions::shared()).unwrap();
let before = device.work_counts();
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&state).unwrap();
encoder.set_bytes(&indices, 0).unwrap();
encoder
.set_bytes(&buffer.gpu_address().0.to_le_bytes(), 1)
.unwrap();
encoder.set_buffer(Some(&out), 0, 2).unwrap();
encoder
.dispatch_threads(crate::Size::new(8, 1, 1), crate::Size::new(8, 1, 1))
.unwrap();
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
let after = device.work_counts();
let words: Vec<u32> = (host.bytes()[32..64].as_chunks::<4>().0.iter())
.map(|word| u32::from_le_bytes(*word))
.collect();
let stored: Vec<u32> = (0..8).map(|t| 0xB000_0000 | t).collect();
eprintln!(
"COPIED: the unnamed write's merge back: {} compared, {} skipped",
after.copied_merges_compared - before.copied_merges_compared,
after.copied_merges_skipped - before.copied_merges_skipped,
);
assert_eq!(
words, stored,
"the stores through the address are in the pages"
);
drop((buffer, out, state, queue));
}
@@ -0,0 +1,520 @@
//! Copied host buffers over pages whose memory came with a log of the writes to them
//! (`copied.rs`, `dirty_pages.rs`), on plain memory:
//!
//! - a merge back reports the bytes it wrote to the pages' logs as the copy's own writes, a block
//! at a time, through both the memory's own log and its guest RAM's (whose offsets are host
//! addresses, through the runs of the RAM the pages are); a merge that writes nothing, and one
//! whose writes are dropped, report nothing;
//! - a copy in compares only the pages the log reports written since the copy's last, after a
//! first that compares every byte, and every byte where the log cannot say, and the bytes no
//! log keeps at every one; one stamp a copy in serves every copy;
//! - a copy takes another copy's merge back over the same pages, and not its own;
//! - a CPU write to a byte the GPU did not change, racing both ways, survives, logged or not.
//!
//! The log is the test's own ([`TestLog`]): it reports the writes it is told of, and lies by
//! leaving out one it is not told, so a block it leaves out shows whether a copy in took it.
use crate::copied::{Copied, CopiedBuffers, Written, SYNC_BLOCK};
use crate::dirty_pages::{hook, DirtySource, DirtyTally, PagesLog};
use crate::work_counts::Counters;
use crate::{DirtyPages, DirtyStamp};
use std::num::NonZeroU64;
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
const BLOCK: u64 = SYNC_BLOCK as u64;
/// A test's log: every write it is told of, stamped later than every stamp asked before, with
/// its writer (0 the consumer's); the pages it was asked to watch.
#[derive(Default)]
pub(super) struct TestLog {
next: AtomicU64,
pub(super) writes: Mutex<Vec<(u64, Range<u64>, u64)>>,
/// The wait answers `false` while set.
pub(super) unanswered: AtomicBool,
pub(super) waits: AtomicU64,
pub(super) watched: Mutex<Vec<Range<u64>>>,
/// The questions `changed` and `changed_except` were asked.
pub(super) asked: AtomicU64,
pub(super) asked_except: AtomicU64,
}
impl TestLog {
/// A write of `range` by `writer`, stamped now.
pub(super) fn told(&self, range: Range<u64>, writer: u64) {
let stamp = self.next.fetch_add(1, Ordering::SeqCst) + 1;
self.writes.lock().unwrap().push((stamp, range, writer));
}
/// The writes reported by writers other than 0 (the runtime's named ones), in order.
pub(super) fn named(&self) -> Vec<(Range<u64>, u64)> {
(self.writes.lock().unwrap().iter())
.filter(|w| w.2 != 0)
.map(|w| (w.1.clone(), w.2))
.collect()
}
}
impl DirtyPages for TestLog {
type Watch = ();
fn watch(&self, range: Range<u64>) {
self.watched.lock().unwrap().push(range);
}
fn request(&self) -> DirtyStamp {
DirtyStamp(self.next.fetch_add(1, Ordering::SeqCst) + 1)
}
fn wait(&self, _stamp: DirtyStamp) -> bool {
self.waits.fetch_add(1, Ordering::SeqCst);
!self.unanswered.load(Ordering::SeqCst)
}
fn changed(&self, since: DirtyStamp, out: &mut Vec<Range<u64>>) {
self.asked.fetch_add(1, Ordering::SeqCst);
let writes = self.writes.lock().unwrap();
out.extend(
(writes.iter())
.filter(|w| w.0 > since.0)
.map(|w| w.1.clone()),
);
}
fn wrote(&self, range: Range<u64>) {
self.told(range, 0);
}
fn wrote_as(&self, range: Range<u64>, writer: NonZeroU64) {
self.told(range, writer.get());
}
fn changed_except(&self, since: DirtyStamp, writer: NonZeroU64, out: &mut Vec<Range<u64>>) {
self.asked_except.fetch_add(1, Ordering::SeqCst);
let writes = self.writes.lock().unwrap();
let changed = (writes.iter()).filter(|w| w.0 > since.0 && w.2 != writer.get());
out.extend(changed.map(|w| w.1.clone()));
}
}
/// `bytes` as a pointer the comparisons read or write.
pub(super) fn at(bytes: &mut [u8]) -> NonNull<u8> {
NonNull::new(bytes.as_mut_ptr()).unwrap()
}
/// A plain read of the pages, the copy's first.
pub(super) fn read(from: NonNull<u8>, into: &mut [u8]) -> bool {
// SAFETY: the tests' pages are `into.len()` bytes of plain memory.
unsafe { std::ptr::copy_nonoverlapping(from.as_ptr(), into.as_mut_ptr(), into.len()) };
true
}
/// A merge back reports, to the memory's own log and to the guest RAM's, each block it wrote a
/// byte of, as the copy's own writer (one no other copy has), and no block it wrote nothing of:
/// not one whose only changed byte the CPU changed too, and nothing of a copy whose writes are
/// dropped.
#[test]
fn a_copy_s_merge_back_reports_the_blocks_it_wrote_as_its_own() {
let length = 5 * BLOCK as usize + 100;
let mut pages: Vec<u8> = (0..length).map(|i| (i * 3 + 1) as u8).collect();
let mut copy = vec![0_u8; length];
let pointer = pages.as_ptr() as u64;
let own = Arc::new(TestLog::default());
let ram = Arc::new(TestLog::default());
let own_source = DirtySource::new(hook(Arc::clone(&own)), pointer);
let ram_source = DirtySource::new(hook(Arc::clone(&ram)), 0);
// The import window: two runs of guest RAM (host addresses), the bytes 0x123 into it.
let (first, second) = (0x10_0000..0x10_2000, 0x40_0000..0x40_6000);
let window = [first.clone(), second.clone()];
let log = PagesLog::new(
(pointer, length as u64),
Some(&own_source),
Some((&ram_source, &window[..], 0x123)),
)
.unwrap();
let buffers = Arc::new(CopiedBuffers::default());
let counts = Counters::default();
// SAFETY: the copy and the pages are the test's, of `length` bytes, live past the answer.
let copied = unsafe { buffers.add_reading(at(&mut pages), at(&mut copy), length, read, false) };
let copied = copied.unwrap();
copied.set_log(&log);
// The GPU writes a byte of blocks 0, 1, 2 and 5 (the last, short); in block 3 it writes a
// byte the CPU wrote too since, which the merge keeps the CPU's of, writing nothing there.
copy[10] ^= 0xFF;
copy[BLOCK as usize + 1] ^= 0xFF;
copy[2 * BLOCK as usize + 5] ^= 0xFF;
copy[length - 1] ^= 0xFF;
copy[3 * BLOCK as usize + 7] ^= 0xFF;
pages[3 * BLOCK as usize + 7] ^= 0x0F;
buffers.merge_back(&counts, &Written::all());
assert_eq!(pages[10], copy[10], "merged back");
let own_named = own.named();
let writer = own_named.first().map(|w| w.1).expect("reported");
// Blocks 0 to 2 are one run of blocks.
let blocks = [0..3 * BLOCK, 5 * BLOCK..length as u64];
let want: Vec<(Range<u64>, u64)> = blocks.iter().map(|b| (b.clone(), writer)).collect();
assert_eq!(
own_named, want,
"the memory's log: each block written, the copy's writer"
);
// The guest RAM's log: the same blocks as host addresses, through the runs; the window's
// bytes 0..0x2000 are the first run, the rest the second, so block 1 lies in both.
let host = |byte: u64| match byte + 0x123 {
w if w < 0x2000 => first.start + w,
w => second.start + (w - 0x2000),
};
let ram_named = ram.named();
let want_ram: Vec<(Range<u64>, u64)> = vec![
(host(0)..first.end, writer),
(second.start..host(3 * BLOCK - 1) + 1, writer),
(host(5 * BLOCK)..host(length as u64 - 1) + 1, writer),
];
assert_eq!(ram_named, want_ram, "the RAM's log, through its runs");
// A merge that writes nothing reports nothing.
buffers.merge_back(&counts, &Written::all());
assert_eq!(own.named().len(), 2);
// Another copy of the same pages is another writer.
let mut other_copy = vec![0_u8; length];
// SAFETY: as above.
let other =
unsafe { buffers.add_reading(at(&mut pages), at(&mut other_copy), length, read, false) };
let other = other.unwrap();
other.set_log(&log);
other_copy[0] ^= 0xFF;
buffers.merge_back(&counts, &Written::all());
let last = own.named().last().cloned().unwrap();
assert_eq!(last.0, 0..BLOCK);
assert_ne!(last.1, writer, "a writer of its own");
drop((copied, other));
// A copy whose GPU writes are dropped writes nothing to the pages, and reports nothing.
let mut dropping_copy = vec![0_u8; length];
// SAFETY: as above.
let dropping =
unsafe { buffers.add_reading(at(&mut pages), at(&mut dropping_copy), length, read, true) };
let dropping = dropping.unwrap();
dropping.set_log(&log);
let before = (
own.writes.lock().unwrap().len(),
ram.writes.lock().unwrap().len(),
);
dropping_copy[50] ^= 0xFF;
buffers.merge_back(&counts, &Written::all());
let after = (
own.writes.lock().unwrap().len(),
ram.writes.lock().unwrap().len(),
);
assert_eq!(before, after, "dropped writes reach no page and no log");
drop(dropping);
}
/// The test's pages and a copy of them, of `blocks` blocks, under `buffers`, logged by `log`: the
/// pages' bytes all different from the copy's start.
struct Pair {
pages: Vec<u8>,
copy: Vec<u8>,
}
impl Pair {
fn new(blocks: usize) -> Pair {
let length = blocks * BLOCK as usize;
Pair {
pages: (0..length).map(|i| (i * 7 + 3) as u8).collect(),
copy: vec![0; length],
}
}
/// Its copy, registered in `buffers`, logged by `log` where given.
fn copied(&mut self, buffers: &Arc<CopiedBuffers>, log: Option<&Arc<PagesLog>>) -> Copied {
let length = self.pages.len();
// SAFETY: the copy and the pages are the test's, of `length` bytes, live past the answer
// (each test drops the answer first).
let copied = unsafe {
buffers.add_reading(at(&mut self.pages), at(&mut self.copy), length, read, false)
};
let copied = copied.unwrap();
if let Some(log) = log {
copied.set_log(log);
}
copied
}
}
/// A log of `length` bytes at `pointer`: their memory's own, `log`.
fn own_log(log: &Arc<TestLog>, pointer: u64, length: usize) -> Arc<PagesLog> {
let source = DirtySource::new(hook(Arc::clone(log)), pointer);
PagesLog::new((pointer, length as u64), Some(&source), None).unwrap()
}
/// A logged copy's first copy in compares every byte (a write before its watch began included);
/// each later one compares only the blocks the log reports written since: a block the log was
/// told of is taken, one it was not told of is not (the log lies, so the copy in shows it asked).
/// A wait the log answers `false` makes the copy in compare every byte, and the next one too.
#[test]
fn a_logged_copy_in_compares_only_the_pages_the_log_reports() {
let mut pair = Pair::new(6);
let pointer = pair.pages.as_ptr() as u64;
let own = Arc::new(TestLog::default());
let log = own_log(&own, pointer, pair.pages.len());
let buffers = Arc::new(CopiedBuffers::default());
let (counts, tally) = (Counters::default(), DirtyTally::default());
let copied = pair.copied(&buffers, Some(&log));
assert_eq!(
*own.watched.lock().unwrap(),
vec![0..6 * BLOCK],
"its pages watched"
);
let (b, untold) = (BLOCK as usize, 3 * BLOCK as usize + 9);
// Written before the first copy in, told to no log.
pair.pages[5 * b + 3] ^= 0xFF;
buffers.copy_in(&counts, &tally);
assert_eq!(
pair.copy[5 * b + 3],
pair.pages[5 * b + 3],
"the first compares every byte"
);
// A byte of block 1, told; one of block 3, not told.
pair.pages[b + 9] ^= 0xFF;
own.told(BLOCK..2 * BLOCK, 0);
pair.pages[untold] ^= 0xFF;
buffers.copy_in(&counts, &tally);
assert_eq!(pair.copy[b + 9], pair.pages[b + 9], "the told block taken");
assert_ne!(
pair.copy[untold], pair.pages[untold],
"the block the log left out not compared"
);
// The log cannot say: every byte compared, and again at the next copy in, which has no
// stamp to count on.
own.unanswered.store(true, Ordering::SeqCst);
buffers.copy_in(&counts, &tally);
assert_eq!(pair.copy[untold], pair.pages[untold], "every byte compared");
own.unanswered.store(false, Ordering::SeqCst);
pair.pages[untold] ^= 0xFF;
buffers.copy_in(&counts, &tally);
assert_eq!(
pair.copy[untold], pair.pages[untold],
"every byte compared again"
);
pair.pages[untold] ^= 0xFF;
buffers.copy_in(&counts, &tally);
assert_ne!(pair.copy[untold], pair.pages[untold], "gated again");
drop(copied);
}
/// One copy in of many copies over one log asks one stamp and makes at most one wait, and asks
/// the log which pages changed since that stamp once for all of them.
#[test]
fn one_stamp_and_one_question_serve_every_copy_of_a_copy_in() {
let own = Arc::new(TestLog::default());
let buffers = Arc::new(CopiedBuffers::default());
let (counts, tally) = (Counters::default(), DirtyTally::default());
let mut pairs: Vec<Pair> = (0..8).map(|_| Pair::new(2)).collect();
let copies: Vec<Copied> = (pairs.iter_mut())
.map(|pair| {
let log = own_log(&own, pair.pages.as_ptr() as u64, pair.pages.len());
pair.copied(&buffers, Some(&log))
})
.collect();
// Each memory its own source over one log: the stamps are the log's.
for round in 0..3 {
let stamps = tally.stamps.load(Ordering::SeqCst);
let asked = own.asked.load(Ordering::SeqCst);
buffers.copy_in(&counts, &tally);
let stamps = tally.stamps.load(Ordering::SeqCst) - stamps;
let asked = own.asked.load(Ordering::SeqCst) - asked;
// Eight memories, each its own source: one stamp of each, the question once each.
assert_eq!(stamps, 8, "round {round}: one stamp a source");
let questions = if round == 0 { 0 } else { 8 };
assert_eq!(
asked, questions,
"round {round}: one question a source and stamp"
);
}
drop(copies);
// One source for every copy (a guest RAM's log, offsets host addresses): one stamp, one
// question, for all of them.
let ram = Arc::new(TestLog::default());
let source = DirtySource::new(hook(Arc::clone(&ram)), 0);
let copies: Vec<Copied> = (pairs.iter_mut())
.map(|pair| {
let (start, length) = (pair.pages.as_ptr() as u64, pair.pages.len() as u64);
let log = PagesLog::new((start, length), Some(&source), None).unwrap();
pair.copied(&buffers, Some(&log))
})
.collect();
for round in 0..3 {
let stamps = tally.stamps.load(Ordering::SeqCst);
let asked = ram.asked.load(Ordering::SeqCst);
buffers.copy_in(&counts, &tally);
assert_eq!(tally.stamps.load(Ordering::SeqCst) - stamps, 1, "one stamp");
let questions = if round == 0 { 0 } else { 1 };
assert_eq!(
ram.asked.load(Ordering::SeqCst) - asked,
questions,
"one question"
);
}
drop(copies);
}
/// Two copies over the same pages, under one log: the GPU's write into one, merged back, is
/// reported as its writer's, so the other's next copy in takes it. The merging copy's own next
/// copy in takes the pages every writer wrote, asked once for every copy, after a small merge,
/// and asks apart for every writer's pages but its own (`changed_except`) after a merge of
/// `ASKS_APART` bytes or more.
#[test]
fn a_copy_takes_another_copy_s_merge_back_over_the_same_pages() {
// 2 MiB: room for a merge of 1 MiB, a byte in each of 256 blocks.
let mut first = Pair::new(512);
let pointer = first.pages.as_ptr() as u64;
let length = first.pages.len();
let own = Arc::new(TestLog::default());
let log = own_log(&own, pointer, length);
let buffers = Arc::new(CopiedBuffers::default());
let (counts, tally) = (Counters::default(), DirtyTally::default());
let one = first.copied(&buffers, Some(&log));
// The second copy is of the same pages.
let mut second_copy = vec![0_u8; length];
// SAFETY: as in `Pair::copied`.
let second = unsafe {
buffers.add_reading(
at(&mut first.pages),
at(&mut second_copy),
length,
read,
false,
)
};
let second = second.unwrap();
second.set_log(&log);
buffers.copy_in(&counts, &tally);
for blocks in [1_usize, 256] {
// The GPU writes a byte of each of `blocks` blocks of the first copy; the completion
// merges them back.
let written: Vec<usize> = (0..blocks)
.map(|b| (b * 2 + 1) * BLOCK as usize + 17)
.collect();
for &byte in &written {
first.copy[byte] ^= 0xFF;
}
buffers.merge_back(&counts, &Written::all());
assert!(
written.iter().all(|&b| first.pages[b] == first.copy[b]),
"merged back"
);
let except = own.asked_except.load(Ordering::SeqCst);
buffers.copy_in(&counts, &tally);
assert!(
written.iter().all(|&b| second_copy[b] == first.pages[b]),
"{blocks} blocks: the other copy took the merge"
);
let apart = u64::from(blocks * BLOCK as usize >= 1 << 20);
assert_eq!(
own.asked_except.load(Ordering::SeqCst) - except,
apart,
"{blocks} blocks: asked apart only after a merge of a MiB or more"
);
}
drop((one, second));
}
/// Bytes no log keeps the writes to (a guest RAM's log whose runs hold only the first two of a
/// copy's four blocks) are compared at every copy in, the logged ones only where written.
#[test]
fn bytes_no_log_keeps_are_compared_at_every_copy_in() {
let mut pair = Pair::new(4);
let pointer = pair.pages.as_ptr() as u64;
let ram = Arc::new(TestLog::default());
let source = DirtySource::new(hook(Arc::clone(&ram)), 0);
// The window: one run of host addresses holding the copy's first two blocks.
let run = pointer..pointer + 2 * BLOCK;
let window = std::slice::from_ref(&run);
let log = PagesLog::new((pointer, 4 * BLOCK), None, Some((&source, window, 0))).unwrap();
let buffers = Arc::new(CopiedBuffers::default());
let (counts, tally) = (Counters::default(), DirtyTally::default());
let copied = pair.copied(&buffers, Some(&log));
buffers.copy_in(&counts, &tally);
let (logged, unlogged) = (BLOCK as usize + 5, 3 * BLOCK as usize + 5);
pair.pages[logged] ^= 0xFF;
pair.pages[unlogged] ^= 0xFF;
buffers.copy_in(&counts, &tally);
assert_ne!(
pair.copy[logged], pair.pages[logged],
"a logged block the log left out"
);
assert_eq!(
pair.copy[unlogged], pair.pages[unlogged],
"the unlogged block compared"
);
drop(copied);
}
/// A CPU thread writing one byte of the pages over and over, which the GPU never writes, while
/// copies in and merges back run, the GPU writing the bytes around it: the byte ends holding the
/// CPU's last write in the pages, and in the copy after the next copy in, both with the CPU's
/// writes told to a log and with no log.
#[test]
fn a_cpu_write_the_gpu_did_not_make_survives_both_ways_logged_or_not() {
for logged in [false, true] {
let mut pair = Pair::new(2);
let pointer = pair.pages.as_ptr() as u64;
let length = pair.pages.len();
let own = Arc::new(TestLog::default());
let log = own_log(&own, pointer, length);
let buffers = Arc::new(CopiedBuffers::default());
let (counts, tally) = (Counters::default(), DirtyTally::default());
let copied = pair.copied(&buffers, logged.then_some(&log));
buffers.copy_in(&counts, &tally);
let cpu_byte = BLOCK as usize + 100;
let stop = Arc::new(AtomicBool::new(false));
let pages = pair.pages.as_mut_ptr() as usize;
let writer = {
let (stop, own) = (Arc::clone(&stop), Arc::clone(&own));
std::thread::spawn(move || {
let mut value = 0u8;
while !stop.load(Ordering::SeqCst) {
value = value.wrapping_add(1) | 1;
// SAFETY: a byte of the test's pages, which outlive the thread (joined
// below); the runtime's reads of it race as the CPU's and the GPU's do.
unsafe { std::ptr::write_volatile((pages as *mut u8).add(cpu_byte), value) };
own.told(BLOCK..2 * BLOCK, 0);
}
value
})
};
let copy = pair.copy.as_mut_ptr();
for round in 0..2000_usize {
// The GPU writes the bytes beside the CPU's (in the copy), and never the CPU's.
for at in [cpu_byte - 1, cpu_byte + 1, round % (BLOCK as usize)] {
// SAFETY: bytes of the test's copy.
unsafe { *copy.add(at) = (*copy.add(at)).wrapping_add(1) };
}
buffers.merge_back(&counts, &Written::all());
buffers.copy_in(&counts, &tally);
}
stop.store(true, Ordering::SeqCst);
let last = writer.join().unwrap();
buffers.copy_in(&counts, &tally);
assert_eq!(
pair.pages[cpu_byte], last,
"logged {logged}: the pages keep the CPU's"
);
assert_eq!(
pair.copy[cpu_byte], last,
"logged {logged}: the copy takes the CPU's"
);
// The GPU's bytes beside it reached the pages.
assert_eq!(
pair.pages[cpu_byte - 1],
pair.copy[cpu_byte - 1],
"logged {logged}"
);
assert_eq!(
pair.pages[cpu_byte + 1],
pair.copy[cpu_byte + 1],
"logged {logged}"
);
drop(copied);
}
}
@@ -0,0 +1,368 @@
//! Host pages whose memory came with a log of the writes to them (`dirty_pages.rs`), on a device:
//! the runtime's own CPU writes into them are reported to the log, as the consumer's writer 0, so
//! every copy of the pages takes them (`DirtyPages::wrote`).
//!
//! - **A `replaceRegion` into a copied heap's shadow texture** writes the heap's bytes, the
//! caller's pages, and reports their range.
//! - **An argument encoder's write** into a no-copy buffer's bytes reports the argument's bytes.
//! - **A GPU write in place**: a blit's fill of a no-copy buffer imported in place reports the
//! bytes it filled, at the commit and again at the completion, as does one through a second
//! buffer over the same bytes, which lies in the first's import.
//!
//! And copies in that the log gates (`copied.rs`): each takes what the runtime reported.
//!
//! - **A GPU write in place, then a copy over the same pages**: a fill through a buffer imported
//! in place reaches a copied buffer over the same pages at its next commit, the copy in having
//! compared only the pages the log reported (`WorkCounts::copied_copy_in_bytes_skipped`).
//! - **A `replaceRegion` of a copied heap's texture, then a read of the heap's bytes**: the
//! heap's own copy takes the texels at the next commit.
//!
//! The log is the test's own (`copied_log::TestLog`): it records what it is told.
//!
//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind
//! of device the cfg selects. A device that imports no host memory says so and passes.
use super::blit_holds::WAIT;
use super::copied_log::TestLog;
use crate::{
Buffer, CommandQueue, Device, DeviceKind, DeviceOptions, HostMemory, ImportGate, Region,
ResourceOptions,
};
use metal2vulkan::bind::ArgumentDescriptor;
use metal2vulkan::metal::{DataType, PixelFormat, TextureUsage};
use std::alloc::Layout;
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::Arc;
/// The bytes of each host memory.
const LENGTH: usize = 64 * 1024;
/// Host memory of whole pages, zeroed, freed when dropped (after the device).
pub(super) struct Pages {
pub(super) pointer: NonNull<u8>,
layout: Layout,
}
impl Pages {
pub(super) fn new() -> Pages {
let layout = Layout::from_size_align(LENGTH, 1 << 16).unwrap();
// SAFETY: the layout's size is not zero.
let pointer = NonNull::new(unsafe { std::alloc::alloc_zeroed(layout) }).unwrap();
Pages { pointer, layout }
}
/// Its memory, logged by `log`, under a gate answering `admit` where given.
pub(super) fn memory(&self, log: &Arc<TestLog>, admit: Option<bool>) -> HostMemory {
// SAFETY: the memory outlives every object over it and the device (dropped after both),
// and only their commands and the tests' reads between command buffers use it.
let memory = unsafe { HostMemory::new(self.pointer) }.with_dirty_pages(Arc::clone(log));
match admit {
Some(answer) => memory.with_import_gate(Arc::new(move |_| answer) as ImportGate),
None => memory,
}
}
/// A no-copy buffer over all of it, logged by `log`, under a gate answering `admit`.
pub(super) fn buffer(
&self,
device: &Device,
log: &Arc<TestLog>,
admit: Option<bool>,
) -> Buffer {
let memory = self.memory(log, admit);
// SAFETY: as in `memory`.
unsafe {
device.new_buffer_with_bytes_no_copy(
memory,
LENGTH as u64,
ResourceOptions::default(),
None,
)
}
.unwrap()
}
}
impl Drop for Pages {
fn drop(&mut self) {
// SAFETY: allocated with this layout.
unsafe { std::alloc::dealloc(self.pointer.as_ptr(), self.layout) };
}
}
/// A device of the cfg's kind; `None` where it imports no host memory.
pub(super) fn device() -> Option<Device> {
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
false => vec![
DeviceKind::Discrete,
DeviceKind::Integrated,
DeviceKind::Virtual,
],
},
..DeviceOptions::default()
};
let device = Device::system_default_with(&options).unwrap();
if device.shared().host_import.is_err() {
eprintln!("COPIED-LOG: the device imports no host memory here; nothing to test");
return None;
}
Some(device)
}
/// The writes `log` was told of by writer 0 (the consumer's, and the runtime's own CPU writes)
/// since it held `before` writes.
fn plain_writes(log: &TestLog, before: usize) -> Vec<Range<u64>> {
(log.writes.lock().unwrap()[before..].iter())
.filter(|w| w.2 == 0)
.map(|w| w.1.clone())
.collect()
}
/// A `replaceRegion` into a texture of a copied no-copy heap (a shadow of the heap's bytes, the
/// caller's pages) reports the heap's bytes it wrote, inside the texture's span, to the heap's
/// memory's log.
#[test]
fn a_replace_region_into_a_copied_heap_s_shadow_texture_is_reported() {
let pages = Pages::new();
let Some(device) = device() else {
return;
};
let log = Arc::new(TestLog::default());
let descriptor = crate::HeapDescriptor::new(
crate::HeapType::Placement,
LENGTH as u64,
ResourceOptions::default(),
);
let memory = pages.memory(&log, Some(false));
// SAFETY: as in `Pages::memory`.
let heap = unsafe { device.new_heap_with_bytes_no_copy(memory, &descriptor, None, None) };
let heap = heap.unwrap();
assert!(
heap.bytes().is_some_and(Buffer::copied),
"the heap is a copy"
);
let mut texture = crate::TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 16, 16, false);
texture.usage = TextureUsage::SHADER_READ;
texture.resource_options = ResourceOptions::default();
let span = device.heap_texture_size_and_align(&texture).unwrap().size;
let texture = heap.new_texture_at_offset(&texture, 0).unwrap();
let before = log.writes.lock().unwrap().len();
let region = Region::new_2d(0, 0, 16, 16);
texture
.replace_region(region, 0, 0, &[0x5C; 16 * 16 * 4], 16 * 4, 0)
.unwrap();
let reported = plain_writes(&log, before);
assert_eq!(reported.len(), 1, "one report: {reported:?}");
let range = reported[0].clone();
assert!(
range.start < range.end && range.end <= span,
"inside the span: {range:?}"
);
assert!(
range.end - range.start >= 16 * 16 * 4,
"every texel: {range:?}"
);
drop((texture, heap));
}
/// An argument encoder's write into a no-copy buffer's bytes reports the argument's bytes to the
/// buffer's memory's log; a write into a buffer of the device's own reports nothing.
#[test]
fn an_argument_encoder_s_write_into_logged_pages_is_reported() {
let pages = Pages::new();
let Some(device) = device() else {
return;
};
let log = Arc::new(TestLog::default());
let buffer = pages.buffer(&device, &log, None);
let own = device.new_buffer(4096, ResourceOptions::shared()).unwrap();
let mut encoder = device
.new_argument_encoder_with_arguments(&[ArgumentDescriptor::new(DataType::Pointer, 0)])
.unwrap();
encoder.set_argument_buffer(Some(&buffer), 256).unwrap();
let before = log.writes.lock().unwrap().len();
encoder.set_buffer(Some(&own), 0, 0).unwrap();
assert_eq!(
plain_writes(&log, before),
vec![256..264],
"the pointer's bytes"
);
encoder.set_argument_buffer(Some(&own), 0).unwrap();
let before = log.writes.lock().unwrap().len();
encoder.set_buffer(Some(&own), 0, 0).unwrap();
assert!(
plain_writes(&log, before).is_empty(),
"nothing for a buffer of its own"
);
drop((encoder, buffer, own));
}
/// Copy `length` bytes of `source` into a buffer of the device's own through `queue`, to
/// completion: those bytes.
fn read_back(queue: &CommandQueue, source: &Buffer, length: u64) -> Vec<u8> {
let device = queue.device();
let into = device
.new_buffer(length, ResourceOptions::shared())
.unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.copy_from_buffer_to_buffer(source, 0, &into, 0, length)
.unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
assert!(command_buffer.wait_until_completed_for(WAIT).is_ok());
let contents = into.contents().unwrap();
// SAFETY: the buffer's `length` bytes, which no command uses now.
unsafe { std::slice::from_raw_parts(contents.as_ptr(), length as usize) }.to_vec()
}
/// Fill `range` of `target` through `queue`, to completion: the writes `log` was told of by
/// writer 0 meanwhile.
fn filled(
queue: &CommandQueue,
log: &TestLog,
target: &Buffer,
range: Range<u64>,
) -> Vec<Range<u64>> {
let before = log.writes.lock().unwrap().len();
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
blit.fill_buffer(target, range, 0x7E).unwrap();
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
assert!(command_buffer.wait_until_completed_for(WAIT).is_ok());
plain_writes(log, before)
}
/// A GPU write through a no-copy buffer imported in place, over logged pages, reports the bytes
/// it wrote to the memory's log, as writer 0, at the commit and again at the completion: a
/// blit's fill of the buffer, and one through a second buffer over the same bytes, which lies in
/// the first's import. A fill of a buffer of the device's own reports nothing.
#[test]
fn a_gpu_write_into_logged_pages_imported_in_place_is_reported() {
let pages = Pages::new();
let Some(device) = device() else {
return;
};
let log = Arc::new(TestLog::default());
let first = pages.buffer(&device, &log, None);
if first.copied() {
eprintln!("COPIED-LOG: the device copies the pages; no import in place to test");
return;
}
let live = device.work_counts().host_imports_live;
let second = pages.buffer(&device, &log, None);
let shares = device.work_counts().host_imports_live == live;
eprintln!("COPIED-LOG: the second buffer lies in the first's import: {shares}");
let own = device.new_buffer(4096, ResourceOptions::shared()).unwrap();
let queue = device.new_command_queue().unwrap();
for (target, range) in [(&first, 4096..8192), (&second, 12288..16384)] {
let reported = filled(&queue, &log, target, range.clone());
assert!(
reported.len() >= 2 && reported.iter().all(|r| *r == range),
"the fill's bytes, at the commit and the completion: {reported:?}"
);
// SAFETY: the command buffer completed; the bytes are the pages'.
let byte = unsafe { *pages.pointer.as_ptr().add(range.start as usize) };
assert_eq!(byte, 0x7E, "filled in place");
}
assert!(
filled(&queue, &log, &own, 0..4096).is_empty(),
"nothing for a buffer of the device's own"
);
drop((first, second, own, queue));
}
/// A fill through a no-copy buffer imported in place over logged pages reaches a copied buffer
/// over the first half of the same pages (its import refused, so a copy whose copy in the log
/// gates): read back after the fill, the copy holds the filled bytes, though its copies in
/// compare only the pages the log reports (`copied_copy_in_bytes_skipped` grows).
#[test]
fn a_gpu_write_in_place_reaches_a_logged_copy_of_the_same_pages() {
let pages = Pages::new();
let Some(device) = device() else {
return;
};
let log = Arc::new(TestLog::default());
let in_place = pages.buffer(&device, &log, Some(true));
let half = (LENGTH / 2) as u64;
let memory = pages.memory(&log, Some(false));
// SAFETY: as in `Pages::memory`.
let copy = unsafe {
device.new_buffer_with_bytes_no_copy(memory, half, ResourceOptions::default(), None)
};
let copy = copy.unwrap();
if in_place.copied() || !copy.copied() {
eprintln!("COPIED-LOG: the device copies the admitted pages; nothing in place to test");
return;
}
let queue = device.new_command_queue().unwrap();
// A first copy in compares every byte, and syncs the copy to a stamp.
assert_eq!(read_back(&queue, &copy, half), vec![0; half as usize]);
let skipped = device.work_counts().copied_copy_in_bytes_skipped;
filled(&queue, &log, &in_place, 4096..8192);
let bytes = read_back(&queue, &copy, half);
assert!(
bytes[4096..8192].iter().all(|b| *b == 0x7E),
"the copy took the fill"
);
assert!(
bytes[..4096].iter().chain(&bytes[8192..]).all(|b| *b == 0),
"and nothing else"
);
let skipped = device.work_counts().copied_copy_in_bytes_skipped - skipped;
eprintln!("COPIED-LOG: the copies in skipped {skipped} bytes");
assert!(skipped > 0, "the copies in were gated by the log");
drop((in_place, copy, queue));
}
/// A `replaceRegion` of a texture of a copied no-copy heap over logged pages writes the heap's
/// bytes in the pages; a buffer of the heap over the texture's span reads them back after the
/// next commit, the heap's own copy having taken them, though its copies in compare only the
/// pages the log reports.
#[test]
fn a_replace_region_of_a_copied_heap_s_texture_reaches_the_heap_s_copy() {
let pages = Pages::new();
let Some(device) = device() else {
return;
};
let log = Arc::new(TestLog::default());
let descriptor = crate::HeapDescriptor::new(
crate::HeapType::Placement,
LENGTH as u64,
ResourceOptions::default(),
);
let memory = pages.memory(&log, Some(false));
// SAFETY: as in `Pages::memory`.
let heap = unsafe { device.new_heap_with_bytes_no_copy(memory, &descriptor, None, None) };
let heap = heap.unwrap();
let mut texture = crate::TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 16, 16, false);
texture.usage = TextureUsage::SHADER_READ;
texture.resource_options = ResourceOptions::default();
let span = device.heap_texture_size_and_align(&texture).unwrap().size;
let texture = heap.new_texture_at_offset(&texture, 0).unwrap();
let bytes = heap
.new_buffer_at_offset(span, ResourceOptions::default(), 0)
.unwrap();
let queue = device.new_command_queue().unwrap();
assert!(read_back(&queue, &bytes, span).iter().all(|b| *b == 0));
let skipped = device.work_counts().copied_copy_in_bytes_skipped;
let region = Region::new_2d(0, 0, 16, 16);
texture
.replace_region(region, 0, 0, &[0x5C; 16 * 16 * 4], 16 * 4, 0)
.unwrap();
let read = read_back(&queue, &bytes, span);
let texels = read.iter().filter(|b| **b == 0x5C).count();
assert_eq!(
texels,
16 * 16 * 4,
"the heap's copy holds every texel's bytes"
);
let skipped = device.work_counts().copied_copy_in_bytes_skipped - skipped;
eprintln!("COPIED-LOG: the copies in skipped {skipped} bytes");
assert!(skipped > 0, "the copies in were gated by the log");
drop((bytes, texture, heap, queue));
}
@@ -44,8 +44,12 @@ mod completion_seen;
mod compute;
mod contexts;
mod copied;
mod copied_bench;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod copied_device;
mod copied_log;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod copied_log_device;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod copy_bounds;
mod copy_plan;
@@ -240,6 +240,7 @@ use metal2vulkan::metal::{PixelFormat, TextureType, TextureUsage};
use metal2vulkan::vk::{
Format, FormatFeatureFlags2, ImageAspectFlags, ImageUsageFlags, SampleCountFlags,
};
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
@@ -441,14 +442,31 @@ impl HeapShadow {
let mut packed = vec![0u8; host.packed_len() as usize];
host.pack(bytes, &mut packed);
let contents = self.contents(call)?;
self.pieces(plan, region, host, |at, from, n| {
// The heap's bytes it wrote, from its first: reported once written.
let mut wrote: Option<Range<usize>> = None;
let written = self.pieces(plan, region, host, |at, from, n| {
wrote = Some(
wrote
.take()
.map_or(at..at + n, |w| w.start.min(at)..w.end.max(at + n)),
);
// SAFETY: every piece lies in the texture's range of the heap's mapped bytes (its
// planes or tiles fit the range: `host_heap_plan`, `heap_image`); a write racing the
// GPU's use of them is the program's, as through `contents`.
unsafe {
std::ptr::copy_nonoverlapping(packed[from..].as_ptr(), contents.as_ptr().add(at), n)
};
})
});
// A write of host pages a consumer logs is the runtime's own, which its log does not see:
// reported, so the copies of the pages take it (`dirty_pages.rs`).
if let Some(wrote) = wrote.filter(|w| w.start < w.end) {
let heap = self.place.heap.upgrade();
if let Some(bytes) = heap.as_ref().and_then(Heap::bytes) {
let first = contents.as_ptr() as u64;
bytes.wrote_host(first + wrote.start as u64..first + wrote.end as u64);
}
}
written
}
/// `getBytes` of `region` of the shadowed image of `plan` into `bytes` laid out as `host`
+36 -4
View File
@@ -300,7 +300,10 @@ pub(crate) struct Counters {
copied_rebind_images_made: AtomicU64,
copied_heaps_made: AtomicU64,
copied_copy_in_bytes: AtomicU64,
copied_copy_in_bytes_skipped: AtomicU64,
copied_merge_back_bytes: AtomicU64,
copied_merges_compared: AtomicU64,
copied_merges_skipped: AtomicU64,
copied_dropped_bytes: AtomicU64,
host_ram_chunks_imported: AtomicU64,
host_ram_chunk_bytes: AtomicU64,
@@ -2074,12 +2077,25 @@ impl Counters {
(self.copied_copy_in_bytes).fetch_add(bytes, Ordering::Relaxed);
}
/// A commit's copy in left `bytes` of copied host buffers uncompared: no log of their pages
/// reported them written since the copy last synced (`copied.rs`).
pub(crate) fn copied_copy_in_skipped(&self, bytes: u64) {
(self.copied_copy_in_bytes_skipped).fetch_add(bytes, Ordering::Relaxed);
}
/// A batch's completion merged `bytes` the GPU changed back into the caller's pages
/// (`copied.rs`).
pub(crate) fn copied_merged_back(&self, bytes: u64) {
(self.copied_merge_back_bytes).fetch_add(bytes, Ordering::Relaxed);
}
/// A completion turn's merge back compared `compared` copied host buffers and left `skipped`
/// uncompared, which no batch it finished could have written (`copied.rs`).
pub(crate) fn copied_merges(&self, compared: u64, skipped: u64) {
(self.copied_merges_compared).fetch_add(compared, Ordering::Relaxed);
(self.copied_merges_skipped).fetch_add(skipped, Ordering::Relaxed);
}
/// A batch's completion dropped `bytes` the GPU changed in copies of pages the process
/// cannot write, taking them out of the copies (`copied.rs`).
pub(crate) fn copied_dropped(&self, bytes: u64) {
@@ -4390,9 +4406,20 @@ pub struct WorkCounts {
/// The bytes the CPU changed in copied host buffers' pages that commits copied into the
/// copies.
pub copied_copy_in_bytes: u64,
/// The bytes of copied host buffers that commits' copies in did not compare: their pages'
/// memory came with a log of the writes to them (`HostMemory::with_dirty_pages`,
/// `HostRam::with_dirty_pages`), which reported none of them written since the copy last
/// synced to it.
pub copied_copy_in_bytes_skipped: u64,
/// The bytes the GPU changed in copied host buffers' copies that batches' completions merged
/// back into the caller's pages.
pub copied_merge_back_bytes: u64,
/// The copied host buffers completion turns' merges back compared, one per copy and turn.
pub copied_merges_compared: u64,
/// The copied host buffers completion turns' merges back left uncompared: no batch the turn
/// finished could have written them (no use of their command buffers' commands wrote one of
/// their keys, and none may have written memory its uses do not name).
pub copied_merges_skipped: u64,
/// The bytes the GPU changed in copies of pages the process cannot write (read-only pages)
/// that batches' completions dropped: taken out of the copies, the pages' bytes in their
/// place, never written to the pages, as Metal drops the GPU's writes to read-only memory.
@@ -4699,14 +4726,15 @@ pub struct WorkCounts {
/// The bytes the gated copies in moved.
pub dirty_copy_in_bytes_copied: u64,
/// The stamps the commits of command buffers with a gated copy in asked of the logs: one per
/// log and commit.
/// log and commit, and one per log and commit for copied host buffers over logged pages.
pub dirty_stamps_asked: u64,
/// The waits the submissions made for a log's publication (`DirtyPages::wait`): one per log
/// serves every stamp asked of it before the wait.
/// The waits the submissions (and, for copied host buffers, the commits) made for a log's
/// publication (`DirtyPages::wait`): one per log serves every stamp asked of it before the
/// wait.
pub dirty_waits: u64,
/// Of the waits, those the log answered `false`.
pub dirty_waits_unanswered: u64,
/// The nanoseconds the waits took, on the threads that submit command buffers.
/// The nanoseconds the waits took, on the threads that submit and commit command buffers.
pub dirty_wait_nanos: u64,
/// Of the keeps and merges among `shadow_copies`, those whose copy of the shadow's texels into
/// the merge's scratch is the dispatch a copy back takes, where the device runs one faster
@@ -5488,7 +5516,11 @@ impl Device {
copied_rebind_images_made: counters.copied_rebind_images_made.load(Ordering::Relaxed),
copied_heaps_made: counters.copied_heaps_made.load(Ordering::Relaxed),
copied_copy_in_bytes: counters.copied_copy_in_bytes.load(Ordering::Relaxed),
copied_copy_in_bytes_skipped: (counters.copied_copy_in_bytes_skipped)
.load(Ordering::Relaxed),
copied_merge_back_bytes: counters.copied_merge_back_bytes.load(Ordering::Relaxed),
copied_merges_compared: counters.copied_merges_compared.load(Ordering::Relaxed),
copied_merges_skipped: counters.copied_merges_skipped.load(Ordering::Relaxed),
copied_dropped_bytes: counters.copied_dropped_bytes.load(Ordering::Relaxed),
host_ram_chunks_imported: counters.host_ram_chunks_imported.load(Ordering::Relaxed),
host_ram_chunk_bytes: counters.host_ram_chunk_bytes.load(Ordering::Relaxed),
@@ -1 +1 @@
166b255c7193c77b160eeae8b0a21293e17e10098b140a1466f8e6255fb14803
b3d90b9c02a84252633f356df01ab78efd80f26437cfe5700934968476c12736
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 479;
/// 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 = 1704;
pub const RUNTIME_VERSION: u32 = 1705;
/// 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
@@ -2471,12 +2471,15 @@ field metal2vulkan-runtime::WorkCounts.completion_arms_after_a_wake pub completi
field metal2vulkan-runtime::WorkCounts.completion_reads_ran_ahead pub completion_reads_ran_ahead: u64
field metal2vulkan-runtime::WorkCounts.compute_pipeline_create_nanos pub compute_pipeline_create_nanos: u64
field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes pub copied_copy_in_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes_skipped pub copied_copy_in_bytes_skipped: u64
field metal2vulkan-runtime::WorkCounts.copied_dropped_bytes pub copied_dropped_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_heaps_made pub copied_heaps_made: u64
field metal2vulkan-runtime::WorkCounts.copied_host_buffers_degraded pub copied_host_buffers_degraded: u64
field metal2vulkan-runtime::WorkCounts.copied_host_buffers_made pub copied_host_buffers_made: u64
field metal2vulkan-runtime::WorkCounts.copied_host_buffers_refused pub copied_host_buffers_refused: u64
field metal2vulkan-runtime::WorkCounts.copied_merge_back_bytes pub copied_merge_back_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_merges_compared pub copied_merges_compared: u64
field metal2vulkan-runtime::WorkCounts.copied_merges_skipped pub copied_merges_skipped: u64
field metal2vulkan-runtime::WorkCounts.copied_rebind_images_made pub copied_rebind_images_made: u64
field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_made pub copied_rebind_pages_made: u64
field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_moved pub copied_rebind_pages_moved: u64
Can't render this file because it is too large.
+12 -7
View File
@@ -316,13 +316,18 @@ recorded here.
Open differences from Metal that no note announces yet, and runtime costs still above the
driver's. Each is open work.
- **A copied host buffer costs O(its size) at every commit and every batch's completion**
(`copied.rs`, `copied-host-pages`): each compares every byte of every live copy with the bytes
the copy and the pages last agreed on, whichever buffers the work names, where a page log or the
work's uses could bound it: a live 64 MiB copy added 45 to 68 ms to each empty command buffer's
commit and wait (0.2 ms without) on an RTX 5080 laptop (Intel Core Ultra 9 275HX). A copy is
made only where the caller's gate refuses an import or an admitted import fails, never by
default.
- **A copied host buffer costs O(its size) at every batch's completion that may have written
it, and at every commit where its pages carry no log** (`copied.rs`, `copied-host-pages`): each
compares every byte of the copy with the bytes the copy and the pages last agreed on, a page at
a time, so 680 MiB of copies that agree take 28-30 ms at each commit without a log on an M3
Max (52-53 ms on the RTX 5080 laptop's Core Ultra 9 275HX), and as long at each completion of
a command buffer whose functions read addresses (which may write every copy) or that executes
an indirect command buffer (`tests/copied_bench.rs`). Where the pages' memory carries a log of
their writes (`HostMemory::with_dirty_pages`, `HostRam::with_dirty_pages`), the commit
compares only the pages it reports written: 0.15 ms where none changed, 4.6 ms where 1% did
(0.3 and 3.5 ms on the 275HX). A completion whose command buffers' uses name the
copies they write compares those alone. A copy is made only where the caller's gate refuses an
import or an admitted import fails, never by default.
- **A copied host buffer's merge keeps the CPU's byte where the CPU and the GPU both wrote it**
between a commit and the completion: bytes are merged one at a time, so a GPU write never
rewrites a byte beside it, but a byte both wrote keeps the CPU's, where on Metal the later write
+11 -2
View File
@@ -352,8 +352,17 @@ handlers run or a waiter returns, keeping a byte the CPU changed since (`copied_
`copied_merge_back_bytes`). An event signal submitted while a copy is live is seen at its batch's
completion, after that write-back: no read of the event's value shows it earlier, and a wait for it
on another queue (a plain `Event`'s too) is held until then rather than chained on the GPU
(`event_signals_behind_merge`). Each compares every byte of every live copy, so keep copies few. A
texture over a copied buffer is a shadow of its bytes. The copy reads the pages through the kernel
(`event_signals_behind_merge`). Each completion compares every byte of each copy its command
buffers may have written (`copied_merges_compared`, `copied_merges_skipped`): those their uses
wrote, and every copy where a function reads addresses or an indirect command buffer runs, so keep
copies few. Where the pages' memory carries a log of the writes to them
(`HostMemory::with_dirty_pages`, `HostRam::with_dirty_pages`), each commit compares only the pages
the log reports written since the copy's last commit, and the bytes no log keeps
(`copied_copy_in_bytes_skipped`): it asks one stamp of each log for every copy and waits for its
publication (bounded) on the committing thread, and every copy compares every byte at its first
commit and where a log answers `false`. The runtime reports to the log what the log cannot see: a
copy's merge back, as the copy's own write, the GPU's writes into the pages through imports in
place, and its own CPU writes into them. A texture over a copied buffer is a shadow of its bytes. The copy reads the pages through the kernel
first, and where the kernel cannot read them, with plain loads where the process maps every page
with read permission: on Linux the kernel's read pins each page, which a mapping of a dma-buf
(`VM_PFNMAP`) does not allow. Pages not mapped, or mapped