From 004399166079cd16edf72dd5dd35568e5fa3e3c3 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 01:14:50 -0800 Subject: [PATCH] RUNTIME 2269: a bit-24 no-copy buffer's blit copies read its pages in place through a read twin Off macOS, a no-copy buffer made with Metal's read-only option bit 24 is a copied host buffer (CopiedFor::ReadOnly) whose copy takes every write; every commit that used it compared the whole copy against the pages (reims's 12.7.6 walk: 130,448 MiB compared, 34,462 compare threads, copy-in bytes 0). Now such a buffer also gets a read twin: the runtime's own buffer over the same pages, imported in place, outside the Metal address space (key bit 63), made only under the Contained policy and only where the pages import in place (never a copy). copyFromBuffer:toBuffer and copyFromBuffer:toTexture read through the twin until an earlier command of the same command buffer may have written the buffer (a write of its key, writes_unnamed, or unnoted uses); after that they read the copy, so the command buffer reads its own dropped write back and the next command buffer reads the pages. Every encoder refuses a command whose own uses write a twin key: it records nothing and fails its command buffer. The twin is placed over the bytes before its buffer, so a twin use does not drag in the copy. Counted: read_twins_made, read_twins_unimported, read_twins_uncontained, read_twin_blit_reads, read_twin_reads_after_writes, read_twin_writes_refused, copied_copy_ins_compared, copied_copy_in_bytes_compared. Docs edited in place: the FAST-PATHS row "Off macOS, GPU writes into read-only memory", API.md's copied-host-pages and private-resource-option rows, read_only_view.rs. RUNTIME_VERSION 2269: blit sources of bit-24 buffers read in place. Verified (roip, lavapipe m3-max-28537 at ad4ed6a591, 40/40 read_twin_device|copied_device): a 29,753,344-byte (3648x2038x4) buffer's copyFromBuffer:toTexture + buffer copy compare [0 copies, 0 bytes, 0 threads] (was [1, 29,753,344, 7]), texels and bytes match the pages; fill + copy-out in one CB reads the fill back, pages unchanged, next CB in place; blit fill, blit copy-in and a kernel store through a loaded pointer at gpuAddress leave the pages; a fill of the twin is refused (negative control: with the guard off it changes the pages); no twin when the import is refused, over read-only pages, or under UnsafeOff. Owed after landing: 5080, clippy x3, rustdoc. Next steps: sampled textures over the buffer, buffer slots, resident sets. Squashed from steelbrain/roip 4d4bef55bd..ad4ed6a591 (encoder.rs import conflict with RUNTIME 2268's encoder_fold resolved by keeping both). --- crates/metal2vulkan-runtime/src/blit.rs | 4 + .../metal2vulkan-runtime/src/blit_texture.rs | 5 +- crates/metal2vulkan-runtime/src/buffer.rs | 34 +- .../src/buffer_descriptor.rs | 34 +- .../src/command_buffer/mod.rs | 6 + crates/metal2vulkan-runtime/src/copied.rs | 4 + .../metal2vulkan-runtime/src/dirty_pages.rs | 6 + crates/metal2vulkan-runtime/src/encoder.rs | 15 +- crates/metal2vulkan-runtime/src/lib.rs | 1 + .../src/read_only_view.rs | 4 +- crates/metal2vulkan-runtime/src/read_twin.rs | 170 ++++++ crates/metal2vulkan-runtime/src/resource.rs | 36 +- .../src/tests/copied_device.rs | 12 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/read_twin_device.rs | 545 ++++++++++++++++++ .../src/used_resources.rs | 8 + .../metal2vulkan-runtime/src/work_counts.rs | 88 +++ crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 8 + docs/API.md | 12 +- docs/FAST-PATHS.md | 12 +- 21 files changed, 984 insertions(+), 24 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/read_twin.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/read_twin_device.rs diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index deaf6a289..aa47b4492 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -415,6 +415,10 @@ impl BlitCommandEncoder { out_of_bounds(CALL, source_offset, size, source_buffer.length()) })?; let to = bytes_in(CALL, destination_offset, size, destination_buffer.length())?; + // A source whose GPU writes are dropped is read in place through its read twin, + // where it has one (`read_twin.rs`). + let twin = this.core.read_source(source_buffer); + let source_buffer = twin.as_ref().unwrap_or(source_buffer); // Read as a blit's: a no-copy buffer's import released while idle is imported again // (`host_residency.rs`). let (source, source_at) = this.core.blit_at(source_buffer, source_offset)?; diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs index 0aa540b1b..fd31fc285 100644 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ b/crates/metal2vulkan-runtime/src/blit_texture.rs @@ -531,10 +531,13 @@ impl BlitCommandEncoder { })) }, |this| { + // A source whose GPU writes are dropped is read in place through its read twin, + // where it has one (`read_twin.rs`). + let twin = this.core().read_source(source_buffer); this.buffer_into_texture( Writer::Blit, ( - source_buffer, + twin.as_ref().unwrap_or(source_buffer), source_offset, source_bytes_per_row, source_bytes_per_image, diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index e0af3cb5c..d7fe75583 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -218,6 +218,10 @@ pub(super) struct HostCell { /// The deallocator of the pages its last detach let go of (`detach.rs`), held back until its /// next rebind or its release, as Metal runs it then ([`Release::hold_back`]). held_back: Mutex>>, + /// Its read twin, where its GPU writes are dropped (`read_twin.rs`): the runtime's buffer over + /// the same pages in place, which commands that cannot write the buffer read instead of its + /// copy. Let go of as the buffer lies elsewhere ([`HostCell::replace`]). + read_twin: Mutex>, } /// An image in place over a buffer's host pages ([`HostCell`], `texture/in_place_image.rs`), @@ -615,9 +619,24 @@ impl HostCell { HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel); lay }; + // Its read twin lies over the pages it lay in: let go of, outside the pages' lock, so the + // buffer is its copy alone from now on (`read_twin.rs`). + let twin = lock(&self.read_twin).take(); + drop(twin); lay } + /// Its read twin (`read_twin.rs`), while it lies in the pages the twin was made over. + pub(super) fn read_twin(&self) -> Option { + lock(&self.read_twin).clone() + } + + /// Keep `twin`, its read twin over the pages it lies in now (`read_twin.rs`). + pub(super) fn keep_read_twin(&self, twin: Buffer) { + let earlier = lock(&self.read_twin).replace(twin); + drop(earlier); + } + /// A detach let go of `pages`: their deallocator is held back until the buffer's next rebind /// or its release ([`HostCell::release_held_back`]), as Metal never runs it at a detach. pub(super) fn hold_back(&self, pages: &HostPages) { @@ -2711,10 +2730,13 @@ pub(super) struct BufferParts { /// carries (`Buffer::carry`), the same buffer on the next generation, its identity, `ObjectId` /// and attributes the buffer's; or the runtime's own buffer over the caller's pages that a /// `Managed` no-copy buffer on a device without unified memory copies to and from -/// (`managed_copy.rs`), new as a new buffer is, which is never a copy of the pages. +/// (`managed_copy.rs`), new as a new buffer is, which is never a copy of the pages; or the +/// runtime's read twin of a no-copy buffer whose GPU writes are dropped (`read_twin.rs`), new as +/// a new buffer is but of a read twin's identity, which is never a copy of the pages either. pub(super) enum Naming { New, HostCopy, + ReadTwin, Carried { object_id: ObjectId, identity: Identity, @@ -2728,6 +2750,7 @@ impl Naming { fn identity(&self, hazard: HazardTrackingMode, of_heap: bool) -> Identity { match self { Naming::New | Naming::HostCopy => Identity::new(hazard, of_heap), + Naming::ReadTwin => Identity::read_twin(), Naming::Carried { identity, .. } => *identity, } } @@ -3712,6 +3735,7 @@ impl Device { freed: AtomicBool::new(false), drops_writes, held_back: Mutex::new(None), + read_twin: Mutex::new(None), }); self.shared().rebinds.register(key, &cell); Lie::Host(cell) @@ -3728,7 +3752,9 @@ impl Device { ) -> Buffer { let options = ResourceOptions::new(modes.storage, modes.cache, own.identity.mode()); let (object_id, attributes) = match naming { - Naming::New | Naming::HostCopy => (ObjectId::new(), ResourceAttributes::new()), + Naming::New | Naming::HostCopy | Naming::ReadTwin => { + (ObjectId::new(), ResourceAttributes::new()) + } Naming::Carried { object_id, attributes, @@ -4293,10 +4319,12 @@ impl Buffer { /// Metal reads the caller's bytes there, current ones, from the pointer to its pages' end /// (an M4 under macOS 27.0.1). Past them, and past another buffer's length, its API validation /// stops the copy, and plain Metal reads zeros, bytes written past the length, or another - /// resource's: refused (`Invalid`). + /// resource's: refused (`Invalid`). A read twin's is its length, as its buffer's copy's is + /// (`read_twin.rs`), so a copy refused out of the buffer is refused out of the twin too. pub(super) fn copy_reach(&self) -> u64 { let s = self.s(); match &s.bytes { + Bytes::Own(own) if own.identity.key.is_read_twin() => own.shape().reach.min(s.length), Bytes::Own(own) => own.shape().reach, Bytes::Heap(_) => s.length, } diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index fc89b2353..607fb3101 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -825,11 +825,14 @@ impl Device { // its own; one whose GPU writes are dropped imports or copies its own (its import is a // read-only view of the pages, or its copy drops them). let made_over = (pointer.as_ptr() as u64, length); - // A two-copy buffer's host copy lies in no copy of the pages (`managed_copy.rs`). + // A two-copy buffer's host copy lies in no copy of the pages (`managed_copy.rs`), nor + // does a read twin (`read_twin.rs`). let shares = (!drops_writes) .then(|| shared.aliases.import(made_over, class)) .flatten() - .filter(|import| !(matches!(naming, Naming::HostCopy) && import.copied())) + .filter(|import| { + !(matches!(naming, Naming::HostCopy | Naming::ReadTwin) && import.copied()) + }) .filter(|import| !(of_heap && import.copied())); if let Some(import) = shares { let address = self.place_window(placement, &window, length)?; @@ -961,16 +964,27 @@ impl Device { // maps no read-only view of the pages (`read_only_view.rs`): a copy of them whose // GPU writes are dropped, the gate unasked and no page pinned. It joins no other // buffer over the bytes, nor does one lie in it. + // A new one that is no heap's own takes a read twin besides where it can: the + // runtime's buffer over the pages in place, which the commands that cannot write + // it read instead of the copy (`read_twin.rs`). if drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES { + let twin = (!of_heap && matches!(naming, Naming::New)).then(|| made_of.clone()); // SAFETY: the caller's contract. let copied = unsafe { self.copied_buffer(copy, release, dirty, CopiedFor::ReadOnly, naming) - }; - return copied.map(|buffer| { - let buffer = kept(buffer, log, kept_runs, made_of); - shared.aliases.place(buffer.identity().key, made_over); - buffer - }); + }?; + let buffer = kept(copied, log, kept_runs, made_of); + if let Some(parts) = twin { + // SAFETY: the parts are the caller's, for the same bytes (the caller's + // contract). + unsafe { self.make_read_twin(&buffer, (call, length, options), parts) }; + } + // Placed after its twin, so that the twin's key is its bytes' (the first + // placed there, `host_aliases.rs`'s `Placements`): a command that reads + // through the twin alone names no use of the copy, whose commit then + // compares none of it, while the copy's uses order against the twin's. + shared.aliases.place(buffer.identity().key, made_over); + return Ok(buffer); } // Pages a live import holds some of: a copy, the gate unasked and no page pinned. if over_import || over_chunk { @@ -2354,6 +2368,10 @@ impl Device { naming: Naming, ) -> Result { let read_only = matches!(why, CopiedFor::ReadOnly); + // A read twin is an import of the pages in place or nothing (`read_twin.rs`). + if let Naming::ReadTwin = naming { + return Err(crate::read_twin::uncopied()); + } // A two-copy buffer's host copy is the pages alone instead (`managed_copy.rs`). if let Naming::HostCopy = naming { let drops = read_only || matches!(why, CopiedFor::Unwritable); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index d1a06af49..82e7f8ff1 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2770,6 +2770,12 @@ impl CommandBuffer { } } + /// Whether a command's uses went unnoted ([`note_dirty`](Self::note_dirty)), nothing + /// collecting them then. + pub(super) fn uses_unnoted(&self) -> bool { + self.0.unnoted.load(Ordering::Relaxed) + } + /// What its commands did so far that the device's logs of host pages hear of at its commit. pub(super) fn dirty(&self) -> MutexGuard<'_, DirtyCommit> { lock(&self.0.dirty) diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index 67ce2e599..363663c10 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -1330,11 +1330,13 @@ impl CopiedBuffers { let plans = planned(asked, tally, &in_flight); let (mut moved, mut skipped, mut unused, mut read) = (0u64, 0u64, 0u64, 0u64); let (mut made, mut refused, mut started, mut read_back) = (0u64, 0u64, 0u64, 0u64); + let (mut copies, mut bytes_compared) = (0u64, 0u64); for entry in lock(&self.entries).iter_mut() { if !reaches(entry) { unused += 1; continue; } + copies += 1; let plan = match &entry.log { Some(_) => (plans.binary_search_by_key(&entry.id, |(id, _)| *id).ok()) .map(|at| &plans[at].1), @@ -1384,6 +1386,7 @@ impl CopiedBuffers { }; compared += range.end - range.start; } + bytes_compared += compared; skipped += length as u64 - compared; if let (Some(log), Some(plan)) = (&mut entry.log, plan) { log.since = plan.stamps.clone(); @@ -1409,6 +1412,7 @@ impl CopiedBuffers { counts.copied_copied_in(moved); counts.copied_copy_in_skipped(skipped); counts.copied_copy_ins_unused(unused); + counts.copied_copy_ins_compared(copies, bytes_compared); counts.copied_bases(made, refused, read); counts.copied_base_blocks_read_back(read_back); counts.copied_compare_threads(started); diff --git a/crates/metal2vulkan-runtime/src/dirty_pages.rs b/crates/metal2vulkan-runtime/src/dirty_pages.rs index 643a9dfd8..6d71aec55 100644 --- a/crates/metal2vulkan-runtime/src/dirty_pages.rs +++ b/crates/metal2vulkan-runtime/src/dirty_pages.rs @@ -1326,6 +1326,12 @@ impl DirtyCommit { } } + /// Whether its commands so far may have written the bytes of `key`: a write of it noted, or + /// more writes than it keeps apart (`read_twin.rs`). + pub(crate) fn may_have_written(&self, key: ResourceKey) -> bool { + self.overflowed || self.written.iter().any(|used| used.key == key) + } + /// 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 CopiesReached) { diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 121b74326..0e95c88e6 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -49,7 +49,7 @@ use super::command_buffer::{recording_error, CommandBuffer}; use super::deferred::{Deferred, StepInputs}; use super::degradation::NoticesFor; use super::encoder_fold::{self, Fold, FoldEnd, Joining}; -use super::error::{internal, invalid, vulkan, CommandBufferError, Error}; +use super::error::{internal, invalid, vulkan, CommandBufferError, Error, VkResultCode}; use super::execution::Execution; use super::fresh_unwritten::{FreshRead, FreshUnwritten}; use super::heap::Heap; @@ -1556,6 +1556,19 @@ impl EncoderCore { self.touch_reaching(uses, resident); return None; } + // A command that writes a read twin, which lies over pages whose GPU writes are dropped in + // place (`read_twin.rs`), records nothing, and its command buffer fails from this encoder + // on: no path binds a twin where a command may write it, so only a defect of the + // runtime's meets this, which it keeps from the pages. + let writes_twin = + || (uses.iter()).any(|used| used.key.is_read_twin() && !used.write.is_empty()); + if writes_twin() && crate::read_twin::refuses_writes() { + self.device().shared().counts.read_twin_write_refused(); + self.fail_command_buffer(CommandBufferError::Internal(VkResultCode( + vk::Result::ERROR_UNKNOWN.as_raw(), + ))); + return None; + } // A command reading a new texture's levels that read zero where Metal reads its pattern, // before a clear covered them, announces it at its commit (`fresh_unwritten.rs`). self.observe_fresh(uses, reads); diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index d35d5351b..96fa00a75 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -201,6 +201,7 @@ mod range; mod rate_map; mod rate_mapped_pass; mod read_only_view; +mod read_twin; mod reader_sizes; mod rebind; mod recorder; diff --git a/crates/metal2vulkan-runtime/src/read_only_view.rs b/crates/metal2vulkan-runtime/src/read_only_view.rs index b84b146fe..83cec9f91 100644 --- a/crates/metal2vulkan-runtime/src/read_only_view.rs +++ b/crates/metal2vulkan-runtime/src/read_only_view.rs @@ -86,7 +86,9 @@ //! [`Degradation::CopiedHostPages`](crate::Degradation::CopiedHostPages)): each commit copies in //! what the CPU wrote, later commands of a batch read its GPU writes back, and its completion //! puts the copy back to the pages' bytes, which the GPU never writes. A render pass's -//! store-out into it completes there, where Metal's faults its command buffer. +//! store-out into it completes there, where Metal's faults its command buffer. A no-copy +//! buffer's blit copies out of it read the pages in place instead, through the buffer's read +//! twin (`read_twin.rs`), which no command writes. use std::ptr::NonNull; diff --git a/crates/metal2vulkan-runtime/src/read_twin.rs b/crates/metal2vulkan-runtime/src/read_twin.rs new file mode 100644 index 000000000..1c3918da1 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/read_twin.rs @@ -0,0 +1,170 @@ +//! Read twins: a no-copy buffer whose GPU writes Metal's private option bit 24 drops +//! ([`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT)), where the system maps +//! no read-only view of its pages (`read_only_view.rs`), read in place by the commands that +//! cannot write it. +//! +//! - **Why.** Off macOS such a buffer is a copy of its pages (`copied.rs`), and a copy is +//! compared with its pages at each commit that uses it: a guest's window server reads such +//! buffers of 30 MB every frame, and the comparisons cost it whole seconds of a walk while the +//! GPU never wrote them. No import keeps the GPU's writes from the pages there (`host_memory.rs`), +//! and Vulkan has no read-only memory, so the pages can be imported in place only where no +//! command that may store into them can reach the import. +//! - **The twin.** Beside its copy, such a buffer takes the runtime's own buffer over the same +//! pages ([`Device::make_read_twin`]), made as a writable no-copy buffer's import would be (in a +//! guest RAM's chunk, inside a live import, by its pointer or as dma-bufs; never a second import +//! of a page, `host_aliases.rs`), and never a copy: where the import would be one, or fails, +//! the buffer takes no twin (`WorkCounts::read_twins_unimported`). Nor does it where the +//! device's policy contains no access (`ContainmentPolicy::UnsafeOff`, +//! `WorkCounts::read_twins_uncontained`), where a store may reach past what it names. The twin +//! takes no address of the Metal space (it lies outside it, `address.rs`), no resource ID, and +//! no place among the live buffers (`live_buffers.rs`); no call returns it. Its key is a read +//! twin's ([`ResourceKey::read_twin`]), owned by its buffer, so a command that reads through it +//! uses the buffer (`CommandBuffer::used_resources`). It holds the pages its buffer lies in, so +//! the caller's deallocator runs once both let go of them, and it goes as the buffer lies +//! elsewhere (a rebind, a detach) or goes. +//! - **Where it is read, and why nothing writes it.** The program names the buffer alone, and +//! every call that names it (a binding, a blit, a pass's visibility results, an attachment, an +//! indirect command, `useResource`) reaches its copy, whose writes are dropped at completion as +//! before. Only a site whose command cannot store into the bytes it reads takes the twin in its +//! place: +//! - a blit's copy out of the buffer, into a buffer or a texture: a copy reads its source alone +//! (`vkCmdCopyBuffer`, `vkCmdCopyBufferToImage`). Counted: `WorkCounts::read_twin_blit_reads`. +//! +//! Each such site takes the twin only while no earlier command of its command buffer may have +//! written the buffer's copy (a write of its key, or a function that may store through an +//! address, `State::writes_unnamed`): after one, the command buffer reads the copy, so a later +//! command reads the dropped write back as Metal's GPU caches let it (`read_only_view.rs`), +//! and the next command buffer reads the pages (`WorkCounts::read_twin_reads_after_writes`). +//! And every encoder refuses a command whose uses write a twin's key: it records nothing, and +//! its command buffer fails (`WorkCounts::read_twin_writes_refused`), which only a defect of +//! the runtime's meets. +//! - **What it saves.** A command buffer that reads such a buffer only through its twin uses +//! none of its copy, so its commit compares none of it (`copied.rs`, +//! `WorkCounts::copied_copy_ins_compared`, `copied_copy_in_bytes_compared`): the twin is placed +//! over the bytes before its buffer, so the bytes' key is the twin's (`host_aliases.rs`'s +//! `Placements`), which a use of the copy takes and a use of the twin takes nothing beside. + +use super::address::{AddressPlacement, Place}; +use super::buffer::{Buffer, Naming}; +use super::command_buffer::CommandBuffer; +use super::device::Device; +use super::encoder::EncoderCore; +use super::error::{internal, Error}; +use super::host_memory::HostParts; +use super::values::ResourceOptions; +use metal2vulkan::device::ContainmentPolicy; +use std::sync::Arc; + +/// The refusal a read twin answers where its pages' import would be a copy of them +/// (`Device::copied_buffer`): it takes none. +pub(super) fn uncopied() -> Error { + internal("a read twin is never a copy of its pages") +} + +#[cfg(test)] +thread_local! { + /// The tests' negative control: an encoder on this thread records a command that writes a + /// read twin, which it refuses otherwise ([`refuses_writes`]). + pub(crate) static UNGUARDED: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Whether an encoder refuses a command whose uses write a read twin (`encoder.rs`): always, but +/// on a test's thread that turned the guard off ([`UNGUARDED`]), to show what it keeps from the +/// pages. +pub(super) fn refuses_writes() -> bool { + #[cfg(test)] + if UNGUARDED.with(std::cell::Cell::get) { + return false; + } + true +} + +impl Device { + /// Give `of`, a new no-copy buffer whose GPU writes are dropped lying in its copy, made for + /// `call` of `length` bytes and `options` over the caller's `parts`, its read twin (the module + /// docs), where the device's policy contains every access and the pages are imported in + /// place; else nothing, counted. + /// + /// # Safety + /// + /// `parts` are the memory `of` was made over, which meets [`HostMemory::new`]'s contract for + /// `length` bytes while `of` holds its pages. + /// + /// [`HostMemory::new`]: crate::HostMemory::new + pub(super) unsafe fn make_read_twin( + &self, + of: &Buffer, + (call, length, options): (&'static str, u64, ResourceOptions), + parts: HostParts, + ) { + let shared = self.shared(); + if self.compile_device().policy().containment != ContainmentPolicy::Contained { + shared.counts.read_twin_not_made(true); + return; + } + let Some(cell) = of.host_cell() else { + return; + }; + let Some(pages) = cell.current() else { + return; + }; + let made = (call, length, options, Place::At(AddressPlacement::Outside)); + // SAFETY: the caller's contract; the twin releases nothing to the caller, and holds the + // pages `of` lies in, whose release keeps them mapped (below). + let twin = + unsafe { self.one_copy_buffer(made, parts, None, false, false, Naming::ReadTwin) }; + let twin = + (twin.ok()).filter(|twin| twin.host_pages().is_some_and(|in_pages| !in_pages.copied())); + let Some(twin) = twin else { + shared.counts.read_twin_not_made(false); + return; + }; + // The pages `of` lies in, and so their release to the caller, go only once the twin's + // pages go too. + if let Some(in_pages) = twin.host_pages() { + in_pages.park(Arc::clone(&pages)); + } + (shared.owners).read_twin(&twin, of, shared.counts.submissions_made()); + cell.keep_read_twin(twin); + shared.counts.read_twin_made(); + } +} + +impl Buffer { + /// Its read twin, while it has one (the module docs): a no-copy buffer whose GPU writes are + /// dropped, lying in its copy, over pages imported in place for it. + pub(super) fn read_twin(&self) -> Option { + self.host_cell()?.read_twin() + } +} + +impl CommandBuffer { + /// Whether a command encoded into it so far may have written the bytes of `key`: a use that + /// wrote it, a function that may store through an address (`State::writes_unnamed`), or + /// writes it did not keep apart. + pub(super) fn may_have_written(&self, key: super::resource::ResourceKey) -> bool { + if self.uses_unnoted() || self.state().writes_unnamed { + return true; + } + self.dirty().may_have_written(key) + } +} + +impl EncoderCore { + /// The buffer a blit's copy out of `buffer` reads its bytes through: its read twin, in place, + /// where it has one and no earlier command of the command buffer may have written its copy + /// (the module docs); else `None`, the buffer itself. + pub(super) fn read_source(&self, buffer: &Buffer) -> Option { + let twin = buffer.read_twin()?; + let counts = &self.device().shared().counts; + if self + .command_buffer() + .may_have_written(buffer.identity().key) + { + counts.read_twin_read_after_write(); + return None; + } + counts.read_twin_blit_read(); + Some(twin) + } +} diff --git a/crates/metal2vulkan-runtime/src/resource.rs b/crates/metal2vulkan-runtime/src/resource.rs index dc55aea57..833143a23 100644 --- a/crates/metal2vulkan-runtime/src/resource.rs +++ b/crates/metal2vulkan-runtime/src/resource.rs @@ -10,19 +10,39 @@ use std::sync::atomic::{AtomicU64, Ordering}; #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub(super) struct ResourceKey(u64); +/// The bit of a read twin's key ([`ResourceKey::read_twin`]): no count of keys reaches it. +const READ_TWIN: u64 = 1 << 63; + impl ResourceKey { /// A key no resource had before. pub(super) fn new() -> ResourceKey { - static NEXT: AtomicU64 = AtomicU64::new(1); - ResourceKey(NEXT.fetch_add(1, Ordering::Relaxed)) + ResourceKey(next_key()) + } + + /// A key no resource had before, of a read twin (`read_twin.rs`): a runtime buffer over a + /// no-copy buffer's read-only pages that no command may write, which every use states + /// ([`is_read_twin`](Self::is_read_twin)) so that an encoder refuses a write of it. + pub(super) fn read_twin() -> ResourceKey { + ResourceKey(next_key() | READ_TWIN) + } + + /// Whether it is a read twin's key ([`read_twin`](Self::read_twin)). + pub(super) fn is_read_twin(self) -> bool { + self.0 & READ_TWIN != 0 } /// Its place among the process's keys, made in order: the first is 1. pub(super) fn ordinal(self) -> u64 { - self.0 + self.0 & !READ_TWIN } } +/// The next key's number, counted from 1 for every key of the process, a read twin's too. +fn next_key() -> u64 { + static NEXT: AtomicU64 = AtomicU64::new(1); + NEXT.fetch_add(1, Ordering::Relaxed) +} + /// A buffer's, texture's, heap's or command buffer's identity (`Buffer::object_id`, /// `Texture::object_id`, `Heap::object_id`, `CommandBuffer::object_id`): a runtime extension, no /// Metal type. Metal names an object by its pointer (`id`), which another object may take once it @@ -75,6 +95,16 @@ impl Identity { } } + /// A read twin's identity (`read_twin.rs`): tracked, so its reads are ordered after the + /// writes of a writable buffer over the same pages whose memory it joined + /// (`host_aliases.rs`). + pub(super) fn read_twin() -> Identity { + Identity { + key: ResourceKey::read_twin(), + tracked: true, + } + } + /// The resolved hazard tracking mode: `Tracked` or `Untracked`. pub(super) fn mode(self) -> HazardTrackingMode { if self.tracked { diff --git a/crates/metal2vulkan-runtime/src/tests/copied_device.rs b/crates/metal2vulkan-runtime/src/tests/copied_device.rs index 5bf12a9a6..c89ff7ffb 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied_device.rs @@ -2156,7 +2156,7 @@ fn copied_rebind_keeps_metal_s_order_around_command_buffers() { /// memory a writable mapping also maps (the guest's own): `LENGTH` bytes in a pattern of `seed`, /// the read-only view at a multiple of 64 KiB. #[cfg(any(target_os = "linux", target_os = "macos"))] -struct ReadOnlyHost { +pub(super) struct ReadOnlyHost { /// The read-only view's first byte. pointer: NonNull, /// The writable mapping of the same memory. @@ -2171,7 +2171,7 @@ struct ReadOnlyHost { #[cfg(any(target_os = "linux", target_os = "macos"))] impl ReadOnlyHost { - fn new(seed: u8) -> ReadOnlyHost { + pub(super) fn new(seed: u8) -> ReadOnlyHost { use std::os::fd::AsRawFd; let memory = Arc::new(shared_memory()); let fd = memory.as_raw_fd(); @@ -2239,6 +2239,12 @@ impl ReadOnlyHost { pattern(self.seed) } + /// How many bytes it holds. + #[cfg(target_os = "linux")] + pub(super) fn length(&self) -> u64 { + LENGTH as u64 + } + /// Its bytes, read through the read-only view while no command buffer runs. fn bytes(&self) -> Vec { // SAFETY: the view's bytes, readable, which no command buffer writes now. @@ -2265,7 +2271,7 @@ impl ReadOnlyHost { /// # Safety /// /// The view outlives every buffer, heap and rebind over it and the device. - unsafe fn memory( + pub(super) unsafe fn memory( &self, gate: ImportGate, calls: &Arc, diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 5dc27b607..d174d5a57 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -561,6 +561,8 @@ mod rate_mapped_fan_out; mod rate_mapped_pieces; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod read_through_constant; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod read_twin_device; mod reader_sizes; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod rebind_behind_a_wait; diff --git a/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs b/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs new file mode 100644 index 000000000..a5aa3d6b6 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/read_twin_device.rs @@ -0,0 +1,545 @@ +//! Read twins on a device (`read_twin.rs`): a no-copy buffer of Metal's private option bit 24, +//! where the system maps no read-only view of its pages, read in place by the commands that +//! cannot write it, every write still dropped. +//! +//! - **Made where it can be.** A buffer over pages the device imports takes a twin; one over pages +//! the process maps read-only, or whose import the caller's gate refuses, takes none (its import +//! would be a copy); nor does any under a policy that contains no access. +//! - **Blits read in place.** A screen-sized buffer (a 3648 x 2038 BGRA image's bytes, about +//! 30 MB) copied into a texture and into a buffer is read through its twin: the copies hold the +//! pages' bytes, a CPU write to the pages reaches the next command buffer with nothing copied in, +//! and the commits compare none of the buffer's copy (`copied_copy_ins_compared`, +//! `copied_copy_in_bytes_compared`, `copied_compare_threads`). +//! - **A write dropped, read back, then gone.** A fill of the buffer and a copy out of it in one +//! command buffer: the copy reads the fill back, through the buffer's copy, which that commit +//! compares; the next command buffer reads the pages, in place again, and the pages never took +//! the fill. +//! - **Every store kind leaves the pages.** A blit's fill and copy into the buffer, a kernel's +//! store into it at a slot, and a kernel's store through its address loaded from memory: the +//! pages keep their bytes and a later command buffer reads them in place. +//! - **The guard, and the negative control.** A fill of the twin itself is refused by the +//! encoder, its command buffer failed and the pages kept; with the guard off on the test's +//! thread the same fill changes the pages: the twin is the pages in place, and what keeps them +//! is that no write reaches it. +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). A device +//! that imports no host memory, and a system that maps read-only views (macOS, whose buffers take +//! no twin), say so and pass. + +use crate::{ + Buffer, CommandBufferStatus, Device, DeviceKind, DeviceOptions, HostMemory, ImportGate, + ImportRequest, Origin, ResourceOptions, Size, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::device::{ContainmentPolicy, DevicePolicy, GuestIsolation}; +use metal2vulkan::metal::PixelFormat; +use std::alloc::Layout; +use std::ptr::NonNull; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +const WAIT: Duration = Duration::from_secs(120); +/// The screen-sized image a window server reads every frame: 3648 x 2038 BGRA texels. +const WIDTH: u64 = 3648; +const HEIGHT: u64 = 2038; +const ROW: u64 = WIDTH * 4; +/// The image's bytes, rounded up to whole pages of 64 KiB. +const SCREEN: usize = ((ROW * HEIGHT) as usize).next_multiple_of(1 << 16); +/// A small buffer's bytes. +const SMALL: usize = 64 * 1024; + +/// Host memory of whole pages in a pattern of its own, freed when dropped (after the device). +struct Pages { + pointer: NonNull, + layout: Layout, +} + +impl Pages { + fn new(length: usize, seed: u8) -> 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(layout) }).unwrap(); + let pages = Pages { pointer, layout }; + pages.write(0, &pattern(length, seed)); + pages + } + + fn bytes(&self) -> Vec { + // SAFETY: the allocation's bytes, which no command writes now. + unsafe { std::slice::from_raw_parts(self.pointer.as_ptr(), self.layout.size()) }.to_vec() + } + + fn write(&self, at: usize, bytes: &[u8]) { + assert!(at + bytes.len() <= self.layout.size()); + // SAFETY: the allocation's bytes, which no command uses now. + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + self.pointer.as_ptr().add(at), + bytes.len(), + ) + }; + } + + /// A no-copy buffer of Metal's private option bit 24 over the pages, under `gate`. + fn private_bit_buffer(&self, device: &Device, gate: Option) -> Buffer { + // SAFETY: the pages outlive the buffer and the device (dropped after both). + let memory = unsafe { HostMemory::new(self.pointer) }; + let memory = match gate { + Some(gate) => memory.with_import_gate(gate), + None => memory, + }; + // SAFETY: as above. + unsafe { + device.new_buffer_with_bytes_no_copy( + memory, + self.layout.size() as u64, + private_bit(), + None, + ) + } + .expect("a buffer of bit 24 over the pages") + } +} + +impl Drop for Pages { + fn drop(&mut self) { + // SAFETY: allocated with this layout in `new`. + unsafe { std::alloc::dealloc(self.pointer.as_ptr(), self.layout) }; + } +} + +/// `length` bytes of a pattern of `seed`'s, none of them zero. +fn pattern(length: usize, seed: u8) -> Vec { + (0..length) + .map(|at| (at as u8).wrapping_mul(31).wrapping_add(seed) | 1) + .collect() +} + +/// `Shared` with Metal's private option bit 24. +fn private_bit() -> ResourceOptions { + ResourceOptions::from_raw(ResourceOptions::shared().raw() | ResourceOptions::PRIVATE_BIT) + .unwrap() +} + +/// The test's device, under `policy` where given; `None` where read twins cannot be made here +/// (said). +fn device(policy: Option) -> Option { + if crate::read_only_view::VIEWS_DROP_WRITES { + eprintln!("READ-TWIN: bit 24 maps a read-only view here; nothing to test"); + return None; + } + let mut options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + ..DeviceOptions::default() + }; + if let Some(policy) = policy { + options.policy = policy; + } + let device = Device::system_default_with(&options).unwrap(); + if device.shared().host_import.is_err() { + eprintln!("READ-TWIN: the device imports no host memory here; nothing to test"); + return None; + } + // Its in-place check's own imports land in no count compared below: settled first. + let exportable = crate::device::lock(&device.shared().memory) + .fd_buffer_types + .is_ok(); + if exportable { + assert!(device.settle_in_place_checks(Duration::from_secs(120))); + } + Some(device) +} + +/// Commit one command buffer whose blit encoder `encode` fills, wait for it, and answer its +/// status. +fn blit( + device: &Device, + encode: impl FnOnce(&mut crate::BlitCommandEncoder), +) -> CommandBufferStatus { + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encode(&mut encoder); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + command_buffer.status() +} + +/// A buffer of the device's own of `length` bytes. +fn own(device: &Device, length: usize) -> Buffer { + device + .new_buffer(length as u64, ResourceOptions::shared()) + .unwrap() +} + +/// `buffer`'s first `length` bytes as the CPU reads them. +fn contents(buffer: &Buffer, length: usize) -> Vec { + let at = buffer.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command writes now. + unsafe { std::slice::from_raw_parts(at.as_ptr(), length) }.to_vec() +} + +/// `buffer`'s bytes as a later command buffer's copy out of it reads them. +fn gpu_bytes(device: &Device, buffer: &Buffer, length: usize) -> Vec { + let out = own(device, length); + let status = blit(device, |encoder| { + encoder + .copy_from_buffer_to_buffer(buffer, 0, &out, 0, length as u64) + .unwrap(); + }); + assert_eq!(status, CommandBufferStatus::Completed); + contents(&out, length) +} + +/// What the commits' copies in did between two counts: the copies compared, their bytes, and +/// the threads the comparisons started. +fn compared(before: &WorkCounts, after: &WorkCounts) -> [u64; 3] { + [ + after.copied_copy_ins_compared - before.copied_copy_ins_compared, + after.copied_copy_in_bytes_compared - before.copied_copy_in_bytes_compared, + after.copied_compare_threads - before.copied_compare_threads, + ] +} + +#[test] +fn a_screen_sized_private_bit_buffer_is_read_in_place_by_blits() { + let pages = Pages::new(SCREEN, 3); + let Some(device) = device(None) else { + return; + }; + let before = device.work_counts(); + let buffer = pages.private_bit_buffer(&device, None); + let after = device.work_counts(); + assert_eq!( + after.copied_read_only_memory - before.copied_read_only_memory, + 1 + ); + assert_eq!( + after.read_twins_made - before.read_twins_made, + 1, + "a twin made" + ); + assert!(buffer.read_twin().is_some()); + + // A copy into a texture, the window server's read, and one into a buffer, in one command + // buffer: both through the twin, the commit comparing nothing. + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::BGRA8Unorm, WIDTH, HEIGHT, false); + descriptor.resource_options = ResourceOptions::private(); + let texture = device.new_texture(&descriptor).unwrap(); + let out = own(&device, SCREEN); + let before = device.work_counts(); + let status = blit(&device, |encoder| { + encoder + .copy_from_buffer_to_texture( + &buffer, + 0, + ROW, + 0, + Size::new(WIDTH, HEIGHT, 1), + &texture, + 0, + 0, + Origin::new(0, 0, 0), + crate::BlitOption::None, + ) + .unwrap(); + encoder + .copy_from_buffer_to_buffer(&buffer, 0, &out, 0, SCREEN as u64) + .unwrap(); + }); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert_eq!(after.read_twin_blit_reads - before.read_twin_blit_reads, 2); + assert_eq!(compared(&before, &after), [0, 0, 0], "nothing compared"); + eprintln!( + "READ-TWIN: two blits out of a {SCREEN}-byte buffer of bit 24: copies in compared {:?} \ + (copies, bytes, threads), unused {}", + compared(&before, &after), + after.copied_copy_ins_unused - before.copied_copy_ins_unused + ); + assert!( + contents(&out, SCREEN) == pages.bytes(), + "the buffer copy holds the pages" + ); + let texels = own(&device, (ROW * HEIGHT) as usize); + let status = blit(&device, |encoder| { + encoder + .copy_from_texture_to_buffer( + &texture, + 0, + 0, + Origin::new(0, 0, 0), + Size::new(WIDTH, HEIGHT, 1), + &texels, + 0, + ROW, + 0, + crate::BlitOption::None, + ) + .unwrap(); + }); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + contents(&texels, (ROW * HEIGHT) as usize) == pages.bytes()[..(ROW * HEIGHT) as usize], + "the texture holds the pages' texels" + ); + + // A CPU write reaches the next command buffer in place, nothing copied in. + pages.write(1 << 20, &[0x7e; 4096]); + let before = device.work_counts(); + assert!( + gpu_bytes(&device, &buffer, SCREEN) == pages.bytes(), + "the CPU's write read" + ); + let after = device.work_counts(); + assert_eq!(compared(&before, &after), [0, 0, 0]); + assert_eq!(after.copied_copy_in_bytes, before.copied_copy_in_bytes); + + // A fill and a copy out in one command buffer: the copy reads the fill back, through the + // buffer's copy, which the commit compares; the pages never take it. + let kept = pages.bytes(); + let back = own(&device, SMALL); + let before = device.work_counts(); + let status = blit(&device, |encoder| { + encoder.fill_buffer(&buffer, 0..SMALL as u64, 0x5a).unwrap(); + encoder + .copy_from_buffer_to_buffer(&buffer, 0, &back, 0, SMALL as u64) + .unwrap(); + }); + let after = device.work_counts(); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + contents(&back, SMALL) == vec![0x5a; SMALL], + "the same command buffer reads the fill back" + ); + assert_eq!( + after.read_twin_reads_after_writes - before.read_twin_reads_after_writes, + 1 + ); + assert_eq!(after.read_twin_blit_reads, before.read_twin_blit_reads); + let [copies, bytes, threads] = compared(&before, &after); + eprintln!( + "READ-TWIN: a fill and a copy out of it in one command buffer: copies in compared \ + {copies} copies, {bytes} bytes, {threads} threads" + ); + assert_eq!(copies, 1, "the copy route compares the buffer's copy"); + assert!(pages.bytes() == kept, "the pages never took the fill"); + // The next command buffer reads the pages, in place again. + let before = device.work_counts(); + assert!( + gpu_bytes(&device, &buffer, SCREEN) == kept, + "the next command buffer reads the pages" + ); + let after = device.work_counts(); + assert_eq!(after.read_twin_blit_reads - before.read_twin_blit_reads, 1); + assert_eq!(compared(&before, &after), [0, 0, 0]); + assert_eq!(after.read_twin_writes_refused, 0); + drop((buffer, texture, out, texels, back)); +} + +#[test] +fn every_store_into_a_private_bit_buffer_leaves_its_pages() { + let pages = Pages::new(SMALL, 5); + let Some(device) = device(None) else { + return; + }; + let buffer = pages.private_bit_buffer(&device, None); + assert!(buffer.read_twin().is_some(), "a twin made"); + let kept = pages.bytes(); + // A command buffer's use of it, through its twin: the device's live buffers list the buffer, + // reached unnamed from here. + assert!(gpu_bytes(&device, &buffer, SMALL) == kept); + // A blit's fill, and its copy into the buffer. + let source = own(&device, SMALL); + // SAFETY: the buffer's bytes, which no command uses now. + unsafe { std::ptr::write_bytes(source.contents().unwrap().as_ptr(), 0x33, SMALL) }; + let status = blit(&device, |encoder| { + encoder.fill_buffer(&buffer, 256..4096, 0xc4).unwrap(); + }); + assert_eq!(status, CommandBufferStatus::Completed); + assert!(pages.bytes() == kept, "a fill leaves the pages"); + let status = blit(&device, |encoder| { + encoder + .copy_from_buffer_to_buffer(&source, 0, &buffer, 0, SMALL as u64) + .unwrap(); + }); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + pages.bytes() == kept, + "a copy into the buffer leaves the pages" + ); + // A kernel's store into it at a slot (`out`), and through its address loaded from memory. + 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 = (0..16u32).flat_map(u32::to_le_bytes).collect(); + 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(&buffer), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(8, 1, 1), 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); + assert!(pages.bytes() == kept, "a kernel's stores leave the pages"); + // A later command buffer reads the pages in place. + let before = device.work_counts(); + assert!( + gpu_bytes(&device, &buffer, SMALL) == kept, + "a later command buffer reads the pages" + ); + let after = device.work_counts(); + assert_eq!(after.read_twin_blit_reads - before.read_twin_blit_reads, 1); + assert_eq!(after.read_twin_writes_refused, 0); + drop((buffer, source, state, queue)); +} + +#[test] +fn a_write_of_the_twin_itself_is_refused_and_would_reach_the_pages() { + let pages = Pages::new(SMALL, 7); + let Some(device) = device(None) else { + return; + }; + let buffer = pages.private_bit_buffer(&device, None); + let twin = buffer.read_twin().expect("a twin made"); + let kept = pages.bytes(); + // The guard: the fill is refused, its command buffer failed, the pages kept. + let before = device.work_counts(); + let status = blit(&device, |encoder| { + encoder.fill_buffer(&twin, 0..4096, 0xe1).unwrap(); + }); + let after = device.work_counts(); + assert_eq!( + status, + CommandBufferStatus::Error, + "the command buffer fails" + ); + assert_eq!( + after.read_twin_writes_refused - before.read_twin_writes_refused, + 1 + ); + assert!(pages.bytes() == kept, "the guard keeps the pages"); + // The negative control: with the guard off on this thread, the same fill reaches the pages, + // which the twin is in place. + crate::read_twin::UNGUARDED.with(|unguarded| unguarded.set(true)); + let status = blit(&device, |encoder| { + encoder.fill_buffer(&twin, 0..4096, 0xe1).unwrap(); + }); + crate::read_twin::UNGUARDED.with(|unguarded| unguarded.set(false)); + assert_eq!(status, CommandBufferStatus::Completed); + assert!( + pages.bytes()[..4096] == [0xe1; 4096], + "unguarded, a write through the twin changes the pages" + ); + drop((twin, buffer)); +} + +#[test] +fn no_twin_where_the_pages_import_would_be_a_copy() { + let pages = Pages::new(SMALL, 9); + let Some(device) = device(None) else { + return; + }; + // The caller's gate refuses the import: the twin's would be a copy. + let asked: Arc>> = Arc::default(); + let gate: ImportGate = { + let asked = Arc::clone(&asked); + Arc::new(move |request| { + asked.lock().unwrap().push(request); + false + }) + }; + let before = device.work_counts(); + let buffer = pages.private_bit_buffer(&device, Some(gate)); + let after = device.work_counts(); + assert_eq!(after.read_twins_made, before.read_twins_made, "no twin"); + assert_eq!( + after.read_twins_unimported - before.read_twins_unimported, + 1 + ); + assert!(buffer.read_twin().is_none()); + // Its copy serves its reads, and drops its writes, as before. + let kept = pages.bytes(); + let status = blit(&device, |encoder| { + encoder.fill_buffer(&buffer, 0..4096, 0x11).unwrap(); + }); + assert_eq!(status, CommandBufferStatus::Completed); + assert!(gpu_bytes(&device, &buffer, SMALL) == kept); + assert!(pages.bytes() == kept); + drop(buffer); + // Pages the process maps read-only: their import would be a copy too. + #[cfg(target_os = "linux")] + { + let host = super::copied_device::ReadOnlyHost::new(31); + let calls: Arc = Arc::default(); + let gate: ImportGate = Arc::new(|_| true); + let before = device.work_counts(); + // SAFETY: the view outlives the buffer and the device (dropped after both). + let buffer = unsafe { + device.new_buffer_with_bytes_no_copy( + host.memory(gate, &calls), + host.length(), + private_bit(), + None, + ) + } + .unwrap(); + let after = device.work_counts(); + assert_eq!(after.read_twins_made, before.read_twins_made, "no twin"); + assert_eq!( + after.read_twins_unimported - before.read_twins_unimported, + 1 + ); + assert!(buffer.read_twin().is_none()); + drop(buffer); + } +} + +#[test] +fn no_twin_where_the_policy_contains_no_access() { + let pages = Pages::new(SMALL, 11); + let mut policy = DevicePolicy::UNTRUSTED; + policy.containment = ContainmentPolicy::UnsafeOff; + policy.isolation = GuestIsolation::Off; + let Some(device) = device(Some(policy)) else { + return; + }; + let before = device.work_counts(); + let buffer = pages.private_bit_buffer(&device, None); + let after = device.work_counts(); + assert_eq!(after.read_twins_made, before.read_twins_made, "no twin"); + assert_eq!( + after.read_twins_uncontained - before.read_twins_uncontained, + 1 + ); + assert!(buffer.read_twin().is_none()); + let before = device.work_counts(); + assert!( + gpu_bytes(&device, &buffer, SMALL) == pages.bytes(), + "read through its copy" + ); + let after = device.work_counts(); + assert_eq!(after.read_twin_blit_reads, before.read_twin_blit_reads); + assert_eq!(compared(&before, &after)[0], 1, "its copy compared"); + drop(buffer); +} diff --git a/crates/metal2vulkan-runtime/src/used_resources.rs b/crates/metal2vulkan-runtime/src/used_resources.rs index b9f7aa679..45c21339f 100644 --- a/crates/metal2vulkan-runtime/src/used_resources.rs +++ b/crates/metal2vulkan-runtime/src/used_resources.rs @@ -290,6 +290,14 @@ impl Owners { registry.owners.entry(key).or_insert((owner, id, made)); } + /// Keep `twin`, the read twin of `of` (`read_twin.rs`), made after `made` submissions, by its + /// key with `of` as its owner: a command that reads `of` through its twin uses `of`, as it + /// would through its copy, and the twin, the runtime's, is never listed. + pub(super) fn read_twin(&self, twin: &Buffer, of: &Buffer, made: u64) { + let id = Owner::id_of_buffer(of); + self.insert(twin.identity().key, Owner::of_buffer(of), id, made); + } + /// Keep a buffer the program made after `made` submissions, by its key: a heap's buffer has /// its heap's, which `HeapKeys` holds. pub(super) fn buffer(&self, buffer: &Buffer, made: u64) { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 3581faab1..1c9be062f 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -480,6 +480,14 @@ pub(crate) struct Counters { copied_base_blocks_read: AtomicU64, copied_base_blocks_read_back: AtomicU64, copied_compare_threads: AtomicU64, + copied_copy_ins_compared: AtomicU64, + copied_copy_in_bytes_compared: AtomicU64, + read_twins_made: AtomicU64, + read_twins_unimported: AtomicU64, + read_twins_uncontained: AtomicU64, + read_twin_blit_reads: AtomicU64, + read_twin_reads_after_writes: AtomicU64, + read_twin_writes_refused: AtomicU64, host_ram_copies: AtomicU64, host_ram_copy_bytes: AtomicU64, host_ram_copy_dispatches: AtomicU64, @@ -4429,6 +4437,47 @@ impl Counters { (self.copied_compare_threads).fetch_add(threads, Ordering::Relaxed); } + /// A commit's copy in compared `copies` copied host buffers, `bytes` of them in all (the + /// bytes no log skipped), which a command of its command buffer used or may have reached + /// unnamed (`copied.rs`). + pub(crate) fn copied_copy_ins_compared(&self, copies: u64, bytes: u64) { + (self.copied_copy_ins_compared).fetch_add(copies, Ordering::Relaxed); + (self.copied_copy_in_bytes_compared).fetch_add(bytes, Ordering::Relaxed); + } + + /// A read twin was made for a no-copy buffer whose GPU writes are dropped (`read_twin.rs`). + pub(crate) fn read_twin_made(&self) { + (self.read_twins_made).fetch_add(1, Ordering::Relaxed); + } + + /// No read twin was made for a no-copy buffer whose GPU writes are dropped + /// (`read_twin.rs`): its pages' import would have been a copy, or failed, or the device's + /// policy contains no access (`uncontained`). + pub(crate) fn read_twin_not_made(&self, uncontained: bool) { + match uncontained { + true => &self.read_twins_uncontained, + false => &self.read_twins_unimported, + } + .fetch_add(1, Ordering::Relaxed); + } + + /// A blit read a buffer's bytes through its read twin, in place (`read_twin.rs`). + pub(crate) fn read_twin_blit_read(&self) { + (self.read_twin_blit_reads).fetch_add(1, Ordering::Relaxed); + } + + /// A command that may read a buffer through its read twin read its copy instead, as an + /// earlier command of its command buffer may have written the copy (`read_twin.rs`). + pub(crate) fn read_twin_read_after_write(&self) { + (self.read_twin_reads_after_writes).fetch_add(1, Ordering::Relaxed); + } + + /// An encoder refused a command whose uses write a read twin (`read_twin.rs`): never, but + /// for a defect of the runtime's. + pub(crate) fn read_twin_write_refused(&self) { + (self.read_twin_writes_refused).fetch_add(1, 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) { @@ -8970,6 +9019,35 @@ pub struct WorkCounts { /// splits its blocks across up to four threads, the calling one among them, each run at /// least 8 MiB, and the threads it started end before it returns. pub copied_compare_threads: u64, + /// The copied host buffers commits' copies in compared, one per copy and commit: a command + /// of the committed command buffer used one, or may have reached it unnamed (the + /// counterpart of `copied_copy_ins_unused`). + pub copied_copy_ins_compared: u64, + /// The bytes of copied host buffers commits' copies in compared with their pages: every + /// byte of a copy compared, but those its pages' log reported unwritten + /// (`copied_copy_in_bytes_skipped`). + pub copied_copy_in_bytes_compared: u64, + /// The read twins made (`read_twin.rs`): of a no-copy buffer of Metal's private option bit + /// 24 where the system maps no read-only view of its pages, the runtime's own buffer over the + /// pages in place, which the commands that cannot write the buffer read instead of its copy. + pub read_twins_made: u64, + /// The no-copy buffers of bit 24 that took no read twin because their pages' import would + /// have been a copy (the caller's gate refused it, the process cannot write the pages, a + /// live import holds some of them) or failed: they are their copy alone. + pub read_twins_unimported: u64, + /// The no-copy buffers of bit 24 that took no read twin because the device's policy contains + /// no access (`ContainmentPolicy::UnsafeOff`): a store may reach past what it names. + pub read_twins_uncontained: u64, + /// The blit reads of a buffer's bytes made through its read twin, in place, one per copy + /// whose source it is. + pub read_twin_blit_reads: u64, + /// The reads a read twin could have taken that read the buffer's copy instead, one per + /// command: an earlier command of the command buffer may have written the copy, and a later + /// one reads that write back, as Metal's GPU caches let it. + pub read_twin_reads_after_writes: u64, + /// The commands an encoder refused because their uses write a read twin: never, but for a + /// defect of the runtime's, which the refusal keeps from reaching the pages. + pub read_twin_writes_refused: u64, /// The host bytes the live copied host buffers' bases hold (a gauge): their tags, a 64th of /// each copy's length, and the bytes of those kept in host memory. pub copied_base_host_bytes: u64, @@ -11436,6 +11514,16 @@ impl Device { copied_base_blocks_read_back: (counters.copied_base_blocks_read_back) .load(Ordering::Relaxed), copied_compare_threads: counters.copied_compare_threads.load(Ordering::Relaxed), + copied_copy_ins_compared: counters.copied_copy_ins_compared.load(Ordering::Relaxed), + copied_copy_in_bytes_compared: (counters.copied_copy_in_bytes_compared) + .load(Ordering::Relaxed), + read_twins_made: counters.read_twins_made.load(Ordering::Relaxed), + read_twins_unimported: counters.read_twins_unimported.load(Ordering::Relaxed), + read_twins_uncontained: counters.read_twins_uncontained.load(Ordering::Relaxed), + read_twin_blit_reads: counters.read_twin_blit_reads.load(Ordering::Relaxed), + read_twin_reads_after_writes: (counters.read_twin_reads_after_writes) + .load(Ordering::Relaxed), + read_twin_writes_refused: counters.read_twin_writes_refused.load(Ordering::Relaxed), copied_base_host_bytes, copied_base_device_bytes, copied_base_host_blocks: self.shared().copied.base_host_blocks(), diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index de908c319..bf169b0ae 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// 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 = 2268; +pub const RUNTIME_VERSION: u32 = 2269; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 40d89bba5..f20119027 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2790,8 +2790,10 @@ field metal2vulkan-runtime::WorkCounts.copied_bases_made pub copied_bases_made: field metal2vulkan-runtime::WorkCounts.copied_bases_refused pub copied_bases_refused: u64 field metal2vulkan-runtime::WorkCounts.copied_compare_threads pub copied_compare_threads: u64 field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes pub copied_copy_in_bytes: u64 +field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes_compared pub copied_copy_in_bytes_compared: u64 field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes_skipped pub copied_copy_in_bytes_skipped: u64 field metal2vulkan-runtime::WorkCounts.copied_copy_ins_after_waits pub copied_copy_ins_after_waits: u64 +field metal2vulkan-runtime::WorkCounts.copied_copy_ins_compared pub copied_copy_ins_compared: u64 field metal2vulkan-runtime::WorkCounts.copied_copy_ins_unused pub copied_copy_ins_unused: 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 @@ -3356,6 +3358,12 @@ field metal2vulkan-runtime::WorkCounts.rate_map_region_runs pub rate_map_region_ field metal2vulkan-runtime::WorkCounts.rate_map_run_region_draws pub rate_map_run_region_draws: u64 field metal2vulkan-runtime::WorkCounts.rate_map_runs_every_region pub rate_map_runs_every_region: u64 field metal2vulkan-runtime::WorkCounts.rate_map_straddling_triangles pub rate_map_straddling_triangles: u64 +field metal2vulkan-runtime::WorkCounts.read_twin_blit_reads pub read_twin_blit_reads: u64 +field metal2vulkan-runtime::WorkCounts.read_twin_reads_after_writes pub read_twin_reads_after_writes: u64 +field metal2vulkan-runtime::WorkCounts.read_twin_writes_refused pub read_twin_writes_refused: u64 +field metal2vulkan-runtime::WorkCounts.read_twins_made pub read_twins_made: u64 +field metal2vulkan-runtime::WorkCounts.read_twins_uncontained pub read_twins_uncontained: u64 +field metal2vulkan-runtime::WorkCounts.read_twins_unimported pub read_twins_unimported: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_by_coverage pub reading_draws_by_coverage: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_in_place pub reading_draws_in_place: u64 field metal2vulkan-runtime::WorkCounts.reading_draws_leading_covered_over_half pub reading_draws_leading_covered_over_half: u64 diff --git a/docs/API.md b/docs/API.md index cebd231cf..796d752b0 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2926,7 +2926,8 @@ bound. of, is made as without it, and reports its options without it, as Metal's does. A no-copy buffer or heap with the bit drops the GPU's writes as Metal's does: on macOS its pages are imported through a read-only view of them, announcing nothing; elsewhere it is made over a copy - of them that drops the GPU's writes (`copied-host-pages`). A buffer of the runtime's memory or a texture descriptor with the bit is + of them that drops the GPU's writes (`copied-host-pages`), a no-copy buffer's blit copies out of + it reading the pages in place where they import in place (`copied-host-pages` says how). A buffer of the runtime's memory or a texture descriptor with the bit is refused, as Metal ends the process there; a buffer placed in a heap without the bit is made as without it, announcing nothing. Cost: the GPU's writes reach the resource's memory, the CPU and later command buffers, where Metal's never reach them. @@ -3695,7 +3696,14 @@ bound. out of the pages, the gate not asked (`copied_read_only_memory`): the copy drops the GPU's writes as a copy of read-only pages does, though a command buffer committed before the writer's batch completed may still read them, and a render pass's store-out into it completes where Metal's - faults its command buffer. On macOS the pages are imported through a read-only view of them. A + faults its command buffer. A blit's copy out of a no-copy buffer of such memory, into a buffer + or a texture, reads its pages in place instead, through a read twin of the buffer imported over + them (`read_twins_made`), where they import in place and the device's policy contains every + access (no twin otherwise: `read_twins_unimported`, `read_twins_uncontained`), while no earlier + command of its command buffer may have written the buffer (`read_twin_blit_reads`; after one, + `read_twin_reads_after_writes`, the copy); no command writes the twin, and one that would fails + its command buffer (`read_twin_writes_refused`). On macOS the pages are imported through a + read-only view of them. A buffer's or heap's rebind is copied the same way, its heap's bound textures and its images in place made again over the copy, and a buffer's rebind to bytes at another offset in their page under a texture planned at the old one is a copy diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 47bea668c..3b1200eb0 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -990,7 +990,17 @@ driver's. Each is open work. RTX 5080 Laptop GPU, commit to completion, median of 300: beside a live 16 MiB copy whose pages carry no log, a 256-byte fill into a writable 16 MiB no-copy buffer took 1.5 ms (49 µs beside a 64 KiB copy, into a 64 KiB buffer), as every commit compares the copy, and the same fill into the - copy 2.6 ms, its completion restoring it; into the 64 KiB copy 53 µs. + copy 2.6 ms, its completion restoring it; into the 64 KiB copy 53 µs. A no-copy buffer of bit-24 + memory whose pages import in place, on a device whose policy contains every access (not + `ContainmentPolicy::UnsafeOff`), also takes a read twin (`read_twin.rs`): the runtime's own + buffer over the same pages, outside the Metal address space, which no command writes (an encoder + refuses a command that would, failing its command buffer: `WorkCounts::read_twin_writes_refused`). + A blit's copy out of the buffer, into a buffer or a texture, reads the pages through the twin, + so a command buffer that reads the buffer only so uses none of its copy and its commit compares + none of it (`WorkCounts::read_twin_blit_reads`, `copied_copy_ins_compared`); after a command of + its command buffer that may have written the buffer, its copy is read instead, so the command + buffer reads its own dropped write back (`read_twin_reads_after_writes`). Every other use reads + the copy as above. - **A function linked from a module that declares function constants** is refused (`Unsupported{Linking; NotImplemented}` at a surviving call to the stub, `canon::link`), keyed on