diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index d78f41eca..8f183fc5f 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -4420,8 +4420,9 @@ impl Buffer { /// says which batch takes it ([`Replaces`]): where no command buffer can have read the /// bytes, one that takes a new buffer's first fill (`register_bytes`). The copy stages /// nothing (`texture/first_move.rs`'s `Keeps::HostCopy`), so it makes no submission, however - /// many bytes wait; pages no import maps are staged, and past the bound of what is staged a - /// submission waited for makes them now (`managed_copy.rs`). Nothing for a buffer without a + /// many bytes wait; pages no import maps are staged (but those a guest RAM's chunk imports + /// hold, which the GPU copies from them), and past the bound of what is staged a submission + /// waited for makes them now (`managed_copy.rs`). Nothing for a buffer without a /// host copy, nor for an empty range. pub(super) fn upload(&self, range: Range, replaces: Replaces) -> Result<(), Error> { let s = self.s(); @@ -4454,7 +4455,7 @@ impl Buffer { /// commands, as the device's policy says (`DevicePolicy::managed_copy_in`): under /// `ManagedCopyInPolicy::AtSubmission` (the default) the GPU copies them from the host copy as /// that submission runs ([`upload`](Self::upload)), with no copy on the CPU but of pages no - /// import maps (`managed_copy.rs`); under `AtCommit` the CPU copies them now, as the host copy + /// import maps and no guest RAM's chunk imports hold (`managed_copy.rs`); under `AtCommit` the CPU copies them now, as the host copy /// holds them, into staging memory that submission copies from (`managed_copy::stage_in`), /// and where that memory is not found the GPU copies them from the host copy as under the /// default. Nothing for a buffer without a host copy, nor for an empty range, nor for pages @@ -4474,9 +4475,10 @@ impl Buffer { None => Ok(()), } } - // Copies from the host copy, which stage nothing and go with this commit's batch; pages - // no import maps staged, a failed submission past the bound failing the device, which - // the commit's own submission reports. + // Copies from the host copy (or a guest RAM's chunk imports that hold it), which stage + // nothing and go with this commit's batch; pages no import maps staged, a failed + // submission past the bound failing the device, which the commit's own submission + // reports. _ => { let _ = self.upload(range, replaces); return; diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index a92b3d704..fc89b2353 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -2357,6 +2357,18 @@ impl Device { // 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); + let alone = match &why { + CopiedFor::Refused | CopiedFor::DeviceRefused | CopiedFor::Failed(_) => { + crate::managed_copy::AloneBecause::Refused + } + CopiedFor::OverImport | CopiedFor::OverRamChunk => { + crate::managed_copy::AloneBecause::OverImports + } + CopiedFor::ReadOnly | CopiedFor::Unwritable => { + crate::managed_copy::AloneBecause::Unwritable + } + }; + self.shared().counts.managed_pages_alone(alone); return Err(crate::managed_copy::uncopied(drops)); } let (cause, failed): (_, Option) = match why { diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 2c4100fa4..6f680cbd5 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -478,8 +478,12 @@ impl HostMemory { /// runtime's other paths, as over memory no RAM holds, and the chunk is imported only for /// the copies over it ([`Device::use_host_ram`](crate::Device::use_host_ram)). Pages of more /// than one run, or of a run crossing a chunk's end, take the runtime's other paths (the gate, - /// then an import or a copy), the runs kept with the object. Counted: - /// `WorkCounts::chunk_bound_buffers_made`. No Metal counterpart. + /// then an import or a copy), the runs kept with the object. A `Managed` no-copy buffer over + /// such pages on a device without unified memory, whose host copy is its pages alone (an import + /// of their own would map pages a chunk's import holds), copies them in by the GPU from the + /// chunks' imports where those hold them all, the CPU staging nothing. Counted: + /// `WorkCounts::chunk_bound_buffers_made`, `WorkCounts::managed_pages_in_ram_chunks`. No Metal + /// counterpart. pub fn with_runs(self, resolver: RunResolver) -> HostMemory { HostMemory { runs: Some(resolver), diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs index e7bf489a7..736581731 100644 --- a/crates/metal2vulkan-runtime/src/host_ram.rs +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -1064,6 +1064,53 @@ impl RamOnDevice { self.chunk(device, importer, slot, By::Object).ok() } + /// The pieces of the RAM's chunks' imports that hold a two-copy buffer's pages, which no + /// import of their own maps (`managed_copy.rs`'s `CallerPages`): `runs`, the resolver's answer + /// for the buffer's import window (`Device::route_runs`, which took them), laid one after + /// another from the window's first byte and cut where a chunk ends, of the window's bytes + /// `bytes` (the buffer's, from its byte 0, to its reach). Each piece is a range of the + /// buffer's bytes and where they lie in its chunk's import, which the piece holds: taken as an + /// object over the chunk takes it ([`RamOnDevice::for_object`]). `None` where a chunk takes + /// none (one not imported on a listed plan, held back, refused, or failed) or the runs do not + /// cover `bytes`: the copies in then go through the CPU. + pub(crate) fn pieces_of( + &self, + device: &Device, + importer: &Importer, + runs: &[Range], + bytes: Range, + ) -> Option> { + let laid = copy::one_after_another(0, runs)?; + let (pieces, _) = copy::pieces(&laid, &self.spans())?; + let mut taken: BTreeMap> = BTreeMap::new(); + let mut out = Vec::with_capacity(pieces.len()); + let mut covered = bytes.start; + for piece in pieces { + let start = piece.at.max(bytes.start); + let end = (piece.at + piece.length).min(bytes.end); + if start >= end { + continue; + } + let chunk = match taken.get(&piece.slot) { + Some(chunk) => Arc::clone(chunk), + None => { + let chunk = self.for_object(device, importer, piece.slot)?; + taken.insert(piece.slot, Arc::clone(&chunk)); + chunk + } + }; + let host = self.slots[piece.slot].span.start + piece.offset + (start - piece.at); + let at = chunk.offset_of(&(host..host + (end - start)))?; + covered = covered.max(end); + out.push(ChunkPiece { + bytes: start - bytes.start..end - bytes.start, + source: (chunk.raw, at), + _chunk: chunk, + }); + } + (covered == bytes.end).then(|| out.into_boxed_slice()) + } + /// Whether a copy's ranges over a chunk not imported yet may be imported alone while the /// chunk's import is made ([`RamOnDevice::run_alone`]): only on a device /// whose plan is [`Plan::listed`], whose chunks and runs are each a dma-buf of the RAM's @@ -2103,6 +2150,17 @@ impl Drop for RamAfterFree { } } +/// A piece of a RAM's chunk import that holds some of a two-copy buffer's pages +/// ([`RamOnDevice::pieces_of`]), which the buffer's copies in read on the GPU. +pub(crate) struct ChunkPiece { + /// The buffer's bytes it holds, from the buffer's byte 0. + pub(crate) bytes: Range, + /// Where they lie: the import's `VkBuffer`, and the byte of it they start at. + pub(crate) source: (vk::Buffer, u64), + /// The import, held while the piece lives. + _chunk: Arc, +} + /// Where a resolver's answer puts a no-copy object's pages (`HostMemory::with_runs`). pub(crate) enum Routed { /// One run inside chunk `slot` of `ram`, from host address `start`: the object is bound in @@ -2123,6 +2181,13 @@ pub(crate) enum Routed { } impl Routed { + /// The RAM the pages lie in. + pub(crate) fn ram(&self) -> &Arc { + match self { + Routed::InChunk { ram, .. } | Routed::Runs { ram, .. } => ram, + } + } + /// The RAM and the runs, kept with the object until its rebind or release. pub(crate) fn kept(&self) -> (Arc, Box<[Range]>) { match self { diff --git a/crates/metal2vulkan-runtime/src/managed.rs b/crates/metal2vulkan-runtime/src/managed.rs index 4b9ed91a2..dc3de1e7e 100644 --- a/crates/metal2vulkan-runtime/src/managed.rs +++ b/crates/metal2vulkan-runtime/src/managed.rs @@ -36,8 +36,8 @@ //! - **The bytes a command buffer reads** follow the device's policy //! (`DevicePolicy::managed_copy_in`). Under the default, `ManagedCopyInPolicy::AtSubmission`, //! the GPU copies the range from the host copy as that submission runs, with no copy on the CPU -//! (but of pages no import maps, which the CPU copies at the commit into staging memory, -//! `managed_copy.rs`): a command buffer reads the bytes the host copy held at its commit, and a +//! (but of pages no import of their own maps and no guest RAM's chunk imports hold, which the +//! CPU copies at the commit into staging memory, `managed_copy.rs`): a command buffer reads the bytes the host copy held at its commit, and a //! CPU write after the commit, before the GPU ran the command buffer, may reach it. Macs differ //! there, so the cheaper answer is the default: on an AMD Radeon Pro 5300M (macOS 26.7.1, two //! copies), a kernel copying a 4 KiB `Managed` buffer behind a spin kernel read the CPU's write diff --git a/crates/metal2vulkan-runtime/src/managed_copy.rs b/crates/metal2vulkan-runtime/src/managed_copy.rs index 921f3d45d..cbbcd07a1 100644 --- a/crates/metal2vulkan-runtime/src/managed_copy.rs +++ b/crates/metal2vulkan-runtime/src/managed_copy.rs @@ -19,9 +19,13 @@ //! dma-bufs, or in a guest RAM's chunk: `host_memory.rs`, `host_ram.rs`), which is a buffer of //! the runtime's own over them, outside the Metal address space ([`Side::Import`]), or, where //! the device imports none of them (the caller's gate refused it, the device refused the -//! pointer, the import failed), the pages alone ([`Side::Pages`]): never a copy of them as well -//! (`copied.rs`), which would be a third. `contents` is the caller's pointer, and the -//! deallocator and keep-alive go as a no-copy buffer's do. +//! pointer, the import failed, a live import holds some of them), the pages alone +//! ([`Side::Pages`]): never a copy of them as well (`copied.rs`), which would be a third. Pages +//! alone that a guest RAM's chunk imports hold all of (`host_ram.rs`: pages across a chunk's +//! end, or of several runs, whose own import would map pages a chunk's maps, or which the +//! device refused) keep the pieces of those imports ([`CallerPages::chunks`]), which hold the +//! chunks imported while the pages are the buffer's. `contents` is the caller's pointer, and +//! the deallocator and keep-alive go as a no-copy buffer's do. //! - **Copies in.** The buffer's bytes and the rest of their last page ([`CallerCopy::reach`]) //! are copied in as it is made, as a new buffer's first fill is made (`texture/first_move.rs`'s //! `register_bytes`; on a device without a fill queue, by the device's next submission, whatever @@ -46,17 +50,22 @@ //! `VkQueue`. Not on the staging queue, //! which waits for no work in flight. From an import, the copy's source is //! the import's `VkBuffer`, held (imported again where the device released it) until the -//! submission completed: no copy on the CPU and no staging. From pages no import maps (and under -//! `AtCommit` from an import too), the call copies the bytes on the CPU into staging buffers of +//! submission completed: no copy on the CPU and no staging. From pages alone that a guest RAM's +//! chunk imports hold, the copy's sources are those imports' `VkBuffer`s, a copy of each piece +//! of the range, the pages held until the submission completed: no copy on the CPU and no +//! staging either (`WorkCounts::managed_bytes_copied_in_from_ram`). From pages no import maps +//! (and under `AtCommit` from an import or a RAM's chunks too), the call copies the bytes on the +//! CPU into staging buffers of //! [`STAGED_CHUNK`] bytes at most, of host-cached system memory, which the GPU's copy reads //! across the bus, never the device-local memory a write-combined buffer prefers there, which //! the CPU would write across the bus ([`Staging::new`]); each is written once, freed once the //! submission completed, and of a power-of-two length, so a later copy's of a like size takes -//! one the device parked (`recycle.rs`) rather than new memory. Past the bound of what is staged +//! one the device parked (`recycle.rs`) rather than new memory +//! (`WorkCounts::managed_bytes_staged_in`). Past the bound of what is staged //! (`texture/first_move.rs`'s `STAGED_BYTES`), the call makes a submission for them and -//! waits. A copy from an import stages nothing and counts toward no bound, so a commit's copies -//! in of the ranges named go with its own batch however many bytes they are, and the commit -//! waits for none of them. +//! waits. A copy from an import, or from a RAM's chunks, stages nothing and counts toward no +//! bound, so a commit's copies in of the ranges named go with its own batch however many bytes +//! they are, and the commit waits for none of them. //! - **Copies out.** `synchronize_resource` copies the buffer's bytes to the import in the blit //! encoder's command stream, a blit's write of the import (`blit.rs`); to pages no import maps, //! into a staging buffer there, which the command buffer's completion copies to the pages before @@ -85,7 +94,8 @@ use super::buffer::{Buffer, HostCopy, Naming, Replaces}; use super::device::lock; use super::error::{internal, Error}; use super::exit_guard; -use super::host_memory::{HostMemory, HostParts, Release}; +use super::host_memory::{HostMemory, HostParts, ImportWindow, Release, RunResolver}; +use super::host_ram::ChunkPiece; use super::texture::first_move::Keeps; use super::values::{CpuCacheMode, HazardTrackingMode, ResourceOptions, StorageMode}; use super::Device; @@ -120,17 +130,21 @@ pub(super) enum Side { /// An import of them, which a buffer of the runtime's own over them holds, outside the Metal /// address space (made as [`Naming::HostCopy`]): its rebind and detach are the host copy's. Import(Buffer), - /// The pages alone, which no import maps, and whether they are detached. + /// The pages alone, which no import of their own maps, and whether they are detached. Pages(Arc, bool), } -/// The caller's pages of a `Managed` no-copy buffer that no import maps ([`Side::Pages`]), given -/// back to the caller's deallocator and keep-alive as they go: once the buffer let go of them and -/// every copy into them or out of them completed. +/// The caller's pages of a `Managed` no-copy buffer that no import of their own maps +/// ([`Side::Pages`]), given back to the caller's deallocator and keep-alive as they go: once the +/// buffer let go of them and every copy into them or out of them completed. pub(super) struct CallerPages { pointer: NonNull, /// The bytes from the pointer the copies cover ([`CallerCopy::reach`] at most). reach: u64, + /// Where a guest RAM's chunk imports hold them all (`host_ram.rs`), the pieces of those + /// imports, which the copies in read on the GPU; `None` where no import holds them, whose + /// copies in the CPU stages. + chunks: Option>, /// The process cannot write them, or Metal's private option bit 24 drops the GPU's writes: /// nothing is copied out to them. drops_writes: bool, @@ -452,7 +466,10 @@ impl CallerCopy { } Side::Pages(pages, false) => { let range = range.start..range.end.min(pages.reach); - stage_in(buffer, pages.pointer, range, bounded, replaces) + match &pages.chunks { + Some(pieces) => copy_in_from_chunks(buffer, &pages, pieces, range, replaces), + None => stage_in(buffer, pages.pointer, range, bounded, replaces), + } } Side::Pages(_, true) => Ok(()), } @@ -560,6 +577,7 @@ pub(super) fn stage_in( bytes as usize, ); } + device.shared().counts.managed_staged_in(bytes); let source = staging.buffer.at(0); let held = Keeps::Staging(Box::new(staging)); buffer.copy_in_from(source, start..start + bytes, held, (bounded, replaces))?; @@ -568,6 +586,80 @@ pub(super) fn stage_in( Ok(()) } +/// Copy `range` of the caller's `pages` into `buffer`'s device copy by the GPU, from the guest +/// RAM's chunk imports `pieces` that hold them ([`CallerPages::chunks`]): a copy of each piece's +/// part of the range, read as the submission that makes it runs, which holds the pages (and so +/// the imports) until it completed, for the batch `replaces` says ([`Replaces`]). No CPU copy and +/// no staging, so no bound of what is staged and no submission made for them. +fn copy_in_from_chunks( + buffer: &Buffer, + pages: &Arc, + pieces: &[ChunkPiece], + range: Range, + replaces: Replaces, +) -> Result<(), Error> { + let counts = &buffer.generation().shared().counts; + for piece in pieces { + let start = range.start.max(piece.bytes.start); + let end = range.end.min(piece.bytes.end); + if start >= end { + continue; + } + let (source, at) = piece.source; + let source = (source, at + (start - piece.bytes.start)); + let held = Keeps::HostCopy(Box::new(Arc::clone(pages))); + buffer.copy_in_from(source, start..end, held, (false, replaces))?; + counts.managed_copied_in_from_ram(end - start); + } + Ok(()) +} + +/// The caller's resolver of a two-copy buffer's pages' runs (`HostMemory::with_runs`) as its host +/// copy is made ([`Device::caller_side`]): asked at most once, as [`RunResolver`]'s contract +/// says, its answer kept with the window it was asked for, for the pages alone +/// ([`Device::chunks_of`]). +#[derive(Clone, Default)] +struct Asked(Arc>>); + +/// A resolver's answer and the window it was asked for: its first byte and length. +type Kept = ((u64, u64), Option>>); + +impl Asked { + /// `resolver`, asked at most once: its answer kept, and given again for the same window, a + /// later ask of another answered `None`. Asked with no lock held. + fn keeping(&self, resolver: RunResolver) -> RunResolver { + let asked = self.clone(); + Arc::new(move |start, length| { + if let Some((window, answer)) = &*lock(&asked.0) { + return answer.clone().filter(|_| *window == (start, length)); + } + let answer = resolver(start, length); + *lock(&asked.0) = Some(((start, length), answer.clone())); + answer + }) + } + + /// The window the resolver was asked for and the runs it answered, where it answered some. + fn answer(&self) -> Option<((u64, u64), Vec>)> { + let (window, answer) = lock(&self.0).clone()?; + Some((window, answer?)) + } +} + +/// Why a two-copy buffer's host copy is its pages alone, no import of their own mapping them +/// (`WorkCounts::managed_pages_alone_*`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum AloneBecause { + /// The caller's gate refused their import, the device refused their pointer and no dma-buf of + /// them served, or the import failed. + Refused, + /// A live import of another object's pages, or of a guest RAM's chunk, holds some of them. + OverImports, + /// The process cannot write them, or Metal's private option bit 24 drops the GPU's writes and + /// the system maps no read-only view of them. + Unwritable, +} + /// The refusal a buffer made as [`Naming::HostCopy`] answers where it would be a copy of the /// caller's pages (`copied.rs`): the host copy is their pages alone instead ([`Side::Pages`]), /// whose GPU writes are dropped where `drops_writes` (read-only pages, or bit-24 memory). @@ -597,7 +689,9 @@ impl Device { /// The host copy of a two-copy buffer of `made`'s call, length and options over the caller's /// memory's `parts`, given back to `release`: an import of them, made as a no-copy buffer's /// (but never a copy of them), outside the Metal address space, or, where the device imports - /// none, the pages alone. Refused as a no-copy buffer is, where the pages are. + /// none, the pages alone, with the pieces of a guest RAM's chunk imports that hold them all + /// where there are such ([`Device::chunks_of`]). Refused as a no-copy buffer is, where the + /// pages are. /// /// # Safety /// @@ -611,6 +705,13 @@ impl Device { let pointer = parts.pointer; let vouched = parts.writable; let made_of = parts.clone(); + // The caller's resolver of the pages' runs, asked once (`RunResolver`): its answer kept + // for the pages alone. + let asked = Asked::default(); + let parts = HostParts { + runs: parts.runs.map(|runs| asked.keeping(runs)), + ..parts + }; let outside = super::address::AddressPlacement::Outside.into(); let made = (call, length, options, outside); // SAFETY: the caller's contract. @@ -628,9 +729,14 @@ impl Device { // writes to pages the process cannot write are dropped, never copied out to them. let drops_writes = error == uncopied(true) || (!vouched && self.unwritable(at..at + reach, page)?); + let chunks = self.chunks_of(call, (pointer, reach), &asked); + if chunks.is_some() { + self.shared().counts.managed_pages_in_ram_chunks(); + } let pages = CallerPages { pointer, reach, + chunks, drops_writes, made_of, release: OnceLock::new(), @@ -645,6 +751,33 @@ impl Device { Ok(side) } + /// The pieces of a guest RAM's chunk imports that hold all of a two-copy buffer's pages from + /// `pointer` to its `reach`, which no import of their own maps ([`CallerPages::chunks`]): of + /// the runs the caller's resolver answered for their import window (`asked`), where the + /// device uses the RAM they lie in (`Device::route_runs`) and each chunk they touch takes an + /// import as an object over it does (`host_ram.rs`'s `RamOnDevice::pieces_of`). `None` + /// elsewhere: the resolver was not asked or answered no runs, or a chunk takes no import. + fn chunks_of( + &self, + call: &'static str, + (pointer, reach): (NonNull, u64), + asked: &Asked, + ) -> Option> { + let ((start, size), runs) = asked.answer()?; + let importer = self.shared().host_import.as_ref().ok()?; + let offset = (pointer.as_ptr() as u64).checked_sub(start)?; + let window = ImportWindow { + start, + size, + offset, + }; + let kept = runs.clone(); + let resolver: RunResolver = Arc::new(move |_, _| Some(kept.clone())); + let routed = self.route_runs(call, importer, &resolver, &window).ok()??; + let bytes = offset..offset.checked_add(reach)?; + routed.ram().pieces_of(self, importer, &runs, bytes) + } + /// Whether the process cannot write the pages of `range` (whole pages of `page` bytes), as /// the import of no-copy memory asks it (`host_memory.rs`'s `refuse_unwritable`); refused /// where the system cannot say, as that import is. diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_managed.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_managed.rs index d86d2dffd..8a2ee3809 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_managed.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_managed.rs @@ -2,6 +2,14 @@ //! (`managed_copy.rs`): two copies, the caller's pages and the GPU's own, the buffer's pages //! across the end of a chunk whose import, and the next chunk's, live. //! +//! - **Copies in from the chunks.** The buffer's host copy is its pages alone +//! (`WorkCounts::managed_pages_alone_over_imports`): an import of their own would map pages the +//! chunks' imports hold, so nothing is imported and the gate is not asked. The chunks' imports +//! hold them all (`managed_pages_in_ram_chunks`). Its copy in as it is made is the GPU's, from +//! those imports, the CPU staging nothing (`managed_bytes_copied_in_from_ram`, +//! `managed_bytes_staged_in`), and so is the copy in of a range `did_modify_range` names across +//! the chunks' end; under `ManagedCopyInPolicy::AtCommit` the CPU stages that range at the +//! commit instead. The GPU reads the CPU's bytes under both. //! - **The bench across a chunk's end** (ignored, `MANAGED-RAM-COPY-IN`; run in release): what a //! `did_modify_range` of 256 KiB, 4 MiB and 32 MiB across the end of the RAM's first chunk, //! written by the CPU before each commit of a command buffer that reads the range's first and @@ -12,12 +20,15 @@ //! of device the cfg selects. A device that imports no host memory, or has unified memory (where //! a `Managed` buffer is one copy), says so and passes. -use super::host_ram_device::{gate, held_device, itself, new_ram, resolver, settles, MIB, WAIT}; -use crate::{ - Buffer, CpuCacheMode, Device, HazardTrackingMode, HostBacking, HostMemory, ResourceOptions, - StorageMode, +use super::host_ram_device::{ + bytes, fill_pattern, gate, gpu_bytes, held_device, itself, new_ram, resolver, settles, MIB, + WAIT, }; -use metal2vulkan::device::DevicePolicy; +use crate::{ + Buffer, CpuCacheMode, Device, HazardTrackingMode, HostBacking, HostMemory, ImportRequest, + ResourceOptions, StorageMode, +}; +use metal2vulkan::device::{DevicePolicy, ManagedCopyInPolicy}; use std::ptr::NonNull; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -61,11 +72,16 @@ fn two_copy_device(policy: DevicePolicy) -> Option { /// The memory at host address `at` of the test's RAM, its pages their own run of it, under a gate /// that admits every import. fn memory_at(at: u64) -> HostMemory { - let (runs, gates): (Arc>, Arc>) = Default::default(); + memory_gated(at, &Arc::default()) +} + +/// [`memory_at`], the gate's requests into `gates`. +fn memory_gated(at: u64, gates: &Arc>>) -> HostMemory { + let runs: Arc> = Arc::default(); // SAFETY: the RAM's bytes, mapped until its keep-alive goes, after every device let go. unsafe { HostMemory::new(NonNull::new(at as *mut u8).unwrap()) } .with_runs(resolver(&runs, itself)) - .with_import_gate(gate(&gates, true)) + .with_import_gate(gate(gates, true)) } /// `Shared` buffers of four pages, one in each of the RAM's two whole chunks from `start`, far @@ -87,6 +103,96 @@ fn import_both_chunks(device: &Device, start: u64) -> (Buffer, Buffer) { (in_chunk(start + 16 * page), in_chunk(start + 96 * MIB)) } +/// Copies in from the chunks (the module docs), under `copy_in`. +fn copies_in_across_a_chunk_end(copy_in: ManagedCopyInPolicy) { + const LENGTH: u64 = 4 * MIB; + let mut policy = DevicePolicy::default(); + policy.managed_copy_in = copy_in; + let Some(device) = two_copy_device(policy) else { + return; + }; + let page = device.shared().host_import.as_ref().unwrap().page; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let chunks = import_both_chunks(&device, start); + let at = start + CHUNK_END - LENGTH / 2; + fill_pattern(at..at + LENGTH); + let gates = Arc::default(); + let before = device.work_counts(); + // SAFETY: as in `memory_at`. + let buffer = unsafe { + device.new_buffer_with_bytes_no_copy(memory_gated(at, &gates), LENGTH, managed(), None) + } + .unwrap(); + assert_eq!(buffer.host_backing(), Some(HostBacking::DeviceCopy)); + assert_eq!( + buffer.contents().map(|pointer| pointer.as_ptr() as u64), + Some(at) + ); + let made = device.work_counts(); + assert_eq!( + ( + made.managed_pages_alone_over_imports - before.managed_pages_alone_over_imports, + made.managed_pages_in_ram_chunks - before.managed_pages_in_ram_chunks, + made.host_pointer_imports_made - before.host_pointer_imports_made, + made.chunk_bound_buffers_made - before.chunk_bound_buffers_made, + ), + (1, 1, 0, 0), + "its pages alone, which the chunks' imports hold; nothing imported" + ); + assert!(gates.lock().unwrap().is_empty(), "the gate was not asked"); + assert_eq!( + gpu_bytes(&device, &buffer, LENGTH), + bytes(at..at + LENGTH), + "the bytes copied in as the buffer was made" + ); + let first = device.work_counts(); + assert_eq!( + ( + first.managed_bytes_copied_in_from_ram - before.managed_bytes_copied_in_from_ram, + first.managed_bytes_staged_in - before.managed_bytes_staged_in, + ), + (LENGTH, 0), + "copied in from the chunks' imports as it was made, nothing staged" + ); + // The CPU's write across the chunks' end, named. + let named = LENGTH / 2 - 2 * page..LENGTH / 2 + 2 * page; + let length = named.end - named.start; + // SAFETY: the RAM's bytes, which no command buffer reads now. + unsafe { std::ptr::write_bytes((at + named.start) as *mut u8, 0xa5, length as usize) }; + buffer.did_modify_range(named).unwrap(); + assert_eq!( + gpu_bytes(&device, &buffer, LENGTH), + bytes(at..at + LENGTH), + "the CPU's write across the chunks' end" + ); + let after = device.work_counts(); + let expected = match copy_in == ManagedCopyInPolicy::AtCommit { + true => (0, length), + false => (length, 0), + }; + assert_eq!( + ( + after.managed_bytes_copied_in_from_ram - first.managed_bytes_copied_in_from_ram, + after.managed_bytes_staged_in - first.managed_bytes_staged_in, + ), + expected, + "the named range copied in from the chunks' imports, or staged at the commit ({copy_in:?})" + ); + drop((buffer, chunks, used, ram, device)); + assert!(settles(&dropped), "the RAM's keep-alive did not go"); +} + +#[test] +fn a_managed_buffer_across_a_chunk_end_copies_in_from_the_chunks_imports() { + copies_in_across_a_chunk_end(ManagedCopyInPolicy::AtSubmission); +} + +#[test] +fn a_managed_buffer_across_a_chunk_end_is_staged_at_the_commit_under_at_commit() { + copies_in_across_a_chunk_end(ManagedCopyInPolicy::AtCommit); +} + /// The median of `values`, in milliseconds. fn median_ms(mut values: Vec) -> f64 { values.sort(); diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index b65143443..c80a72511 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -510,6 +510,12 @@ pub(crate) struct Counters { managed_bytes_synchronized: AtomicU64, managed_staging_bytes: AtomicU64, managed_writes_undone: AtomicU64, + managed_bytes_staged_in: AtomicU64, + managed_bytes_copied_in_from_ram: AtomicU64, + managed_pages_alone_refused: AtomicU64, + managed_pages_alone_over_imports: AtomicU64, + managed_pages_alone_unwritable: AtomicU64, + managed_pages_in_ram_chunks: AtomicU64, dma_buf_textures_in_place: AtomicU64, fresh_page_textures_in_place: AtomicU64, copied_textures_in_place: AtomicU64, @@ -4212,6 +4218,36 @@ impl Counters { self.managed_writes_undone.fetch_add(1, Ordering::Relaxed); } + /// The CPU copied `bytes` bytes of a two-copy buffer's host copy into a staging buffer for a + /// copy in (`managed_copy.rs`'s `stage_in`). + pub(crate) fn managed_staged_in(&self, bytes: u64) { + (self.managed_bytes_staged_in).fetch_add(bytes, Ordering::Relaxed); + } + + /// The GPU's copy of `bytes` bytes of a two-copy buffer's pages into its device copy, from a + /// guest RAM's chunk imports, was registered (`managed_copy.rs`). + pub(crate) fn managed_copied_in_from_ram(&self, bytes: u64) { + (self.managed_bytes_copied_in_from_ram).fetch_add(bytes, Ordering::Relaxed); + } + + /// A two-copy buffer's host copy was made its pages alone, no import of their own mapping + /// them, for `why` (`managed_copy.rs`). + pub(crate) fn managed_pages_alone(&self, why: crate::managed_copy::AloneBecause) { + use crate::managed_copy::AloneBecause; + let count = match why { + AloneBecause::Refused => &self.managed_pages_alone_refused, + AloneBecause::OverImports => &self.managed_pages_alone_over_imports, + AloneBecause::Unwritable => &self.managed_pages_alone_unwritable, + }; + count.fetch_add(1, Ordering::Relaxed); + } + + /// Such pages alone took the pieces of a guest RAM's chunk imports that hold them all, which + /// their copies in read (`managed_copy.rs`). + pub(crate) fn managed_pages_in_ram_chunks(&self) { + (self.managed_pages_in_ram_chunks).fetch_add(1, Ordering::Relaxed); + } + /// A texture over host pages of `class` was made an image in place over them (`in_place.rs`), /// its rows at Metal's pitch in a `DRM_FORMAT_MOD_LINEAR` image where `pitched`; over a /// copied host buffer's copy of them where `copied` (`copied.rs`), whose class is the copy's @@ -8486,6 +8522,33 @@ pub struct WorkCounts { /// Command buffers that used such a buffer whose pages drop the GPU's writes (a read-only /// rebind) and completed, its pages then copied in whole again. pub managed_writes_undone: u64, + /// The bytes the CPU copied from `Managed` buffers' host copies into staging buffers for + /// their copies in, on a device without unified memory: such a buffer's pages no import maps + /// (but those a guest RAM's chunk imports hold, `managed_bytes_copied_in_from_ram`), and + /// under `ManagedCopyInPolicy::AtCommit` every range a commit takes, of the runtime's own + /// `Managed` buffers too. Every other copy in is the GPU's, from the host copy itself. + pub managed_bytes_staged_in: u64, + /// The bytes the GPU copied into such buffers' device copies from a guest RAM's chunk imports + /// that hold their pages, which no import of their own maps (`HostRam`): no CPU copy and no + /// staging. Of `managed_bytes_copied_in`. + pub managed_bytes_copied_in_from_ram: u64, + /// Host copies of such buffers made (with the buffer, at a rebind, at a recovery) that are + /// their pages alone, no import of their own mapping them, because the caller's gate refused + /// their import, the device refused their pointer and no dma-buf of them served, or the import + /// failed. + pub managed_pages_alone_refused: u64, + /// Such host copies made their pages alone because a live import of another object's pages, + /// or of a guest RAM's chunk, holds some of them (their bytes across an import's edge, or a + /// chunk's end): no page is imported twice. + pub managed_pages_alone_over_imports: u64, + /// Such host copies made their pages alone because the process cannot write them, or Metal's + /// private option bit 24 drops the GPU's writes and the system maps no read-only view. + pub managed_pages_alone_unwritable: u64, + /// Of the host copies counted by `managed_pages_alone_*`, those whose pages a guest RAM's chunk + /// imports hold all of: their copies in are the GPU's, from those imports + /// (`managed_bytes_copied_in_from_ram`), never staged by the CPU, but under + /// `ManagedCopyInPolicy::AtCommit`. + pub managed_pages_in_ram_chunks: u64, /// Of `host_textures_in_place`, those over pages imported as dma-bufs: each a /// `DRM_FORMAT_MOD_LINEAR` image over a dma-buf of its own pages (also counted in /// `dma_buf_images`). @@ -10556,6 +10619,17 @@ impl Device { managed_bytes_synchronized: counters.managed_bytes_synchronized.load(Ordering::Relaxed), managed_staging_bytes: counters.managed_staging_bytes.load(Ordering::Relaxed), managed_writes_undone: counters.managed_writes_undone.load(Ordering::Relaxed), + managed_bytes_staged_in: counters.managed_bytes_staged_in.load(Ordering::Relaxed), + managed_bytes_copied_in_from_ram: (counters.managed_bytes_copied_in_from_ram) + .load(Ordering::Relaxed), + managed_pages_alone_refused: (counters.managed_pages_alone_refused) + .load(Ordering::Relaxed), + managed_pages_alone_over_imports: (counters.managed_pages_alone_over_imports) + .load(Ordering::Relaxed), + managed_pages_alone_unwritable: (counters.managed_pages_alone_unwritable) + .load(Ordering::Relaxed), + managed_pages_in_ram_chunks: (counters.managed_pages_in_ram_chunks) + .load(Ordering::Relaxed), dma_buf_textures_in_place: counters.dma_buf_textures_in_place.load(Ordering::Relaxed), fresh_page_textures_in_place: counters .fresh_page_textures_in_place diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 50badc62d..6bb1d7cf0 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3143,13 +3143,19 @@ field metal2vulkan-runtime::WorkCounts.lost_programs_released pub lost_programs_ field metal2vulkan-runtime::WorkCounts.lost_textures_released pub lost_textures_released: u64 field metal2vulkan-runtime::WorkCounts.makings_held_for_compile_memory pub makings_held_for_compile_memory: u64 field metal2vulkan-runtime::WorkCounts.managed_bytes_copied_in pub managed_bytes_copied_in: u64 +field metal2vulkan-runtime::WorkCounts.managed_bytes_copied_in_from_ram pub managed_bytes_copied_in_from_ram: u64 field metal2vulkan-runtime::WorkCounts.managed_bytes_copied_out pub managed_bytes_copied_out: u64 field metal2vulkan-runtime::WorkCounts.managed_bytes_modified pub managed_bytes_modified: u64 +field metal2vulkan-runtime::WorkCounts.managed_bytes_staged_in pub managed_bytes_staged_in: u64 field metal2vulkan-runtime::WorkCounts.managed_bytes_synchronized pub managed_bytes_synchronized: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copies pub managed_device_copies: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copies_in_place pub managed_device_copies_in_place: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copies_made pub managed_device_copies_made: u64 field metal2vulkan-runtime::WorkCounts.managed_device_copy_bytes pub managed_device_copy_bytes: u64 +field metal2vulkan-runtime::WorkCounts.managed_pages_alone_over_imports pub managed_pages_alone_over_imports: u64 +field metal2vulkan-runtime::WorkCounts.managed_pages_alone_refused pub managed_pages_alone_refused: u64 +field metal2vulkan-runtime::WorkCounts.managed_pages_alone_unwritable pub managed_pages_alone_unwritable: u64 +field metal2vulkan-runtime::WorkCounts.managed_pages_in_ram_chunks pub managed_pages_in_ram_chunks: u64 field metal2vulkan-runtime::WorkCounts.managed_ranges_modified pub managed_ranges_modified: u64 field metal2vulkan-runtime::WorkCounts.managed_resources_synchronized pub managed_resources_synchronized: u64 field metal2vulkan-runtime::WorkCounts.managed_staging_bytes pub managed_staging_bytes: u64 diff --git a/docs/API.md b/docs/API.md index cbd8e3a8b..7d9e8fd54 100644 --- a/docs/API.md +++ b/docs/API.md @@ -551,9 +551,12 @@ copies) read the bytes at the commit. `ManagedCopyInPolicy::AtCommit`, which `ex selects, takes the 5300M's answer: the commit copies each range on the CPU into staging buffers of host-cached system memory, a cost of the range's bytes, and a write after it reaches no command buffer committed before it, however late the GPU reaches it (docs/FAST-PATHS.md). Pages -no import maps are staged so at the commit under either. A CPU write that no `did_modify_range` names is not seen by the GPU. A blit encoder's `synchronize_resource` copies the GPU's copy out to the pages in its +no import of their own maps are staged so at the commit under either, but where a guest RAM's +chunk imports hold them all (`HostRam`): there the default copies them by the GPU from those +imports, as from an import of their own (`WorkCounts::managed_bytes_copied_in_from_ram`). A CPU write that no `did_modify_range` names is not seen by the GPU. A blit encoder's `synchronize_resource` copies the GPU's copy out to the pages in its command buffer's order, which the CPU sees once the command buffer completed. The copies run -from an import of the pages where the device makes one (never a copy of them), else through +from an import of the pages where the device makes one (never a copy of them), or from the +chunk imports of a guest RAM that hold them, else through staging buffers the runtime frees once their work completed, at most 256 MiB staged ahead (`WorkCounts::managed_*`). A texture over the buffer's bytes is over the GPU's copy and follows it, its `replace_region` copying in and its `synchronize_resource` or `synchronize_texture` diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 4ac634a61..37b8e0977 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -48,7 +48,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | A linear sample of a two-plane YCbCr texture whose planes a function reads in place (`YCBCR8_420_2P`, `YCBCR10_420_2P` through a uniform texel buffer over their codes, on an integrated GPU or a CPU device; `lower::sampler::in_place`), through a sampler that addresses no border on either plane axis, with no texel offset placed by a parent's size, is Vulkan's Y′CbCr model of the codes, as the device's own conversion with a linear chroma filter computes it: the four luma codes around the point and the four chroma pairs around the same point of the chroma plane (Metal's midpoint siting) blended bilinearly, then the surface's range and matrix (Metal's coefficients) in `float`, each channel clamped into `[0, 1]`: eight fetches. A runtime sampler's word decides as the function runs. A nearest sample, a border mode, a parent-placed offset and a gather are Metal's under either value. | `ycbcr_in_place_reads = YCbCrInPlacePolicy::Model` | `ycbcr_in_place_reads = YCbCrInPlacePolicy::Exact`: every tap Metal's texel (its chroma weighted 9/3/3/1 and rounded to a code, the fixed-point conversion), and the sample Metal's sum of the four taps' steps on the grid `2048`: twenty fetches and four conversions | The model reconstructs each channel at the point where Metal converts four taps and sums them: within the `float` arithmetic's rounding of the model (checked against an `f64` model on the CPU interpreter, `engine_ycbcr_in_place`), it differs from Metal's by the chroma the taps reconstruct, by Metal's roundings to a code and to `1/2048`, and where a tap's channel leaves `[0, 1]`, which Metal clamps before it sums. `HalfSampleFilter` / `FloatSampleFilter` under the bound converted 4:2:0 format, announced `ycbcr-filter-not-exact` | Radeon 780M (RADV): a 3840 x 2160 `YCBCR10_420_2P` frame sampled linearly into a 3840 x 2160 `BGRA8Unorm` target, GPU time per frame (median of 60): 6.4-6.9 ms under the exact form (`runtime_lane::video_frames`) | | A vertex buffer layout a draw fetches in fixed function, on a driver whose fixed-function vertex input takes an element's displacement modulo `2^32` (`RuntimeDriverDefect::VertexFetchWrapsPast4GiB`: lavapipe), where the draw's indices (`uint` indices, a per-vertex layout) or its indirect arguments (any layout but a constant one) state how far it fetches: the layout keeps the fixed-function fetch, so an element `2^32` bytes or more past the buffer's bind offset reads the bytes at its displacement's low 32 bits, where Metal reads zero past a buffer that ends before them (`render/vertex_reach.rs`). A layout whose reach the draw's own values bound (its last vertex without indices, `65535` plus its base vertex with `ushort` indices, its base instance plus its last instance over the step rate) is pulled where that reach passes `2^32`, under either value, and reads zero. Other drivers read zero (RADV on the 780M, MoltenVK 1.4.2: `runtime_lane::far_vertex_fetches`). | `vertex_reach = VertexReachPolicy::Bounded` | `vertex_reach = VertexReachPolicy::Exact`: such a layout is pulled too, wherever its stride and furthest attribute could reach past `2^32` from the largest index or argument (on lavapipe, every `uint`-indexed draw's per-vertex layout of a stride above 0, and every indirect draw's layout but a constant one), the plan's pulled-vertex-buffer variant (`WorkCounts::far_vertex_fetch_pulled_draws`) | Under `Bounded`, on lavapipe, an element of such a draw at or past `2^32` reads the wrapped bytes: the conformance case `vertex-fetch-past-4gib-small-buffer` replayed under the default policy differs in 8 elements (its two far `uint`-indexed draws at stride 4), and passes under `Exact`. `VertexFetchMayWrap` (`vertex-fetch-may-wrap`), once per device, for a draw left so; `runtime_lane::far_vertex_fetches` (both values) | Measured on lavapipe (Mesa 26.2.4, LLVM 23.1.1) on a Core Ultra 9 275HX shared with other jobs (`runtime_lane::far_vertex_fetches::far_reach_costs`): a state drawn without indices and then with `uint` indices makes one pipeline under `Bounded` and two under `Exact`, the pulled variant made at the first `uint`-indexed draw; a pass of one draw of 65,536 `uint`-indexed points, from the encoder's making to the wait's return, takes 2.3 to 2.8 times as long pulled (medians of 20 passes: 0.94 against 2.41 ms beside two builds, 3.5 to 4.8 against 9.7 to 12.0 ms at a load average of 59 on 24 threads). On every other driver neither value changes a draw | | A draw of triangles in a rasterization-rate-mapped pass that a host step records (an execution whose records the GPU writes or whose range a buffer holds), filled, of one amplification, without a compensation or a band, whose pipeline chooses no slice or viewport and writes no memory from its vertex function, over a map whose layers are alike and whose plan is a grid of at most 128 columns and rows, on a device that enables `geometryShader`, `shaderClipDistance` and `vertexPipelineStoresAndAtomics`, is drawn once and fanned out to the regions its triangles touch (`rate_mapped_pass.rs`, **Fan-out**): its variant's geometry stage emits a copy of each triangle for each region it touches, at most the copies the device's `maxGeometryTotalOutputComponents` allows up to 16, through one viewport over the render area, four clip distances keeping each copy to its region's pixels, where Metal shades each region through its own viewport. A probe recorded before the pass, submitted and waited for, flags a draw a triangle of which crosses `w = 0` or touches more regions than the copies, which is drawn region by region, and marks a draw a triangle of which touches more than four (`bind::fan_out::FEW_COPIES`): a draw it marks none of is drawn through the variant of four copies, whose geometry stage declares the output of fewer vertices, the three variants (the probe's, four copies and the most) begun at `commit`; it stops at a command's barrier and after a draw that writes memory. A copy's window coordinates are the region viewport's computed in the geometry stage, so a pixel centre within a rounding error of a triangle's edge may be covered by one route and not by the other | `rate_map_regions = RateMapRegionPolicy::FanOut` | `rate_map_regions = RateMapRegionPolicy::Exact`: every draw recorded once per region of the map's plan, each through its own viewport and scissor, its vertex function run once per region | No note of its own: the map's creation announces the pass as a near-equivalent (`rasterization-rate-map`). `WorkCounts::rate_map_probes`, `rate_map_flagged_draws` and `rate_map_fanned_draws` count the probes and the draws each route drew, `rate_map_fanned_few_draws` the fanned-out draws of four copies; `WorkCounts::rate_map_probe_gpu_nanos` the probes' GPU time | Measured at the host step, 64 executed commands of 918,108 indices over a 3648 by 1734 screen's 2074 regions (`runtime_lane::rate_mapped_pieces`), each frame cold (its pipelines begun at `commit`) then warm, the command buffer's GPU time under `FanOut` against `Exact`: an Iris Xe's (Mesa 26.2.6) 48 ms cold and 40 ms warm against 510 ms and 498 ms; a Radeon 780M's (Mesa 26.2.6) 40 ms and 30 ms against 299 ms and 233 ms (`Exact`'s from an earlier run); an RTX 3090's (NVIDIA 620.70.06) 29 ms and 6.1 ms against 64 ms and 58 ms, its cold frame's step waiting for the fan-out's pipelines. Every draw of the lane's is of four copies; on the Radeon 780M, in one run, two frames of them took 29.7 ms and 30.8 ms warm, where the same draws through the most copies took 36.8 ms and 34.5 ms (40.2 ms and 43.9 ms cold against 61.9 ms and 62.7 ms). The probe's GPU time 1.3 ms, 0.5 ms and 1.5 ms. Unmeasured on the RTX 5080. Under `Exact` a draw's vertex work is its vertices times the regions its viewport reaches (`rate_mapped_pass::draw_work`), under `FanOut` its vertices once, its triangles' geometry stage, three vertices per copy (`rate_mapped_pass::fan_out_work`) and the probe's run of the same draws, which emits nothing | -| A `Managed` buffer's range that `did_modify_range` names, on a device without unified memory (two copies: the runtime's own host copy, or the caller's pages through their import, `managed.rs`, `managed_copy.rs`), is copied into the GPU's copy by the GPU as the submission of the next command buffer committed that uses the buffer runs, from the host copy as it holds the range then: no copy on the CPU and no staging (pages no import maps are staged by the CPU at the commit under either value). Macs differ on a CPU write of the range after the commit, before the GPU runs the command buffer: an AMD Radeon Pro 5300M (two copies, macOS 26.7.1) read the bytes at the commit, an Intel UHD Graphics 630 (one copy) read the later write (steps A,B,B,A,B against A,B,B,B,B; `runtime_lane::device_copies`), so the cheaper answer is the default. | `managed_copy_in = ManagedCopyInPolicy::AtSubmission` | `managed_copy_in = ManagedCopyInPolicy::AtCommit`: the commit takes the range as the host copy holds it then, by a CPU copy into staging buffers of host-cached system memory, freed once the submission that copies them in completed (at most 256 MiB staged ahead); a write after the commit reaches no command buffer committed before it, the 5300M's answer | A CPU write after the commit, before the GPU runs the command buffer, may be read. No notice: both answers are a Mac's. `tests::managed_copy_device`'s `ranges_named_*` (the default: each round reads its own bytes or those written after its commit, never an earlier round's; `AtCommit`: its own alone) and `runtime_lane::device_copies`'s `a_did_modify_range_reaches_the_bytes_the_next_commit_finds` (step 4 reads either answer) and `exact_answers_take_a_did_modify_range_at_the_commit` (step 4 reads the bytes at the commit) | A CPU copy of each range at the commit into system memory, which the commit waits for. `tests::managed_copy_device::managed_copy_in_bench` (`MANAGED-COPY-IN`, medians of 40 commits of 32 MiB each, two rounds, over the runtime's own buffer and the caller's pages): RTX 3090 (an eGPU, NVIDIA 620.70.06) `AtSubmission` commit 0.034 to 0.045 ms and 17.3 to 17.7 ms to the completion, `AtCommit` 1.8 to 2.9 ms and 19.2 to 20.2 ms; RX 7900 XTX (RADV, Mesa 26.2.6) `AtSubmission` 0.012 to 0.036 ms and 5.1 to 5.5 ms, `AtCommit` 1.9 to 2.2 ms and 7.1 to 7.5 ms. Memory: the staged ranges until their submission completed, in buffers the device parks and takes again | +| A `Managed` buffer's range that `did_modify_range` names, on a device without unified memory (two copies: the runtime's own host copy, or the caller's pages through their import, `managed.rs`, `managed_copy.rs`), is copied into the GPU's copy by the GPU as the submission of the next command buffer committed that uses the buffer runs, from the host copy as it holds the range then: no copy on the CPU and no staging (pages no import of their own maps are staged by the CPU at the commit under either value, but those a guest RAM's chunk imports hold all of, which the GPU copies from those imports: `WorkCounts::managed_bytes_copied_in_from_ram`, `managed_bytes_staged_in`). Macs differ on a CPU write of the range after the commit, before the GPU runs the command buffer: an AMD Radeon Pro 5300M (two copies, macOS 26.7.1) read the bytes at the commit, an Intel UHD Graphics 630 (one copy) read the later write (steps A,B,B,A,B against A,B,B,B,B; `runtime_lane::device_copies`), so the cheaper answer is the default. | `managed_copy_in = ManagedCopyInPolicy::AtSubmission` | `managed_copy_in = ManagedCopyInPolicy::AtCommit`: the commit takes the range as the host copy holds it then, by a CPU copy into staging buffers of host-cached system memory, freed once the submission that copies them in completed (at most 256 MiB staged ahead); a write after the commit reaches no command buffer committed before it, the 5300M's answer | A CPU write after the commit, before the GPU runs the command buffer, may be read. No notice: both answers are a Mac's. `tests::managed_copy_device`'s `ranges_named_*` (the default: each round reads its own bytes or those written after its commit, never an earlier round's; `AtCommit`: its own alone) and `runtime_lane::device_copies`'s `a_did_modify_range_reaches_the_bytes_the_next_commit_finds` (step 4 reads either answer) and `exact_answers_take_a_did_modify_range_at_the_commit` (step 4 reads the bytes at the commit) | A CPU copy of each range at the commit into system memory, which the commit waits for. `tests::managed_copy_device::managed_copy_in_bench` (`MANAGED-COPY-IN`, medians of 40 commits of 32 MiB each, two rounds, over the runtime's own buffer and the caller's pages): RTX 3090 (an eGPU, NVIDIA 620.70.06) `AtSubmission` commit 0.034 to 0.045 ms and 17.3 to 17.7 ms to the completion, `AtCommit` 1.8 to 2.9 ms and 19.2 to 20.2 ms; RX 7900 XTX (RADV, Mesa 26.2.6) `AtSubmission` 0.012 to 0.036 ms and 5.1 to 5.5 ms, `AtCommit` 1.9 to 2.2 ms and 7.1 to 7.5 ms. Memory: the staged ranges until their submission completed, in buffers the device parks and takes again | All at once: `DevicePolicy::exact_answers()` sets every switch above; each row states its own cost.