From 442dcd08c9d4e5bf828c18d7da4f60dbf0b6b3f1 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 12:43:26 -0800 Subject: [PATCH] Copied host memory: a copy that drops the GPU's writes takes its guest RAM's log, and a draw that only reads through loaded addresses leaves unnamed copies uncompared A copy of memory of Metal's private option bit 24 (on a system that maps no read-only view of the pages) skipped the routing of its guest RAM runs, so it kept no log: every commit compared every byte of it, and every completion of a command buffer with a root table compared every copy. In consumer boots that is about 29.5 MiB per commit and per completion over 37-44 objects. - Commit (copy in): a no-copy buffer, heap or rebind whose GPU writes are dropped has its runs asked as a writable one's are (routes_runs), so its copy takes the RAM's log and copies in only the pages the log reports written. It is still never bound in the RAM's chunk: the in-chunk binding is filtered on drops_writes. macOS keeps its read-only view and asks no runs. - Completion (merge back): State::writes_unnamed narrows reaches_unnamed to commands whose functions may write memory. A draw's root table writes only where the vertex or fragment function may store or update memory (GraphicsState::vertex_writes_memory, fragment_writes_memory) or the pipeline has another stage; kernels, tile functions, replay tables and records resolved by host steps stay as they were (every copy compared). The compare itself stays: in a dropping copy it is what restores the dropped bytes, so later command buffers read the pages' bytes. Tests: host_ram_copy_device a_private_bit_copy_over_the_pages_copies_in_only_the_pages_the_log_reports (one page written: length - page bytes not compared, the GPU's fill dropped) and copied_device a_merge_back_skips_a_copy_when_a_draw_only_reads_through_loaded_addresses (root table noted, merge back compared 0). Docs: copied.rs, FAST-PATHS known gap, HOWTO section on copies. (cherry picked from commit 61a9a4f4603a4c080ba5a4f2e204668ae621cf41) --- crates/metal2vulkan-runtime/src/binding.rs | 22 ++++- .../src/buffer_descriptor.rs | 37 ++++--- .../src/command_buffer/completion.rs | 2 +- .../src/command_buffer/mod.rs | 19 +++- crates/metal2vulkan-runtime/src/compute.rs | 2 + crates/metal2vulkan-runtime/src/copied.rs | 19 ++-- .../metal2vulkan-runtime/src/gpu_execute.rs | 1 + crates/metal2vulkan-runtime/src/render.rs | 13 +++ .../src/render/draw_again/rebound.rs | 1 + .../src/render/tile_dispatch.rs | 2 + .../src/tests/copied_device.rs | 95 +++++++++++++++++- .../src/tests/host_ram_copy_device.rs | 98 +++++++++++++++++++ docs/FAST-PATHS.md | 17 ++-- docs/HOWTO.md | 7 +- 14 files changed, 296 insertions(+), 39 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/binding.rs b/crates/metal2vulkan-runtime/src/binding.rs index e1ffcccf0..ee08571ea 100644 --- a/crates/metal2vulkan-runtime/src/binding.rs +++ b/crates/metal2vulkan-runtime/src/binding.rs @@ -410,6 +410,10 @@ pub(super) struct Command<'a> { pub(super) descriptor_ranges: &'a [DescriptorRange], /// Each stage's root table, by the stages its push hole names. pub(super) root_tables: Vec<(metal2vulkan::vk::ShaderStageFlags, &'a RootTable)>, + /// Whether a function that reads one of them may write memory (stores or atomic updates, + /// `StageInterface::writes_memory`): where none does, nothing writes memory through them + /// (`State::writes_unnamed`). + pub(super) root_writes: bool, pub(super) push_holes: &'a [PushHole], /// The command's own resources beyond the plan's uses (an index buffer, indirect arguments). pub(super) uses: &'a [ResourceUse], @@ -846,7 +850,10 @@ pub(super) fn bind_into( } let mut roots = Vec::with_capacity(command.root_tables.len()); for &(stages, table) in &command.root_tables { - roots.push((stages, root_table(device, state, table)?)); + roots.push(( + stages, + root_table(device, state, table, command.root_writes)?, + )); } let mut holes = Vec::with_capacity(command.push_holes.len()); for hole in command.push_holes { @@ -2355,9 +2362,14 @@ fn descriptor( } /// Upload `table` with a fresh sink's device address in its sink entry, at a 32-byte-aligned -/// device address, noted for its command buffer's resident set (`live_buffers.rs`); its device -/// address. -fn root_table(device: &Device, state: &mut State, table: &RootTable) -> Result { +/// device address, noted for its command buffer's resident set (`live_buffers.rs`), read by +/// functions that may write memory where `writes`; its device address. +fn root_table( + device: &Device, + state: &mut State, + table: &RootTable, + writes: bool, +) -> Result { let no_address = || internal("a root table on a device without device addresses"); let sink = state .uploads @@ -2378,7 +2390,7 @@ fn root_table(device: &Device, state: &mut State, table: &RootTable) -> Result self.route_runs(call, importer, resolver, &window)?, + // writes are dropped is never bound in a chunk: it imports a read-only view of its pages, + // or is a copy of them, whose runs are asked all the same, so that the copy's commits + // copy in only the pages the RAM's log reports written ([`routes_runs`]). + let routed = match &runs { + Some(resolver) if routes_runs(drops_writes) => { + self.route_runs(call, importer, resolver, &window)? + } _ => None, }; // SAFETY: the window's pages are the bytes of the run in the RAM (the resolver's // contract, `HostMemory::with_runs`). - let in_chunk = (routed.as_ref()) + let in_chunk = (routed.as_ref().filter(|_| !drops_writes)) .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 @@ -876,9 +879,10 @@ impl Device { // the chunk's import, with no import of its own, no pin and no gate, unless the // bytes moved in their page, which take the copy laid out at the old offset. // Others take the paths below, the runs kept with the new pages. A buffer whose - // GPU writes are dropped is never routed. - let routed = match (&runs, drops_writes) { - (Some(resolver), false) => { + // GPU writes are dropped is never bound in a chunk, but its copy's runs are asked + // for the RAM's log ([`routes_runs`]). + let routed = match &runs { + Some(resolver) if routes_runs(drops_writes) => { let was_settled = settled.take().is_some(); let routed = self.route_runs(call, importer, resolver, &window); if was_settled { @@ -890,9 +894,9 @@ impl Device { }; // SAFETY: the window's pages are the bytes of the run in the RAM (the resolver's // contract, `HostMemory::with_runs`). - let in_chunk = (routed.as_ref().filter(|_| !moved)).and_then(|routed| unsafe { - self.bind_in_chunk(importer, routed, &window, length) - }); + let in_chunk = (routed.as_ref().filter(|_| !moved && !drops_writes)).and_then( + |routed| unsafe { self.bind_in_chunk(importer, routed, &window, length) }, + ); let chunk_bound = in_chunk.is_some(); let kept_runs = routed.as_ref().map(Routed::kept); // Whether an import alive now holds every page of them: counted once the import @@ -2000,6 +2004,17 @@ struct HostWindow { source: Option, } +/// Whether a no-copy buffer, heap or rebind whose pages the caller resolves to runs of a guest RAM +/// (`HostMemory::with_runs`) has them asked, where its GPU writes are dropped where `drops_writes`: +/// every one but memory whose GPU writes Metal's private option bit 24 drops on macOS, which +/// imports a read-only view of its pages (`read_only_view.rs`). Elsewhere such memory is a copy +/// of its pages (`copied.rs`), never bound in the RAM's chunk, whose runs give it the RAM's log of +/// the writes to them (`dirty_pages::PagesLog`), so its commits copy in only the pages the log +/// reports written, as a writable copy's do, where they compared every byte. +fn routes_runs(drops_writes: bool) -> bool { + !drops_writes || !crate::read_only_view::VIEWS_DROP_WRITES +} + /// Whether the process cannot write some of `host`'s pages, asked by a call that imports them /// itself (not a buffer that lies in a live import of them): such pages are a copy whose GPU /// writes are dropped (`copied.rs`), on every device, never imported and their dma-buf source diff --git a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs index 137c56bf7..b5877ee67 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/completion.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/completion.rs @@ -633,7 +633,7 @@ fn finish(watch: &Watch, lists: &mut FenceLists, mut finished: Vec<(usize, Submi let mut written = Written::default(); for (_, batch) in &finished { let buffer = &batch.buffer; - if buffer.unnoted.load(Ordering::Relaxed) || lock(&buffer.state).reaches_unnamed { + if buffer.unnoted.load(Ordering::Relaxed) || lock(&buffer.state).writes_unnamed { written = Written::all(); break; } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index e36e4a7d9..75ffb1e5b 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -925,9 +925,16 @@ pub(super) struct State { replay_tables: Vec, /// 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`). + /// host steps resolve from records (`Deferred::reaches_unnamed`). pub(super) reaches_unnamed: bool, + /// A command of it may write memory no use it noted names: one that reaches it as above + /// whose functions may write memory (stores or atomic updates, + /// `StageInterface::writes_memory`; the root table of a draw whose vertex and fragment + /// functions store nothing writes nothing through it), work on the GPU alone, or work its host + /// steps resolve from records. The merge back of copied host buffers then takes every copy as + /// written by it (`copied.rs`); a command buffer whose unnamed reach only reads leaves the + /// copies its uses did not write uncompared. + pub(super) writes_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, @@ -1035,6 +1042,7 @@ impl State { /// the submitted command buffer holds. pub(super) fn replay_table(&mut self, table: ReplayTable) { self.reaches_unnamed = true; + self.writes_unnamed = true; if !self.submitted { self.replay_tables.push(table); } @@ -1254,14 +1262,17 @@ impl State { /// Note a root table its commands read, uploaded at `table` (`upload`), whose own resident /// set is `ranges`: the commit points it at the command buffer's resident set. One a host /// step uploads after the commit is pointed now, at that set where it holds `ranges`, else - /// at a set of both made for it. + /// at a set of both made for it. `writes`: whether a function that reads it may write memory + /// ([`State::writes_unnamed`]). pub(super) fn root_table( &mut self, device: &Device, noted: NotedTable, ranges: Vec, + writes: bool, ) -> Result<(), Error> { self.reaches_unnamed = true; + self.writes_unnamed |= writes; let counts = &device.shared().counts; counts.root_table_ranges_noted(ranges.len() as u64); if self.status == CommandBufferStatus::NotEnqueued { @@ -2170,6 +2181,7 @@ impl CommandBuffer { release: None, replay_tables: Vec::new(), reaches_unnamed: false, + writes_unnamed: false, unrunnable: BTreeSet::new(), submitted_holds: Vec::new(), failed_at_commit: None, @@ -3232,6 +3244,7 @@ impl CommandBuffer { .unzip(); if segments.iter().any(|(work, _)| work.reaches_unnamed()) { state.reaches_unnamed = true; + state.writes_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. diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 28a0ed9c2..e7d59a81a 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -2416,6 +2416,8 @@ fn record( .iter() .map(|table| (metal2vulkan::vk::ShaderStageFlags::COMPUTE, table)) .collect(), + // A kernel's artifact states no proof that it stores nothing. + root_writes: true, push_holes: &commands.push_holes, uses: &command_uses, blobs: pipeline_stage diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index fa4005459..2beaa5276 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -32,9 +32,9 @@ //! since ([`CopiedBuffers::merge_back`]): a byte both changed keeps the CPU's, which the next //! 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 +//! copy where one of those may have written memory no use names (the loaded addresses of a +//! function that may store or update memory atomically, 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 @@ -42,8 +42,10 @@ //! back reports the blocks it wrote to the log as the copy's own writes, in one call //! (`DirtyPages::wrote_runs_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 +//! - **Copies in the log gates.** Where the pages' memory came with such a log (a copy that drops +//! the GPU's writes included: its guest RAM's runs are asked as a writable copy's are), 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 @@ -504,9 +506,10 @@ impl CopiedBuffers { /// /// 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 + /// every copy where a command may have written memory no use names (the loaded addresses of + /// a function that may store or update memory atomically, `StageInterface::writes_memory`; 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. diff --git a/crates/metal2vulkan-runtime/src/gpu_execute.rs b/crates/metal2vulkan-runtime/src/gpu_execute.rs index 0a40007ef..b3061ece7 100644 --- a/crates/metal2vulkan-runtime/src/gpu_execute.rs +++ b/crates/metal2vulkan-runtime/src/gpu_execute.rs @@ -704,6 +704,7 @@ fn variant_uses( heap_tables: &[], descriptor_ranges: &[], root_tables: Vec::new(), + root_writes: false, push_holes: &[], uses: &[], blobs: Vec::new(), diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 9dd33a3d3..3444c8116 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -8922,6 +8922,18 @@ impl RenderLowering { .map(|dispatch| tessellation_scan::TessellationWork::new(&self.core, dispatch)) .transpose()?; let pipeline_objects = variant.pipeline(); + // Whether a function that reads a root table may write memory: a vertex or fragment + // function the compile found storing nothing writes none (`vertex_writes_memory`, + // `fragment_writes_memory`), and any other stage (an object or mesh function, a + // synthesized one) has no such proof. + let root_writes = graphics.vertex_writes_memory + || graphics.fragment_writes_memory + || (pipeline_objects.stages.iter()).any(|module| { + !matches!( + module.stage, + metal2vulkan::vk::ShaderStage::VERTEX | metal2vulkan::vk::ShaderStage::FRAGMENT + ) + }); let mut blobs = Vec::new(); for (index, module) in pipeline_objects.stages.iter().enumerate() { // A tessellation pipeline's synthesized stages are its vertex function's. @@ -8957,6 +8969,7 @@ impl RenderLowering { .iter() .map(|(stages, table)| (*stages, table)) .collect(), + root_writes, push_holes: &commands.push_holes, uses: &commands.uses, blobs, diff --git a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs index 06b5a0793..5e3c18323 100644 --- a/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs +++ b/crates/metal2vulkan-runtime/src/render/draw_again/rebound.rs @@ -434,6 +434,7 @@ impl RenderLowering { heap_tables: &[], descriptor_ranges: &commands.descriptor_ranges, root_tables: Vec::new(), + root_writes: false, push_holes: &commands.push_holes, uses: &commands.uses, blobs: Vec::new(), diff --git a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs index f165125dc..3bb370ab3 100644 --- a/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs +++ b/crates/metal2vulkan-runtime/src/render/tile_dispatch.rs @@ -1055,6 +1055,8 @@ impl RenderLowering { .iter() .map(|table| (metal2vulkan::vk::ShaderStageFlags::COMPUTE, table)) .collect(), + // A tile function's artifact states no proof that it stores nothing. + root_writes: true, push_holes: &commands.push_holes, uses: &commands.uses, blobs: pipeline_stage diff --git a/crates/metal2vulkan-runtime/src/tests/copied_device.rs b/crates/metal2vulkan-runtime/src/tests/copied_device.rs index f42ad02d7..b4cfaa478 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied_device.rs @@ -12,7 +12,9 @@ //! The same without a gate. //! - **Coherence.** In each, the GPU reads the caller's bytes; a CPU write before a commit reaches //! the GPU, those bytes alone copied in; a fill reaches the caller's pages at its completion, -//! those bytes alone merged back. +//! those bytes alone merged back. A completion compares no copy its batch only read, nor one a +//! batch left unnamed whose draw only reads through the addresses it loads; a kernel's stores +//! through such an address still merge back. //! - **Unreadable pages** (mapped without access, memory Metal makes no buffer over) are never //! copied: the buffer is refused, as their import is. //! - **A dma-buf's mapping** (Linux, where `/dev/udmabuf` opens), whose pages the kernel's read @@ -1911,6 +1913,97 @@ fn a_write_through_an_address_no_use_names_still_merges_back() { drop((buffer, out, state, queue)); } +/// A batch whose draw reads memory through addresses it loads (a root table), with vertex and +/// fragment functions that store nothing (`GraphicsState::vertex_writes_memory`, +/// `fragment_writes_memory`), leaves a copy none of its uses wrote uncompared at its merge back: +/// the draw writes no memory its uses do not name. +#[test] +fn a_merge_back_skips_a_copy_when_a_draw_only_reads_through_loaded_addresses() { + use crate::{SamplerStateOptions, TextureDescriptor}; + use metal2vulkan::bind::SamplerDescriptor; + use metal2vulkan::metal::TextureUsage; + use metal2vulkan::metal::{PixelFormat, PrimitiveType, RenderStages, ResourceUsage}; + let Some((device, _)) = device() else { + return; + }; + let host = Host::new(15); + let asked = Arc::default(); + let buffer = host.buffer(&device, Some(gate(&asked, false))); + assert!(buffer.copied(), "the buffer is a copy"); + // The fixture's entry shape: the vertex function loads its position through the address in + // its table's entry, and the fragment function samples the texture the entry names. + let state = super::encoder_holds::render_state( + &device, + "engine/resident_draws.ll", + "rd_entry_vertex", + "rd_entry_fragment", + ); + let mut sampled = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 4, 4, false); + sampled.usage = TextureUsage::SHADER_READ; + let sampled = device.new_texture(&sampled).unwrap(); + let options = SamplerStateOptions { + support_argument_buffers: true, + ..SamplerStateOptions::default() + }; + let sampler = device + .new_sampler_state_with_options(&SamplerDescriptor::new(), options) + .unwrap(); + let position: Vec = [0.0f32, 0.0, 0.0, 1.0].map(f32::to_le_bytes).concat(); + let position = device + .new_buffer_with_bytes(&position, ResourceOptions::shared()) + .unwrap(); + let entry: Vec = [ + position.gpu_address().0, + sampled.gpu_resource_id().0, + sampler.gpu_resource_id().0, + ] + .map(u64::to_le_bytes) + .concat(); + let table = device + .new_buffer_with_bytes(&entry, ResourceOptions::shared()) + .unwrap(); + let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 16, 16, false); + target.usage = TextureUsage::RENDER_TARGET; + let target = device.new_texture(&target).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 + .render_command_encoder(&super::encoder_holds::pass(&target)) + .unwrap(); + let vertex = (position.as_resource(), RenderStages::VERTEX); + let fragment = (sampled.as_resource(), RenderStages::FRAGMENT); + for (resource, stages) in [vertex, fragment] { + (encoder.use_resource(resource, ResourceUsage::READ, stages)).unwrap(); + } + encoder.set_render_pipeline_state(&state).unwrap(); + encoder.set_vertex_buffer(Some(&table), 0, 0).unwrap(); + encoder.set_fragment_buffer(Some(&table), 0, 0).unwrap(); + (encoder.draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0)).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 compared = after.copied_merges_compared - before.copied_merges_compared; + let skipped = after.copied_merges_skipped - before.copied_merges_skipped; + eprintln!( + "COPIED: a draw through loaded addresses: {} root table ranges, merge back {compared} \ + compared, {skipped} skipped", + after.root_table_ranges_noted - before.root_table_ranges_noted, + ); + assert!( + after.root_table_ranges_noted > before.root_table_ranges_noted, + "the draw read through a root table" + ); + assert_eq!( + compared, 0, + "the copy the draw did not write is not compared" + ); + assert!(skipped >= 1); + drop((buffer, state, queue)); +} + /// `Buffer::host_backing` answers what the GPU uses for each kind of buffer: the caller's pages, /// imported by their pointer; a copy, where the gate refuses their import; a buffer placed in a /// no-copy heap its heap's; `Detached` while detached and the new pages' once rebound; and `None` diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs index 23aae3613..c8e743272 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs @@ -16,6 +16,10 @@ //! - **A copied backing over the pages** (the import gate refused, the RAM's log given) takes a //! scatter's bytes at the next commit, the log told of them; a gather after its merge back //! reads what the GPU wrote through it. +//! - **Memory of Metal's private option bit 24 over the pages**, where the system maps no +//! read-only view of them: a copy, never bound in the chunk, whose commit after the CPU wrote +//! one page compares that page alone (the RAM's log, `copied_copy_in_bytes_skipped`); the GPU's +//! writes to it are dropped. //! - **Refused**: runs off the page, empty or outside the RAM, a RAM the device does not use (or //! no longer does), bytes past the buffer and an offset off a word; no runs copy nothing. //! - **A chunk taken as an object takes it**, on a device whose thread imports ahead: a gather @@ -579,6 +583,100 @@ fn a_copied_backing_over_the_pages_takes_a_scatter_at_the_next_commit() { ); } +/// Memory of Metal's private option bit 24 over the RAM's pages, where the system maps no +/// read-only view of them: a copy whose GPU writes are dropped, never bound in the RAM's chunk, +/// whose runs give it the RAM's log, so that a commit after the CPU wrote one page compares that +/// page alone; a GPU write to it leaves the pages as they were, and a later command buffer reads +/// their bytes. +#[test] +fn a_private_bit_copy_over_the_pages_copies_in_only_the_pages_the_log_reports() { + if crate::read_only_view::VIEWS_DROP_WRITES { + eprintln!("HOST-RAM-COPY: the private bit maps a read-only view here; nothing to test"); + return; + } + let Some(device) = device() else { + return; + }; + let log = Arc::new(Log::default()); + let (ram, start) = new_ram(Some(Arc::clone(&log))); + let _used = device.use_host_ram(&ram).unwrap(); + let page = host_page(); + let length = 8 * page; + let at = (start + 300 * PAGE).next_multiple_of(page); + write_pattern(at..at + length, 21); + let options = + ResourceOptions::from_raw(ResourceOptions::default().raw() | ResourceOptions::PRIVATE_BIT) + .unwrap(); + let before = device.work_counts(); + // SAFETY: the RAM's bytes, mapped until its keep-alive goes, after every device let go. + let memory = + unsafe { HostMemory::new(NonNull::new(at as *mut u8).unwrap()) }.with_runs(itself()); + // SAFETY: as above. + let copied = + unsafe { device.new_buffer_with_bytes_no_copy(memory, length, options, None) }.unwrap(); + let after = device.work_counts(); + assert_eq!(copied.host_backing(), Some(HostBacking::Copied)); + assert_eq!( + after.copied_read_only_memory - before.copied_read_only_memory, + 1, + "a copy for the private bit" + ); + assert_eq!( + after.chunk_bound_buffers_made + after.run_bound_buffers_made, + before.chunk_bound_buffers_made + before.run_bound_buffers_made, + "never bound in the RAM's chunk" + ); + let read = || { + let out = shared(&device, length, |_| 0); + blit(&device, |encoder| { + encoder + .copy_from_buffer_to_buffer(&copied, 0, &out, 0, length) + .unwrap(); + }); + contents(&out) + }; + assert!( + read() == bytes(at..at + length), + "the copy holds the pages' bytes" + ); + // The CPU writes one page, which the RAM's log reports. + let written = at + 3 * page..at + 4 * page; + write_pattern(written.clone(), 22); + log.told(written, 0); + let before = device.work_counts(); + let out = read(); + let after = device.work_counts(); + let copied_in = after.copied_copy_in_bytes - before.copied_copy_in_bytes; + let skipped = after.copied_copy_in_bytes_skipped - before.copied_copy_in_bytes_skipped; + eprintln!( + "HOST-RAM-COPY: a private-bit copy's commit after one page written: {copied_in} bytes \ + copied in, {skipped} of {length} not compared" + ); + assert!( + out == bytes(at..at + length), + "the copy took the CPU's write" + ); + assert_eq!( + skipped, + length - page, + "only the page the log reports compared" + ); + assert!(0 < copied_in && copied_in <= page); + // The GPU's write to the copy is dropped. + let kept = bytes(at..at + length); + let before = device.work_counts(); + blit(&device, |encoder| { + encoder.fill_buffer(&copied, 0..length, 0x5a).unwrap(); + }); + let after = device.work_counts(); + assert!(bytes(at..at + length) == kept, "the GPU's write dropped"); + assert!(after.copied_dropped_bytes > before.copied_dropped_bytes); + assert!( + read() == kept, + "a later command buffer reads the pages' bytes" + ); +} + #[test] fn copies_off_the_page_outside_the_ram_or_past_the_buffer_are_refused() { let Some(device) = device() else { diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 961d498ee..21edc541c 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -371,13 +371,16 @@ driver's. Each is open work. 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 command buffer whose functions read addresses and may store (which may write every copy; + a draw whose vertex and fragment functions store nothing writes none) 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`, a copy that drops + the GPU's writes included), 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, an admitted import fails, or the GPU's writes to + the pages must be dropped (pages the process cannot write, and memory of Metal's private + option bit 24 where the system maps no read-only view), never for other memory by default. - **Two memories over overlapping host bytes agree GPU to GPU only through the pages when one is a copied host buffer** (`copied.rs`, `copied-host-pages`): a copy and another copy or an import of pages that overlap without being the same first byte and length (a rebind's bytes inside a diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 9248c4cb4..6f1cc01e7 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -410,9 +410,10 @@ completion, after that write-back: no read of the event's value shows it earlier on another queue (a plain `Event`'s too) is held until then rather than chained on the GPU (`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 +wrote, and every copy where a function that may store 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`, a copy that drops the GPU's writes +included), 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