From 44eaa098984e791d54d3440310f65e8aaa68476c Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 29 Oct 2026 08:27:25 +0200 Subject: [PATCH] Copies of read-only pages drop the GPU's writes; the gate is asked before write permission The consumer's 4K boot on the RTX 5080 (NVIDIA 615.71.09) died at a buffer rebind onto 12 KiB of read-only pages (`replaceBackingWithRanges:readOnly:`) with `OutOfMemory(Device)`, its gate having refused the pages. Cause: on Linux the runtime asked the pages' write permission before the caller's gate. Read-only pages with a dma-buf source were sent to the source (by_pointer cleared), and the gate, asked only for pages imported by pointer, was skipped. NVIDIA 615's import of the source's dma-bufs fails with VK_ERROR_OUT_OF_DEVICE_MEMORY, and that failure was answered as the call's error, where a failed pointer import takes the copy. The copy path itself never ran. Reproduced on the 5080: a buffer's rebind, a heap's rebind and a no-copy buffer over read-only pages under a refusing gate each answered OutOfMemory(Device). On macOS the gate was asked and the copy made, and the copy's merge-back then wrote the read-only pages: SIGBUS in all three. Fix: - The gate is asked before the write permission, at a no-copy buffer's or heap's making and at a rebind. Pages it refuses, and bytes moved in their page, are a copy, their permission unasked; only pages imported have it asked. - An admitted import of the caller's dma-bufs that fails (out of memory, another Vulkan error) takes the copy too, as the pointer's import did: the gate's documented contract. - A copy of pages the process cannot write drops the GPU's writes (copied.rs), as Metal drops them for read-only memory (read_only_view.rs). The copy asks the system as it is made (`mapped_writable`: PROCMAP_QUERY on Linux, mach_vm_region on macOS). At each completion, every byte the GPU changed in the copy takes back the byte the pages and the copy last agreed on, and nothing is written to the pages. Later commands of the same batch read the write back; a later command buffer reads the pages' bytes. CPU writes through another mapping are copied in at each commit as before. - The copied-host-pages detail says so; read-only-pages-written is not announced over a copy. Changes beyond the consumer's case: gate-refused pages and moved-bytes copies no longer ask the kernel for write permission (no host_mappings_queried for them). Read-only pages with no source under a refusing gate are a copy instead of Unsupported. WorkCounts::copied_dropped_bytes (new). RUNTIME_VERSION 1703. api_signatures.tsv blessed; REFUSALS.md regenerated, unchanged. Docs: HOWTO (copied host buffers), API.md (copied-host-pages, read-only-pages-written), FAST-PATHS (the read-only-memory known gap now excepts copies), ImportGate, HostMemory::new, new_buffer_with_bytes_no_copy, Buffer::rebind_bytes_no_copy, the two Degradation declarations, copied.rs module docs. Tests: - Device, copied_device: - a no-copy buffer, a buffer's rebind and a heap's rebind over read-only pages under a refusing gate, the consumer's form: a read-only shared mapping, a dma-buf source on Linux; - checked in each: the gate asked once with the pages, the source never called, a copy that reads the bytes and a CPU write through the writable mapping; - a blit fill completes with the pages unchanged, nothing merged back, copied_dropped_bytes the fill's changed bytes, and a later command buffer reading the pages' bytes; - Linux: the rebind under an admitting gate whose dma-buf import fails is a degraded copy that drops the writes. - Unit: restore, merge_back of an unwritable copy, mapped_writable (Linux and macOS). - Negative controls: - the three refusing-gate tests on the unfixed runtime: RTX 5080 3/3 fail with OutOfMemory(Device) at the call; M3 Max 3/3 die with SIGBUS; - the admitted test with only the source-failure copy arm removed: the 5080 fails with OutOfMemory(Device). Verified: - RTX 5080 Laptop, NVIDIA 615.71.09 (msi; four holds, each under a minute): runtime copied_device|rebind|host_ram_device|tests::copied::|can_be_written 52/52 at the final tree. The admitted test's copy path ran (its line printed). - M3 Max, MoltenVK 1.4.2, --cfg m2v_gpu under maclock and memcap: the same filter 49/49 (the admitted test is Linux-only). - Mac: degradation_catalogue, copied and host_memory unit tests with api_surface and published_crates 37/37; api_signatures and fast_paths 16/16; clippy --workspace --all-targets --all-features, plain and --cfg m2v_gpu, clean; rustdoc -D warnings for the runtime clean. - msi: clippy -p metal2vulkan-runtime --all-targets --all-features --cfg m2v_gpu clean. - Not run: the validation suites. The runtime-sources pin is left for landing. One work packet, landed as 2 commits on archive/development-linear-2026-10-29: 5012056c31, then 6385d650b9 (the re-pin). --- .../src/buffer_descriptor.rs | 247 +++++----- crates/metal2vulkan-runtime/src/copied.rs | 85 +++- .../metal2vulkan-runtime/src/degradation.rs | 19 +- .../metal2vulkan-runtime/src/host_memory.rs | 89 +++- crates/metal2vulkan-runtime/src/rebind.rs | 4 +- .../metal2vulkan-runtime/src/tests/copied.rs | 64 ++- .../src/tests/copied_device.rs | 434 ++++++++++++++++++ .../src/tests/host_memory.rs | 47 ++ .../src/tests/host_residency.rs | 2 +- .../metal2vulkan-runtime/src/work_counts.rs | 12 + .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/API.md | 11 +- docs/FAST-PATHS.md | 5 +- docs/HOWTO.md | 15 +- 16 files changed, 896 insertions(+), 143 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index cbfe44ea0..bb94020aa 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -305,11 +305,13 @@ impl Device { /// alone; elsewhere the GPU's writes reach them, announced (`private-resource-option`). /// /// Where the caller's gate refuses the import ([`HostMemory::with_import_gate`]), or the import - /// the device and the gate admitted fails (out of memory, another Vulkan error), the buffer is - /// made over a copy of the bytes in memory of the device's own instead, its `contents` still - /// the pointer, announced (`copied-host-pages`): each commit copies in the bytes the CPU - /// changed, and each batch's completion merges back the bytes the GPU changed (`copied.rs`). - /// Pages the process cannot read are never copied, and keep the import's refusal. + /// the device and the gate admitted fails (out of memory, another Vulkan error), of the pointer + /// or of the dma-bufs, the buffer is made over a copy of the bytes in memory of the device's + /// own instead, its `contents` still the pointer, announced (`copied-host-pages`): each commit + /// copies in the bytes the CPU changed, and each batch's completion merges back the bytes the + /// GPU changed (`copied.rs`). A copy of pages the process maps read-only drops the GPU's writes + /// instead, as Metal drops them, and writes nothing to the pages. Pages the process cannot read + /// are never copied, and keep the import's refusal. /// /// Refused: a length of 0 or past `max_buffer_length` (`Nil`, as plain Metal answers nil); /// `Private` or `Memoryless` storage, as Metal stops them, and an undefined @@ -534,15 +536,12 @@ impl Device { let (buffer, memory, again, unwritable) = match in_chunk { Some((buffer, memory)) => (buffer, memory, None, false), None => { - // Only a buffer that imports its pages pins them, and so has their writability - // asked: one that lies in a live import pins none, that import's making asked for - // the same window, and the pages stay writable while imported (`HostMemory::new`). - let host = writability_settled(host, writable, &shared.counts)?; - let unwritable = host.unwritable; // A no-copy buffer or heap whose pointer the device would import (not one whose GPU // writes are dropped) may be a copy instead (`copied.rs`): where the caller's gate // refuses the import, asked here with the pages it would map, holding no lock of - // the runtime's; or where the import it admitted fails. + // the runtime's, before their write permission is asked (a copy pins no page, and + // drops the GPU's writes to pages the process cannot write); or where the import it + // admitted fails, of the pointer or of the caller's dma-bufs. let copyable = !drops_writes; let refused_by_host = copyable && host.by_pointer @@ -553,13 +552,18 @@ impl Device { }; !gate(request) }); + let copy = (call, pointer, length, modes, placement, of_heap); if refused_by_host { shared.counts.host_import_refused_by_host(); - let copy = (call, pointer, length, modes, placement, of_heap); // SAFETY: the caller's contract. let copied = unsafe { self.copied_buffer(copy, release, dirty, None) }; return copied.map(|buffer| kept_with(buffer, kept_runs)); } + // Only a buffer that imports its pages pins them, and so has their writability + // asked: one that lies in a live import pins none, that import's making asked for + // the same window, and the pages stay writable while imported (`HostMemory::new`). + let host = writability_settled(host, writable, &shared.counts)?; + let unwritable = host.unwritable; // SAFETY: the window lies in the pages of the caller's bytes, which stay mapped // (`HostMemory::new`), and the source's pieces hold them // (`HostMemory::with_dma_buf`). No lock of the runtime's is held. A no-copy @@ -568,37 +572,38 @@ impl Device { // pointer where the driver's pointer imports follow their address; a heap's import // stays, as does an import of a read-only view. let imported = - unsafe { self.import_by_pointer(importer, pointer, length, host, class) }; - let imported = match imported { + match unsafe { self.import_by_pointer(importer, pointer, length, host, class) } + { + Ok(Ok((buffer, memory))) => { + #[cfg(unix)] + let again = (!of_heap && !drops_writes) + .then(|| Again::pointer(self, pointer, (length, window, class))) + .flatten(); + #[cfg(not(unix))] + let again = None; + Ok((buffer, memory, again)) + } + // SAFETY: as above. + Ok(Err(source)) => unsafe { + let keep = !of_heap; + let window = &window; + self.import_from_source( + call, importer, pointer, length, window, source, class, keep, + ) + }, + Err(error) => Err(error), + }; + let (buffer, memory, again) = match imported { + Ok(imported) => imported, // An import the device and the gate admitted that then failed: a copy, // announced. Err(error) if copyable && copies_after(&error) => { - let copy = (call, pointer, length, modes, placement, of_heap); // SAFETY: the caller's contract. let copied = unsafe { self.copied_buffer(copy, release, dirty, Some(error)) }; return copied.map(|buffer| kept_with(buffer, kept_runs)); } - imported => imported, - }; - let (buffer, memory, again) = match imported? { - Ok((buffer, memory)) => { - #[cfg(unix)] - let again = (!of_heap && !drops_writes) - .then(|| Again::pointer(self, pointer, (length, window, class))) - .flatten(); - #[cfg(not(unix))] - let again = None; - (buffer, memory, again) - } - // SAFETY: as above. - Err(source) => unsafe { - let keep = !of_heap; - let window = &window; - self.import_from_source( - call, importer, pointer, length, window, source, class, keep, - ) - }?, + Err(error) => return Err(error), }; (buffer, memory, again, unwritable) } @@ -787,12 +792,6 @@ impl Device { }); let chunk_bound = in_chunk.is_some(); let kept_runs = routed.as_ref().map(Routed::kept); - // Only pages imported here are pinned, and so have their writability asked. - let host = match chunk_bound { - true => host, - false => writability_settled(host, writable, &shared.counts)?, - }; - let unwritable = !chunk_bound && host.unwritable; // Whether an import alive now holds every page of them: counted once the import // is made (`WorkCounts::host_rebind_imports_covered`). let start = pointer.as_ptr() as u64; @@ -800,8 +799,10 @@ impl Device { // New pages whose pointer the device would import (a buffer's or a heap's, not a // buffer's whose GPU writes are dropped) may be a copy of them instead // (`copied.rs`): where the caller's gate refuses the import, asked here with the - // pages it would map, holding no lock of the runtime's; or where the import it - // admitted fails. Bytes moved in their page are a copy, the gate unasked. + // pages it would map, holding no lock of the runtime's, before their write + // permission is asked (a copy pins no page, and drops the GPU's writes to pages the + // process cannot write); or where the import it admitted fails, of the pointer or + // of the caller's dma-bufs. Bytes moved in their page are a copy, the gate unasked. let gate = gate.filter(|_| copyable && host.by_pointer && !moved && !chunk_bound); let refused_by_host = match gate { Some(gate) => { @@ -823,6 +824,13 @@ impl Device { if refused_by_host { shared.counts.host_import_refused_by_host(); } + // Only pages imported here are pinned, and so have their writability asked. + let imports = !chunk_bound && !refused_by_host && !moved; + let host = match imports { + true => writability_settled(host, writable, &shared.counts)?, + false => host, + }; + let unwritable = imports && host.unwritable; // The heap's images bound to its bytes, and the images in place over the bytes, // are made again over the copy (`Device::rebound_heap_images`, // `Device::rebound_in_place_images`): its memory holds whole pages from a multiple @@ -834,20 +842,86 @@ impl Device { // SAFETY: the caller's contract. unsafe { self.copied_pages(pointer, length, window, images, own_pages, failed) } }; - let imported = match (in_chunk, refused_by_host || moved) { - (Some(bound), _) => Ok(Ok(Ok(bound))), - (None, true) => Err(None), + let imported = match (in_chunk, imports) { + (Some(bound), _) => Ok(Ok(bound)), + (None, false) => Err(None), // SAFETY: the window lies in the pages of the caller's bytes, which stay // mapped (`HostMemory::new`, `HostMemory::with_dma_buf`). - (None, false) => match unsafe { + (None, true) => match unsafe { self.import_by_pointer(importer, pointer, length, host, class) } { + Ok(imported) => Ok(imported), Err(error) if copyable && copies_after(&error) => Err(Some(error)), - imported => Ok(imported), + Err(error) => return Err(error), }, }; - let (imported, copied) = match imported { - Ok(imported) => (imported, None), + let imported = match imported { + Ok(Ok((host, placement))) => Ok((host, placement, Remade::default())), + // The source is called with no lock of the runtime's held (`dma_buf.rs`): + // the textures over detached bytes are let go of meanwhile, and must be + // settled again after it. + Ok(Err(source)) => { + let was_settled = settled.take().is_some(); + // SAFETY: as above, and the source's pieces hold the pages + // (`HostMemory::with_dma_buf`). + let from_source = unsafe { + let window = &window; + self.import_from_source( + call, importer, pointer, length, window, source, class, false, + ) + }; + let made = match from_source { + Ok((host, placement, _)) => { + // The heap's images bound to its bytes, and the images in place + // over them, made over dma-bufs of their own pages, each of which + // the source makes: still with no lock held. + let again = match heap { + Some(heap) => { + self.dma_buf_images_again(heap, &placement, pointer) + } + None => Ok(Remade::default()), + }; + let again = again.and_then(|mut remade| { + let watches = &in_place; + self.dma_buf_in_place_again( + watches, + &placement, + pointer, + &mut remade, + )?; + Ok(remade) + }); + match again { + Ok(remade) => Ok((host, placement, remade)), + Err(error) => { + self.discard_import(host, placement); + return Err(error); + } + } + } + // An import of the caller's dma-bufs the gate admitted that then + // failed: a copy, as where the pointer's fails. + Err(error) if copyable && copies_after(&error) => Err(Some(error)), + Err(error) => return Err(error), + }; + if was_settled { + match cell.settled() { + Some(again) => settled = Some(again), + None => { + if let Ok((host, placement, remade)) = made { + drop(remade); + self.discard_import(host, placement); + } + return Err(detached_textures()); + } + } + } + made + } + Err(failed) => Err(failed), + }; + let (host, placement, remade, copied) = match imported { + Ok((host, placement, remade)) => (host, placement, remade, None), Err(failed) => { let cause = match (moved, &failed) { (true, _) => CopiedBecause::Moved, @@ -855,57 +929,10 @@ impl Device { (false, None) => CopiedBecause::Refused, }; let (host, placement, copied) = copy(failed)?; - (Ok(Ok((host, placement))), Some((copied, cause))) + (host, placement, Remade::default(), Some((copied, cause))) } }; - let (host, placement, remade) = match imported? { - Ok((host, placement)) => (host, placement, Remade::default()), - // The source is called with no lock of the runtime's held (`dma_buf.rs`): - // the textures over detached bytes are let go of meanwhile, and must be - // settled again after it. - Err(source) => { - let was_settled = settled.take().is_some(); - // SAFETY: as above, and the source's pieces hold the pages - // (`HostMemory::with_dma_buf`). - let (host, placement, _) = unsafe { - let window = &window; - self.import_from_source( - call, importer, pointer, length, window, source, class, false, - ) - }?; - // The heap's images bound to its bytes, and the images in place over them, - // made over dma-bufs of their own pages, each of which the source makes: - // still with no lock held. - let again = match heap { - Some(heap) => self.dma_buf_images_again(heap, &placement, pointer), - None => Ok(Remade::default()), - }; - let again = again.and_then(|mut remade| { - let watches = &in_place; - self.dma_buf_in_place_again(watches, &placement, pointer, &mut remade)?; - Ok(remade) - }); - let remade = match again { - Ok(remade) => remade, - Err(error) => { - self.discard_import(host, placement); - return Err(error); - } - }; - if was_settled { - match cell.settled() { - Some(again) => settled = Some(again), - None => { - drop(remade); - self.discard_import(host, placement); - return Err(detached_textures()); - } - } - } - (host, placement, remade) - } - }; - if unwritable { + if unwritable && copied.is_none() { self.degrade_read_only_pages(call, pointer, length); } // A copy lies at the offset it was laid out at: the old one where the bytes moved. @@ -922,10 +949,11 @@ impl Device { ); match copied { Some((copied, cause)) => { + let drops = copied.drops_writes(); pages.set_copied(copied); shared.counts.copied_host_buffer_made(cause); shared.counts.copied_rebind_pages_made(); - self.degrade_copied(call, pointer, length, cause); + self.degrade_copied(call, pointer, length, (cause, drops)); } None if chunk_bound => {} None => shared.counts.host_rebind_import_made(covered), @@ -1382,13 +1410,14 @@ impl Device { } /// Announce that `call` made the `length` bytes at `pointer` a copy of the caller's pages - /// (`Degradation::CopiedHostPages`), for `cause`. + /// (`Degradation::CopiedHostPages`), for `cause`; one that `drops` the GPU's writes, as the + /// process cannot write the pages, says so. fn degrade_copied( &self, call: &'static str, pointer: NonNull, length: u64, - cause: CopiedBecause, + (cause, drops): (CopiedBecause, bool), ) { self.degrade(Degradation::CopiedHostPages, || { let why = match cause { @@ -1402,9 +1431,18 @@ impl Device { where a texture over the buffer was planned, which no import lays them at" } }; + let dropped = match drops { + true => { + ", whose GPU writes are dropped, as Metal drops them, since the process maps \ + some of their pages read-only" + } + false => "", + }; ( format!("{call} over {length:#x} bytes at {pointer:p}"), - format!("{why}, so the GPU uses a copy of them in memory of the device's own"), + format!( + "{why}, so the GPU uses a copy of them in memory of the device's own{dropped}" + ), ) }); } @@ -1515,6 +1553,7 @@ impl Device { #[cfg(unix)] again: None, }); + let drops = copied.drops_writes(); if let Some(pages) = buffer.host_pages() { pages.set_copied(copied); // The caller's log of the pages' writes stays with them (`dirty_pages.rs`). @@ -1530,7 +1569,7 @@ impl Device { if of_heap { shared.counts.copied_heap_made(); } - self.degrade_copied(call, pointer, length, cause); + self.degrade_copied(call, pointer, length, (cause, drops)); Ok(buffer) } diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index 3604c06e5..fb0d47836 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -22,6 +22,15 @@ //! commit copies in. Bytes are compared 8 at a time and merged one at a time where they differ, //! so a merge writes no byte the GPU did not change. Each batch ends with a barrier that makes //! its writes visible to the host (`tracker::Barrier::to_host`). +//! - **Pages the process cannot write** (read-only pages, as a consumer's alias of a read-only +//! replace, `replaceBackingWithRanges:readOnly:`, maps them), asked of the system as the copy is +//! made ([`mapped_writable`]): the GPU's writes to the copy are dropped, as Metal drops the GPU's +//! writes to read-only memory (`read_only_view.rs`). At each batch's completion every byte the +//! GPU changed in the copy takes back the byte the pages and the copy last agreed on +//! ([`CopiedBuffers::merge_back`]), and nothing is written to the pages: later commands of the +//! same batch read the write back, and a later command buffer the pages' bytes. The CPU's writes +//! to the pages through another mapping are copied in at each commit, as above. Counted: +//! `WorkCounts::copied_dropped_bytes`. //! - **Event signals.** A batch's event signals, submitted while a copy is live, are seen at its //! completion turn alone, after the merge: no read of the value observes them earlier, and a //! wait for them is held on the host until that turn (`event_timeline.rs`), so the GPU's writes @@ -30,7 +39,7 @@ //! - **Cost.** Every live copy is compared whole at each commit and at each batch's completion, //! whichever buffers the work names: O(bytes) per commit and per batch, a fallback's cost //! (`docs/FAST-PATHS.md`, known gaps). Counted: `WorkCounts::copied_copy_in_bytes`, -//! `WorkCounts::copied_merge_back_bytes`. +//! `WorkCounts::copied_merge_back_bytes`, `WorkCounts::copied_dropped_bytes`. //! - **Heaps and rebinds.** A no-copy heap's own buffer is copied as a buffer is, where the heap's //! textures could lie, with a heap's hazard identity; its buffers lie in the copy at their //! offsets, and its textures are shadows of its bytes (`AliasRoute::MemoryShadow` or Metal's @@ -44,7 +53,7 @@ //! before. A texture made over a copied buffer is a shadow of its bytes (`shadowed-texture`). use crate::device::lock; -use crate::host_memory::mapped_readable; +use crate::host_memory::{mapped_readable, mapped_writable}; use crate::work_counts::Counters; use std::ptr::NonNull; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; @@ -78,6 +87,9 @@ struct Entry { copy: NonNull, /// The bytes the pages and the copy last agreed on. snapshot: Box<[u8]>, + /// The process cannot write the pages: the GPU's writes to the copy are dropped, never merged + /// back. + drops_writes: bool, } // SAFETY: the pointers name the caller's pages, which stay mapped while the buffer's import lives @@ -90,6 +102,14 @@ unsafe impl Send for Entry {} pub(crate) struct Copied { buffers: Arc, id: u64, + drops_writes: bool, +} + +impl Copied { + /// Whether the GPU's writes to the copy are dropped: the process cannot write the pages. + pub(crate) fn drops_writes(&self) -> bool { + self.drops_writes + } } impl Drop for Copied { @@ -111,8 +131,10 @@ impl CopiedBuffers { /// Register the copy at `copy` of the `length` bytes at `pages`, its bytes read from the pages /// now ([`read_caller`]: through the kernel, or where it fails, with plain loads of pages - /// mapped readable). Refused, registering nothing, where the process cannot read every page, - /// or the host has no memory for the bytes the copy and the pages last agreed on. + /// mapped readable). Where the process cannot write every page ([`mapped_writable`]), the + /// GPU's writes to the copy are dropped (the module docs). Refused, registering nothing, where + /// the process cannot read every page, or the host has no memory for the bytes the copy and + /// the pages last agreed on. /// /// # Safety /// @@ -131,12 +153,14 @@ impl CopiedBuffers { // readable (the caller's contract). unsafe { read_caller(pages, into, read_pages, mapped_readable) } }; + let start = pages.as_ptr() as u64; + let drops_writes = !mapped_writable(start, start.saturating_add(length as u64)); // SAFETY: the caller's. - unsafe { self.add_reading(pages, copy, length, read) } + unsafe { self.add_reading(pages, copy, length, read, drops_writes) } } /// [`CopiedBuffers::add`], the first bytes of the pages read by `read`, which answers whether - /// it read every one. + /// it read every one; the GPU's writes to the copy dropped where `drops_writes`. /// /// # Safety /// @@ -147,6 +171,7 @@ impl CopiedBuffers { copy: NonNull, length: usize, read: impl FnOnce(NonNull, &mut [u8]) -> bool, + drops_writes: bool, ) -> Result { let mut snapshot = Vec::new(); if snapshot.try_reserve_exact(length).is_err() { @@ -165,11 +190,13 @@ impl CopiedBuffers { pages, copy, snapshot, + drops_writes, }); self.live.fetch_add(1, Ordering::Relaxed); Ok(Copied { buffers: Arc::clone(self), id, + drops_writes, }) } @@ -189,17 +216,26 @@ impl CopiedBuffers { /// At a batch's completion: write back into each copy's pages the bytes the GPU changed in the /// copy since they last agreed, where the CPU did not change them since, before anything sees - /// the batch complete. + /// the batch complete. A copy of pages the process cannot write takes back instead the bytes + /// they last agreed on wherever the GPU changed it: the GPU's writes are dropped, and nothing + /// is written to the pages. pub(crate) fn merge_back(&self, counts: &Counters) { if self.live.load(Ordering::Relaxed) == 0 { return; } - let mut moved = 0u64; + let (mut moved, mut dropped) = (0u64, 0u64); for entry in lock(&self.entries).iter_mut() { - // SAFETY: the entry's pointers are live while it is registered (`Entry`). - moved += unsafe { sync(entry.copy, entry.pages, &mut entry.snapshot, true) }; + match entry.drops_writes { + // SAFETY: the entry's copy is live while it is registered (`Entry`). + true => dropped += unsafe { restore(entry.copy, &entry.snapshot) }, + // SAFETY: the entry's pointers are live while it is registered (`Entry`). + false => { + moved += unsafe { sync(entry.copy, entry.pages, &mut entry.snapshot, true) } + } + } } counts.copied_merged_back(moved); + counts.copied_dropped(dropped); } } @@ -250,6 +286,35 @@ pub(crate) unsafe fn sync( written } +/// Write into `copy` each byte of `snapshot` that `copy` differs from: the GPU's writes to a copy +/// of pages the process cannot write, dropped. The bytes written. +/// +/// # Safety +/// +/// `copy` is `snapshot.len()` bytes of mapped memory. +pub(crate) unsafe fn restore(copy: NonNull, snapshot: &[u8]) -> u64 { + let copy = copy.as_ptr(); + let mut written = 0u64; + let mut at = 0; + while at < snapshot.len() { + let span = (snapshot.len() - at).min(8); + let mut now = [0u8; 8]; + // SAFETY: `span` bytes at `at` lie in `copy` (the caller's). + unsafe { std::ptr::copy_nonoverlapping(copy.add(at), now.as_mut_ptr(), span) }; + if now[..span] != snapshot[at..at + span] { + for byte in 0..span { + if now[byte] != snapshot[at + byte] { + // SAFETY: as above. + unsafe { copy.add(at + byte).write_volatile(snapshot[at + byte]) }; + written += 1; + } + } + } + at += span; + } + written +} + /// Read the caller's `into.len()` bytes at `pages` into `into`: through the kernel (`kernel`, /// [`read_pages`]), and where it fails, with plain loads where every page of them is mapped with /// read permission (`readable`, asked for the bytes' addresses, [`mapped_readable`]). Whether diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index a301c48b7..d6cc78dbd 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1836,9 +1836,10 @@ degradations! { /// A no-copy buffer, heap or rebind was made over host pages the process maps /// read-only, from the caller's dma-buf source (`HostMemory::with_dma_buf`): on Linux, /// where drivers pin a pointer's imported pages for writing, such pages are imported only - /// as dma-bufs of their pages, whose memory the GPU writes. Announced once per device, by - /// the call that makes it, or at each such call where `DeviceOptions::announce_each` - /// asks. + /// as dma-bufs of their pages, whose memory the GPU writes. Where the caller's gate + /// refuses their import, or that import fails, they are a copy whose GPU writes are + /// dropped instead (`CopiedHostPages`). Announced once per device, by the call that makes + /// it, or at each such call where `DeviceOptions::announce_each` asks. ReadOnlyPagesWritten = "read-only-pages-written", Precision, "the GPU's writes through it reach the pages, and the CPU then reads them there, \ where after Metal's GPU writes into pages the process maps read-only the CPU reads \ @@ -1847,11 +1848,13 @@ degradations! { /// caller's host pages in memory of the device's own, which no import maps (`copied.rs`; /// a heap's textures shadows of its bytes): the caller's gate /// (`HostMemory::with_import_gate`) refused the pages' import, or the import the device - /// and the gate admitted failed (out of memory, or another Vulkan error, such as a - /// driver out of the mappings the host kernel allows). A copy whose own allocation fails - /// refuses the call (`OutOfMemory`). Announced once per device, by the call that makes - /// it, or at each such call where `DeviceOptions::announce_each` asks. Counted: - /// `WorkCounts::copied_host_buffers_made`. + /// and the gate admitted failed, of the pointer or of the caller's dma-bufs (out of + /// memory, or another Vulkan error, such as a driver out of the mappings the host kernel + /// allows). A copy of pages the process maps read-only drops the GPU's writes, as Metal + /// drops them: never written to the pages (`WorkCounts::copied_dropped_bytes`; the detail + /// says so). A copy whose own allocation fails refuses the call (`OutOfMemory`). + /// Announced once per device, by the call that makes it, or at each such call where + /// `DeviceOptions::announce_each` asks. Counted: `WorkCounts::copied_host_buffers_made`. CopiedHostPages = "copied-host-pages", Precision, "the GPU uses a copy of the bytes, into which each commit writes every byte the CPU \ changed in the pages since, and from which each batch's completion writes back \ diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 9e00ddd91..b9c4326f0 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -163,15 +163,19 @@ pub type RunResolver = Arc Option>> + Send + /// go on; `false` refuses it, and the buffer is a copied host buffer instead (the heap's own /// buffer too, the rebind's new pages a copy of them), whose bytes the GPU uses in memory of the /// device's own, kept coherent with the pages at each commit and each completion, so the pages -/// take no kernel mapping (`copied.rs`, docs/HOWTO.md, "Copied host buffers"). Called on the +/// take no kernel mapping (`copied.rs`, docs/HOWTO.md, "Copied host buffers"). Asked before the +/// runtime asks the kernel whether the process may write the pages (Linux): pages it refuses are a +/// copy whatever their permission, and a copy of pages the process maps read-only drops the GPU's +/// writes, as Metal drops them. Called on the /// thread that makes the buffer, heap or rebind, holding no lock of the runtime's. Not asked for a /// buffer or rebind that lies in a live import (one made over the same bytes), nor where the device /// refused the import before it (no host-pointer import, an import alignment the range cannot /// meet), nor for memory whose GPU writes Metal's private option bit 24 drops, nor for a buffer's /// rebind to bytes at another offset in their page under a texture planned at the old one, which /// is a copy without asking. A heap's rebind asks it as a heap's making does. An import it lets go -/// on that then fails (out of memory, another Vulkan error) makes the copy all the same. Every copy -/// is announced (`copied-host-pages`). No Metal counterpart. +/// on that then fails (out of memory, another Vulkan error), of the pointer or of the dma-bufs of +/// the caller's source, makes the copy all the same. Every copy is announced +/// (`copied-host-pages`). No Metal counterpart. pub type ImportGate = Arc bool + Send + Sync + 'static>; /// The pages an [`ImportGate`] is asked about: those an import would map for the buffer, from the @@ -246,10 +250,12 @@ impl HostMemory { /// failed every command buffer submitted after a page of an import was made read-only /// (`mprotect`). With a dma-buf source ([`HostMemory::with_dma_buf`]) pages the process maps /// read-only are instead imported from the source alone, announced - /// (`read-only-pages-written`). Some drivers also refuse shared memory (RADV refused anonymous - /// shared memory and mappings of shared memory objects, `memfd` mappings among them); private - /// memory imports everywhere measured. [`HostMemory::with_dma_buf`] imports such memory where - /// the device imports dma-bufs. + /// (`read-only-pages-written`). Under a gate that refuses their import + /// ([`HostMemory::with_import_gate`]), or where the source's import fails, they are a copy + /// whose GPU writes are dropped, as Metal drops them (`copied-host-pages`). Some drivers also + /// refuse shared memory (RADV refused anonymous shared memory and mappings of shared memory + /// objects, `memfd` mappings among them); private memory imports everywhere measured. + /// [`HostMemory::with_dma_buf`] imports such memory where the device imports dma-bufs. pub unsafe fn new(pointer: NonNull) -> HostMemory { HostMemory { pointer, @@ -665,6 +671,75 @@ pub(super) fn mapped_readable(_start: u64, _end: u64) -> bool { false } +/// Whether the process maps every page of `[start, end)` with write permission, as the kernel +/// answers now ([`mappings_permitted`]): where it does not, a copied host buffer of the pages drops +/// the GPU's writes rather than write them back (`copied.rs`). `false` where the mappings cannot be +/// read (`/proc/self/maps` does not open), so that no write back faults. +#[cfg(target_os = "linux")] +pub(super) fn mapped_writable(start: u64, end: u64) -> bool { + mappings_permitted(start, end, Access::Write, &mut 0) == Some(true) +} + +/// [`mapped_writable`] on macOS: the regions of this task over `[start, end)`, without a gap, +/// each with write protection now (`mach_vm_region`, `VM_REGION_BASIC_INFO_64`); `false` where the +/// kernel answers no region. +#[cfg(target_os = "macos")] +pub(super) fn mapped_writable(start: u64, end: u64) -> bool { + unsafe extern "C" { + /// ``: the port of this process's task. + static mach_task_self_: libc::mach_port_t; + fn mach_vm_region( + target_task: libc::vm_map_t, + address: *mut libc::mach_vm_address_t, + size: *mut libc::mach_vm_size_t, + flavor: libc::c_int, + info: *mut libc::c_int, + count: *mut libc::mach_msg_type_number_t, + object_name: *mut libc::mach_port_t, + ) -> libc::kern_return_t; + } + // ``: `VM_REGION_BASIC_INFO_64`, whose `struct vm_region_basic_info_64` + // (packed to 4 bytes) is 9 words, the current protection its first. + const VM_REGION_BASIC_INFO_64: libc::c_int = 9; + const WORDS: usize = 9; + let mut covered = start; + while covered < end { + let (mut address, mut size) = (covered, 0); + let mut info = [0 as libc::c_int; WORDS]; + let mut count = WORDS as libc::mach_msg_type_number_t; + let mut object = 0; + // SAFETY: the call writes the region's address and size, at most `count` words of `info`, + // and a port name (none for this flavour) into the values given. + let answer = unsafe { + mach_vm_region( + mach_task_self_, + &mut address, + &mut size, + VM_REGION_BASIC_INFO_64, + info.as_mut_ptr(), + &mut count, + &mut object, + ) + }; + // The region answered is the first at or past the address: past it is a gap. + if answer != libc::KERN_SUCCESS || address > covered || size == 0 { + return false; + } + if info[0] & libc::VM_PROT_WRITE == 0 { + return false; + } + covered = address.saturating_add(size); + } + true +} + +/// [`mapped_writable`] where the runtime does not ask the system for its mappings: `false` (and no +/// copy is made here: the runtime reads no caller's page, [`mapped_readable`]). +#[cfg(not(any(target_os = "linux", target_os = "macos")))] +pub(super) fn mapped_writable(_start: u64, _end: u64) -> bool { + false +} + /// A permission the process's mappings are asked for. #[cfg(target_os = "linux")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index a9e449512..8e6149bad 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -907,7 +907,9 @@ impl Buffer { /// device and the gate admitted fails (out of memory, another Vulkan error), the buffer is /// given a copy of the new pages in memory of the device's own instead, its `contents` the new /// pointer, announced (`copied-host-pages`, `copied.rs`), an image in place over its bytes made - /// again over the copy. New memory at another offset in its page than the old, where a texture + /// again over the copy. New pages the process maps read-only (Metal's + /// `replaceBackingWithRanges:readOnly:`) are copied so too, and the copy drops the GPU's + /// writes, as Metal drops them. New memory at another offset in its page than the old, where a texture /// over the buffer lives, is given such a copy laid out at the old offset, the gate unasked. /// Metal rebinds over any memory; the copy is the difference. /// diff --git a/crates/metal2vulkan-runtime/src/tests/copied.rs b/crates/metal2vulkan-runtime/src/tests/copied.rs index 8e0700bf2..16c06835b 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied.rs @@ -5,7 +5,8 @@ //! copied all the same and others refused; on Linux, a mapping of a dma-buf (`VM_PFNMAP`), which //! the kernel's read refuses, is copied (where `/dev/udmabuf` opens). -use crate::copied::{read_caller, sync, CopiedBuffers, NotCopied}; +use crate::copied::{read_caller, restore, sync, CopiedBuffers, NotCopied}; +use crate::work_counts::Counters; use std::cell::Cell; use std::ptr::NonNull; use std::sync::Arc; @@ -63,6 +64,64 @@ fn copied_merge_back_keeps_a_byte_the_cpu_changed_since() { assert_eq!(copy, pages); } +#[test] +fn copied_restore_takes_the_gpu_s_bytes_out_of_the_copy_alone() { + let snapshot: Vec = (0..21).collect(); + let mut copy = snapshot.clone(); + // The GPU wrote bytes 2, 3 and 20 (the last, short span). + copy[2] = 0x22; + copy[3] = 0x33; + copy[20] = 0x44; + // SAFETY: the copy is the snapshot's length. + let written = unsafe { restore(at(&mut copy), &snapshot) }; + assert_eq!(written, 3); + assert_eq!(copy, snapshot, "the copy holds the agreed bytes again"); +} + +/// A copy of pages the process cannot write drops the GPU's writes: a completion takes them out +/// of the copy and writes nothing to the pages; a CPU write to the pages is copied in at the next +/// commit as for any copy. A copy of writable pages merges them back. +#[test] +fn copied_merge_back_of_unwritable_pages_drops_the_gpu_s_writes() { + let length = 4099; + let mut pages: Vec = (0..length as u32).map(|i| (i * 5 + 1) as u8).collect(); + let original = pages.clone(); + let mut copy = vec![0_u8; length]; + let buffers = Arc::new(CopiedBuffers::default()); + let counts = Counters::default(); + let read = |from: NonNull, into: &mut [u8]| { + // SAFETY: the pages are `into.len()` bytes of plain memory. + unsafe { std::ptr::copy_nonoverlapping(from.as_ptr(), into.as_mut_ptr(), into.len()) }; + true + }; + // SAFETY: the copy and the pages are the test's, of `length` bytes, live past the answer. + let copied = unsafe { buffers.add_reading(at(&mut pages), at(&mut copy), length, read, true) }; + let copied = copied.unwrap(); + assert!(copied.drops_writes()); + // The GPU writes 100 bytes of the copy; the completion drops them. + copy[1000..1100].fill(0xEE); + buffers.merge_back(&counts); + assert_eq!(pages, original, "nothing written to the pages"); + assert_eq!(copy, original, "the copy holds the pages' bytes again"); + // A CPU write to the pages reaches the copy at the next commit. + pages[7] = !pages[7]; + buffers.copy_in(&counts); + assert_eq!(copy[7], pages[7]); + drop(copied); + // A copy of writable pages merges the GPU's writes back. + let mut writable = original.clone(); + let mut other = vec![0_u8; length]; + // SAFETY: as above. + let copied = + unsafe { buffers.add_reading(at(&mut writable), at(&mut other), length, read, false) }; + let copied = copied.unwrap(); + assert!(!copied.drops_writes()); + other[0] = !other[0]; + buffers.merge_back(&counts); + assert_eq!(writable[0], other[0], "merged back"); + drop(copied); +} + /// Where the kernel's read of the pages fails (a mapping it cannot pin), pages the process maps /// readable are read with plain loads and copied; where a page is not mapped readable, the copy /// is refused and nothing written; where the kernel reads them, no mapping is asked about. @@ -84,7 +143,7 @@ fn copied_pages_the_kernel_cannot_read_are_copied_where_mapped_readable() { }; // SAFETY: the copy and the pages are the test's, of `length` bytes, live past the answer. let copied = - unsafe { buffers.add_reading(at(&mut pages), at(&mut copy), length, read_readable) }; + unsafe { buffers.add_reading(at(&mut pages), at(&mut copy), length, read_readable, false) }; assert!(copied.is_ok(), "copied"); assert_eq!(copy, pages, "the copy holds the pages' bytes"); assert_eq!(asked.get(), Some((start, start + length as u64)), "asked"); @@ -100,6 +159,7 @@ fn copied_pages_the_kernel_cannot_read_are_copied_where_mapped_readable() { at(&mut refused_copy), length, read_unreadable, + false, ) }; assert_eq!(refused.err(), Some(NotCopied::Unreadable)); diff --git a/crates/metal2vulkan-runtime/src/tests/copied_device.rs b/crates/metal2vulkan-runtime/src/tests/copied_device.rs index 757ca09e5..1602bf05a 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied_device.rs @@ -1339,3 +1339,437 @@ fn copied_rebind_keeps_metal_s_order_around_command_buffers() { assert_eq!(texels(&device, &texture), rows(&expected)); drop((texture, buffer)); } + +/// Pages the process maps read-only, as a consumer maps its alias of a read-only replace +/// (`replaceBackingWithRanges:readOnly:`, its maximum protection lowered to read), over shared +/// 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 { + /// The read-only view's first byte. + pointer: NonNull, + /// The writable mapping of the same memory. + writable: NonNull, + /// The address space the view was placed in (`2 * LENGTH` bytes), unmapped with it. + reserved: NonNull, + /// The shared memory, a `memfd`, which udmabuf takes for the source's dma-bufs. + #[cfg(target_os = "linux")] + memory: Arc, + seed: u8, +} + +#[cfg(any(target_os = "linux", target_os = "macos"))] +impl ReadOnlyHost { + fn new(seed: u8) -> ReadOnlyHost { + use std::os::fd::AsRawFd; + let memory = Arc::new(shared_memory()); + let fd = memory.as_raw_fd(); + // SAFETY: a new shared mapping of the memory, at an address the kernel chooses. + let writable = unsafe { + libc::mmap( + std::ptr::null_mut(), + LENGTH, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + fd, + 0, + ) + }; + assert_ne!( + writable, + libc::MAP_FAILED, + "{}", + std::io::Error::last_os_error() + ); + // SAFETY: a new private reservation without access, at an address the kernel chooses. + let reserved = unsafe { + libc::mmap( + std::ptr::null_mut(), + 2 * LENGTH, + libc::PROT_NONE, + libc::MAP_PRIVATE | libc::MAP_ANON, + -1, + 0, + ) + }; + assert_ne!( + reserved, + libc::MAP_FAILED, + "{}", + std::io::Error::last_os_error() + ); + let at = (reserved as usize).next_multiple_of(1 << 16); + // SAFETY: a read-only shared mapping of the memory over the reservation's own pages. + let view = unsafe { + libc::mmap( + at as *mut libc::c_void, + LENGTH, + libc::PROT_READ, + libc::MAP_SHARED | libc::MAP_FIXED, + fd, + 0, + ) + }; + assert_eq!(view as usize, at, "{}", std::io::Error::last_os_error()); + let host = ReadOnlyHost { + pointer: NonNull::new(view.cast()).unwrap(), + writable: NonNull::new(writable.cast()).unwrap(), + reserved: NonNull::new(reserved.cast()).unwrap(), + #[cfg(target_os = "linux")] + memory, + seed, + }; + host.write(0, &pattern(seed)); + host + } + + /// The pattern it was made with. + fn pattern(&self) -> Vec { + pattern(self.seed) + } + + /// 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. + unsafe { std::slice::from_raw_parts(self.pointer.as_ptr(), LENGTH) }.to_vec() + } + + /// Write `bytes` at `at` through the writable mapping, while no command buffer runs. + fn write(&self, at: usize, bytes: &[u8]) { + assert!(at + bytes.len() <= LENGTH); + // SAFETY: the writable mapping's bytes, which no command buffer uses now. + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + self.writable.as_ptr().add(at), + bytes.len(), + ) + }; + } + + /// The view as the consumer hands it to the runtime, under `gate`: on Linux with a source of + /// dma-bufs of its pages (one chunk of the `memfd`'s pages behind each request, through + /// `/dev/udmabuf`), counting its calls in `calls`. + /// + /// # Safety + /// + /// The view outlives every buffer, heap and rebind over it and the device. + unsafe fn memory( + &self, + gate: ImportGate, + calls: &Arc, + ) -> HostMemory { + #[cfg(target_os = "linux")] + let memory = { + use std::sync::atomic::Ordering; + let fd = Arc::clone(&self.memory); + let base = self.pointer.as_ptr() as usize; + let calls = Arc::clone(calls); + let source: crate::DmaBufSource = Arc::new(move |request: crate::DmaBufRequest| { + calls.fetch_add(1, Ordering::AcqRel); + let offset = (request.start.as_ptr() as usize) + .checked_sub(base) + .ok_or_else(|| std::io::Error::other("pages before the view"))?; + Ok(vec![crate::DmaBufChunk { + fd: super::host_residency::udmabuf(&fd, offset as u64, request.length)?, + length: request.length, + }]) + }); + // SAFETY: the caller's; the source's chunks hold exactly the view's pages. + unsafe { HostMemory::with_dma_buf(self.pointer, source) } + }; + #[cfg(target_os = "macos")] + let memory = { + let _ = calls; + // SAFETY: the caller's. + unsafe { HostMemory::new(self.pointer) } + }; + memory.with_import_gate(gate) + } +} + +#[cfg(any(target_os = "linux", target_os = "macos"))] +impl Drop for ReadOnlyHost { + fn drop(&mut self) { + // SAFETY: the mappings made by `new`, which nothing uses now: the reservation holds the + // view. + unsafe { + assert_eq!(libc::munmap(self.writable.as_ptr().cast(), LENGTH), 0); + assert_eq!(libc::munmap(self.reserved.as_ptr().cast(), 2 * LENGTH), 0); + } + } +} + +/// `LENGTH` bytes of new shared memory, zero. +#[cfg(target_os = "linux")] +fn shared_memory() -> std::os::fd::OwnedFd { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + // SAFETY: a NUL-terminated name. + let fd = unsafe { + libc::memfd_create( + c"m2v-read-only-pages".as_ptr(), + libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING, + ) + }; + assert!(fd >= 0, "memfd: {}", std::io::Error::last_os_error()); + // SAFETY: a new descriptor, owned at once. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + // SAFETY: sizes and seals the memfd made above, against shrinking, as udmabuf requires. + unsafe { + assert_eq!(libc::ftruncate(fd.as_raw_fd(), LENGTH as libc::off_t), 0); + assert_eq!( + libc::fcntl(fd.as_raw_fd(), libc::F_ADD_SEALS, libc::F_SEAL_SHRINK), + 0 + ); + } + fd +} + +/// `LENGTH` bytes of new shared memory, zero: a POSIX shared memory object, unlinked at once. +#[cfg(target_os = "macos")] +fn shared_memory() -> std::os::fd::OwnedFd { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::sync::atomic::{AtomicUsize, Ordering}; + static NEXT: AtomicUsize = AtomicUsize::new(0); + let name = format!( + "/m2v-ro-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + ); + let name = std::ffi::CString::new(name).unwrap(); + // SAFETY: a NUL-terminated name; a new object, owned at once and unlinked. + let fd = unsafe { + let fd = libc::shm_open( + name.as_ptr(), + libc::O_RDWR | libc::O_CREAT | libc::O_EXCL, + 0o600 as libc::c_uint, + ); + assert!(fd >= 0, "shm_open: {}", std::io::Error::last_os_error()); + libc::shm_unlink(name.as_ptr()); + OwnedFd::from_raw_fd(fd) + }; + // SAFETY: sizes the object made above. + assert_eq!( + unsafe { libc::ftruncate(fd.as_raw_fd(), LENGTH as libc::off_t) }, + 0 + ); + fd +} + +/// `buffer`, whose bytes are those of `host` from `at`, lies in a copy of the read-only pages +/// whose GPU writes are dropped: the GPU reads their bytes; a CPU write through the writable +/// mapping before a commit reaches the GPU; a fill completes, the pages keep their bytes, nothing +/// is merged back, the fill's bytes are dropped (counted), and a later command buffer reads the +/// pages' bytes, not the fill's. +#[cfg(any(target_os = "linux", target_os = "macos"))] +fn drops_the_gpu_s_writes(device: &Device, (buffer, at): (&Buffer, usize), host: &ReadOnlyHost) { + let length = LENGTH - at; + assert!(buffer.copied(), "the buffer is a copy"); + let pattern = host.pattern(); + assert_eq!( + gpu_bytes_of(device, buffer, length), + pattern[at..], + "the GPU reads the bytes" + ); + host.write(at, &[0xC3; 4096]); + let mut expected = pattern.clone(); + expected[at..at + 4096].fill(0xC3); + assert_eq!( + gpu_bytes_of(device, buffer, length), + expected[at..], + "the GPU reads the CPU's write" + ); + let dropped = expected[at + 4096..at + 8192] + .iter() + .filter(|&&byte| byte != 0x5A) + .count() as u64; + let before = device.work_counts(); + blit(device, |encoder| { + encoder.fill_buffer(buffer, 4096..8192, 0x5A).unwrap(); + }); + let after = device.work_counts(); + assert_eq!(host.bytes(), expected, "the pages keep their bytes"); + assert_eq!( + after.copied_merge_back_bytes - before.copied_merge_back_bytes, + 0, + "nothing is merged back" + ); + assert_eq!( + after.copied_dropped_bytes - before.copied_dropped_bytes, + dropped, + "the fill's bytes are dropped" + ); + assert_eq!( + gpu_bytes_of(device, buffer, length), + expected[at..], + "a later command buffer reads the pages' bytes" + ); + eprintln!("COPIED-READ-ONLY: dropped {dropped} bytes the GPU wrote"); +} + +/// A no-copy buffer over read-only pages (the consumer's no-copy object over its read-only alias) +/// whose import the gate refuses is a copy of them, the source never called, whose GPU writes are +/// dropped. +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[test] +fn copied_buffer_over_read_only_pages_drops_the_gpu_s_writes() { + let host = ReadOnlyHost::new(28); + let Some((device, heard)) = device() else { + return; + }; + let asked: Arc>> = Arc::default(); + let calls: Arc = Arc::default(); + 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(&asked, false), &calls), + LENGTH as u64, + ResourceOptions::default(), + None, + ) + } + .expect("a buffer over read-only pages the gate refuses is a copy"); + let after = device.work_counts(); + assert_eq!(moved(&before, &after), [1, 1, 1, 0, 0]); + let requests = asked.lock().unwrap().clone(); + assert_eq!(requests.len(), 1, "the gate was asked once"); + assert_eq!(requests[0].start, host.pointer, "with the pages"); + assert_eq!(requests[0].length, LENGTH as u64); + assert_eq!( + calls.load(std::sync::atomic::Ordering::Acquire), + 0, + "the source unasked" + ); + assert_eq!(announced(&heard), 1, "announced once"); + drops_the_gpu_s_writes(&device, (&buffer, 0), &host); + drop(buffer); +} + +/// A buffer's rebind to read-only pages (the consumer's `replaceBackingWithRanges:readOnly:`) +/// whose import the gate refuses gives it a copy of them, the source never called, whose GPU +/// writes are dropped; the old pages stay as they were. +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[test] +fn copied_rebind_over_read_only_pages_drops_the_gpu_s_writes() { + let (first, second) = (Host::new(29), ReadOnlyHost::new(30)); + let Some((device, heard)) = device() else { + return; + }; + let buffer = first.buffer(&device, None); + assert!(!buffer.copied(), "imported first"); + let asked: Arc>> = Arc::default(); + let calls: Arc = Arc::default(); + let before = device.work_counts(); + // SAFETY: the view outlives the buffer and the device (dropped after both), and no command + // that uses the buffer is encoded or pending. + let rebound = unsafe { + buffer.rebind_bytes_no_copy(second.memory(gate(&asked, false), &calls), None, None) + }; + let after = device.work_counts(); + rebound.expect("a rebind to read-only pages the gate refuses is a copy"); + assert_eq!(moved(&before, &after), [1, 1, 1, 0, 0]); + assert_eq!( + after.copied_rebind_pages_made - before.copied_rebind_pages_made, + 1 + ); + let requests = asked.lock().unwrap().clone(); + assert_eq!(requests.len(), 1, "the gate was asked once"); + assert_eq!(requests[0].start, second.pointer, "with the new pages"); + assert_eq!(requests[0].length, LENGTH as u64); + assert_eq!( + calls.load(std::sync::atomic::Ordering::Acquire), + 0, + "the source unasked" + ); + assert_eq!(announced(&heard), 1, "announced once"); + drops_the_gpu_s_writes(&device, (&buffer, 0), &second); + assert_eq!(first.bytes(), first.pattern(), "the old pages stay"); +} + +/// A heap's rebind to read-only pages whose import the gate refuses gives it a copy of them, the +/// source never called, whose GPU writes through a buffer placed in it are dropped. +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[test] +fn copied_heap_rebind_over_read_only_pages_drops_the_gpu_s_writes() { + let (first, second) = (Host::new(31), ReadOnlyHost::new(32)); + let Some((device, heard)) = device() else { + return; + }; + let imported = heap(&device, &first, None); + let at = 32 * 1024; + let buffer = imported + .new_buffer_at_offset((LENGTH - at) as u64, ResourceOptions::default(), at as u64) + .unwrap(); + let asked: Arc>> = Arc::default(); + let calls: Arc = Arc::default(); + let before = device.work_counts(); + // SAFETY: the view outlives the heap and the device (dropped after both), and no command + // that uses the heap is encoded or pending. + let rebound = unsafe { + imported.rebind_bytes_no_copy(second.memory(gate(&asked, false), &calls), None, None) + }; + let after = device.work_counts(); + rebound.expect("a heap's rebind to read-only pages the gate refuses is a copy"); + assert_eq!(moved(&before, &after), [1, 1, 1, 0, 0]); + assert_eq!( + after.copied_rebind_pages_made - before.copied_rebind_pages_made, + 1 + ); + let requests = asked.lock().unwrap().clone(); + assert_eq!(requests.len(), 1, "the gate was asked once"); + assert_eq!(requests[0].start, second.pointer, "with the new pages"); + assert_eq!( + calls.load(std::sync::atomic::Ordering::Acquire), + 0, + "the source unasked" + ); + assert_eq!(announced(&heard), 1, "announced once"); + drops_the_gpu_s_writes(&device, (&buffer, at), &second); + assert_eq!(first.bytes(), first.pattern(), "the old pages stay"); + drop((buffer, imported)); +} + +/// A buffer's rebind to read-only pages whose import the gate admits goes to the caller's source +/// (Linux drivers pin a pointer's pages for writing); where the device's import of those dma-bufs +/// then fails (the RTX 5080's, out of device memory), the buffer is a copy of them all the same, +/// counted as degraded, whose GPU writes are dropped. Where the device imports them, or none, the +/// test says what it took and passes. +#[cfg(target_os = "linux")] +#[test] +fn copied_rebind_over_read_only_pages_whose_admitted_import_fails_drops_the_gpu_s_writes() { + let (first, second) = (Host::new(33), ReadOnlyHost::new(34)); + let Some((device, heard)) = device() else { + return; + }; + let buffer = first.buffer(&device, None); + let asked: Arc>> = Arc::default(); + let calls: Arc = Arc::default(); + let before = device.work_counts(); + // SAFETY: the view outlives the buffer and the device (dropped after both), and no command + // that uses the buffer is encoded or pending. + let rebound = unsafe { + buffer.rebind_bytes_no_copy(second.memory(gate(&asked, true), &calls), None, None) + }; + let after = device.work_counts(); + let called = calls.load(std::sync::atomic::Ordering::Acquire); + assert_eq!(asked.lock().unwrap().len(), 1, "the gate was asked once"); + // An import that failed is never the answer: the copy is. + if let Err(error @ (crate::Error::OutOfMemory(_) | crate::Error::Vulkan(_))) = &rebound { + panic!("the admitted import failed and no copy was made: {error:?}"); + } + if !buffer.copied() { + eprintln!( + "COPIED-READ-ONLY-ADMITTED: not a copy here ({rebound:?}, the source called {called} \ + times, {} dma-buf imports made): nothing to test", + after.dma_buf_imports - before.dma_buf_imports + ); + return; + } + rebound.unwrap(); + assert_eq!(moved(&before, &after), [0, 1, 0, 1, 0]); + assert_eq!(called, 1, "the source was asked once"); + assert_eq!(announced(&heard), 1, "announced once"); + drops_the_gpu_s_writes(&device, (&buffer, 0), &second); + eprintln!("COPIED-READ-ONLY-ADMITTED: the source's import failed, and the copy was made"); +} diff --git a/crates/metal2vulkan-runtime/src/tests/host_memory.rs b/crates/metal2vulkan-runtime/src/tests/host_memory.rs index 8874ba345..a04bd27e6 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_memory.rs @@ -302,6 +302,53 @@ fn the_mapping_queries_keep_one_file_open() { assert!(std::sync::Arc::ptr_eq(&first, &again)); } +/// The system's answer to whether the process can write its pages (`mapped_writable`), which a +/// copy of them asks to know whether it drops the GPU's writes (`copied.rs`): pages mapped +/// writable can be written, until one of them is made read-only; a range past a mapping's end, or +/// pages no longer mapped, cannot. +#[cfg(any(target_os = "linux", target_os = "macos"))] +#[test] +fn only_pages_mapped_writable_without_a_gap_can_be_written() { + use crate::host_memory::mapped_writable; + let page = host_page().unwrap(); + let len = 3 * page as usize; + // SAFETY: a fresh private mapping, unmapped below. + let at = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANON, + -1, + 0, + ) + }; + assert_ne!(at, libc::MAP_FAILED); + let start = at as u64; + let end = start + len as u64; + assert!(mapped_writable(start, end), "mapped writable"); + assert!( + mapped_writable(start + page, start + page + 1), + "a byte of it" + ); + // SAFETY: the middle page of the mapping made above, which nothing uses. + let middle = unsafe { at.cast::().add(page as usize) }; + // SAFETY: as above. + assert_eq!( + unsafe { libc::mprotect(middle.cast(), page as usize, libc::PROT_READ) }, + 0 + ); + assert!(!mapped_writable(start, end), "a read-only page among them"); + assert!(mapped_writable(start, start + page), "the first page alone"); + assert!( + !mapped_writable(start + page, start + 2 * page), + "the read-only page" + ); + // SAFETY: the mapping made above, which nothing uses. + assert_eq!(unsafe { libc::munmap(at, len) }, 0); + assert!(!mapped_writable(start, end), "no longer mapped"); +} + /// The check reads this process's own mappings: a fresh page is importable until it is made /// read-only, and a page no longer mapped is not, through the kept file's queries as they are now. #[cfg(target_os = "linux")] diff --git a/crates/metal2vulkan-runtime/src/tests/host_residency.rs b/crates/metal2vulkan-runtime/src/tests/host_residency.rs index 9a8173363..eb137bbcc 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_residency.rs @@ -89,7 +89,7 @@ fn udmabuf_openable(test: &str) -> bool { } /// A dma-buf of `memfd`'s `size` bytes from `offset`. -fn udmabuf(memfd: &OwnedFd, offset: u64, size: u64) -> std::io::Result { +pub(super) fn udmabuf(memfd: &OwnedFd, offset: u64, size: u64) -> std::io::Result { let device = std::fs::OpenOptions::new() .read(true) .write(true) diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index bab40e9fe..6a47cb24e 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -300,6 +300,7 @@ pub(crate) struct Counters { copied_heaps_made: AtomicU64, copied_copy_in_bytes: AtomicU64, copied_merge_back_bytes: AtomicU64, + copied_dropped_bytes: AtomicU64, host_ram_chunks_imported: AtomicU64, host_ram_chunk_bytes: AtomicU64, host_ram_chunks_live: AtomicU64, @@ -2072,6 +2073,12 @@ impl Counters { (self.copied_merge_back_bytes).fetch_add(bytes, 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) { + (self.copied_dropped_bytes).fetch_add(bytes, Ordering::Relaxed); + } + /// A host import the device never releases while idle, for `because`, was made (`kept`), or /// went. pub(crate) fn host_import_kept(&self, because: KeptBecause, kept: bool) { @@ -4371,6 +4378,10 @@ pub struct WorkCounts { /// The bytes the GPU changed in copied host buffers' copies that batches' completions merged /// back into the caller's pages. pub copied_merge_back_bytes: u64, + /// The bytes the GPU changed in copies of pages the process cannot write (read-only pages) + /// that batches' completions dropped: taken out of the copies, the pages' bytes in their + /// place, never written to the pages, as Metal drops the GPU's writes to read-only memory. + pub copied_dropped_bytes: u64, /// The chunks of guest RAM the device imported (`Device::use_host_ram`): 64 MiB of a RAM's /// range each (its last fewer), imported the first time a no-copy object over it was made. pub host_ram_chunks_imported: u64, @@ -5462,6 +5473,7 @@ impl Device { copied_heaps_made: counters.copied_heaps_made.load(Ordering::Relaxed), copied_copy_in_bytes: counters.copied_copy_in_bytes.load(Ordering::Relaxed), copied_merge_back_bytes: counters.copied_merge_back_bytes.load(Ordering::Relaxed), + copied_dropped_bytes: counters.copied_dropped_bytes.load(Ordering::Relaxed), host_ram_chunks_imported: counters.host_ram_chunks_imported.load(Ordering::Relaxed), host_ram_chunk_bytes: counters.host_ram_chunk_bytes.load(Ordering::Relaxed), host_ram_chunks_live: counters.host_ram_chunks_live.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 2b287b633..4ab13c812 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -0609af2b1a7cfe3fcb54e1c4851c2f8285af3b1c9af3cee5bb6f5a06c050795b +faca8fc6a81d13b1e16caba23bb8a2197ee15157d4826c24bad0de831aa7ac8d diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index f9f59dc4c..cd4059a1f 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 479; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1702; +pub const RUNTIME_VERSION: u32 = 1703; /// 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 bd8b205d5..186df8ceb 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2471,6 +2471,7 @@ field metal2vulkan-runtime::WorkCounts.completion_arms_after_a_wake pub completi field metal2vulkan-runtime::WorkCounts.completion_reads_ran_ahead pub completion_reads_ran_ahead: u64 field metal2vulkan-runtime::WorkCounts.compute_pipeline_create_nanos pub compute_pipeline_create_nanos: u64 field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes pub copied_copy_in_bytes: u64 +field metal2vulkan-runtime::WorkCounts.copied_dropped_bytes pub copied_dropped_bytes: u64 field metal2vulkan-runtime::WorkCounts.copied_heaps_made pub copied_heaps_made: u64 field metal2vulkan-runtime::WorkCounts.copied_host_buffers_degraded pub copied_host_buffers_degraded: u64 field metal2vulkan-runtime::WorkCounts.copied_host_buffers_made pub copied_host_buffers_made: u64 diff --git a/docs/API.md b/docs/API.md index 6e58598fb..314e1f317 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2499,15 +2499,20 @@ bound. buffer, heap or rebind was made over host pages the process maps read-only, from the caller's dma-buf source (`HostMemory::with_dma_buf`): on Linux, where drivers pin a pointer's imported pages for writing, such pages are imported only as dma-bufs of their pages, whose memory the GPU - writes. Cost: the GPU's writes through it reach the pages, and the CPU then reads them there, + writes. Where the caller's gate refuses their import, or that import fails, they are a copy whose + GPU writes are dropped instead (`copied-host-pages`). Cost: the GPU's writes through it reach the pages, and the CPU then reads them there, where after Metal's GPU writes into pages the process maps read-only the CPU reads them as they were (an M3 Max under macOS 27.0.1, private and shared memory alike). - `metal2vulkan-degrade-copied-host-pages` (precision). `CopiedHostPages`: A no-copy buffer, a no-copy heap or a buffer's rebind was made over a copy of the caller's host pages in memory of the device's own, which no import maps (a heap's textures shadows of its bytes): the caller's gate (`HostMemory::with_import_gate`) refused the pages' import, or the import the - device and the gate admitted failed (out of memory, or another Vulkan error, such as a driver out - of the mappings the host kernel allows). The copy reads the pages through the kernel, and + device and the gate admitted failed, of the pointer or of the caller's dma-bufs (out of memory, or + another Vulkan error, such as a driver out of the mappings the host kernel allows). The gate is + asked before the pages' write permission: pages the process maps read-only (a VMM's alias of a + read-only replace) are copied as any, and the copy drops the GPU's writes, as Metal drops them: + each batch's completion takes them back out of the copy and writes nothing to the pages + (`copied_dropped_bytes`; the detail says so). The copy reads the pages through the kernel, and where the kernel cannot (on Linux it pins each page, which a dma-buf's mapping does not allow), with plain loads where the process maps every page readable. Pages not mapped, or mapped without read permission, are never copied: the buffer is refused, as their import is. A copy diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 4e8269467..d42cf5b1f 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -380,8 +380,9 @@ driver's. Each is open work. `loadAction = Load` complete; resolving *into* such memory is unknown (no page fault in 520 processes, almost all of them recovery victims). On macOS the runtime imports such pages through a read-only view of them (`read_only_view.rs`), which takes the GPU's writes nowhere as Metal's - memory does. Elsewhere the import is of the caller's own pages and the GPU's writes reach them: - honouring bit 24 there means a read-only import (`Device::no_copy_options`, `host_lie`'s + memory does. Elsewhere the import is of the caller's own pages and the GPU's writes reach them + (a copy of pages the process maps read-only, where the caller's gate refused their import or it + failed, drops them as Metal does, `copied.rs`): honouring bit 24 there means a read-only import (`Device::no_copy_options`, `host_lie`'s `drops_writes`) and measuring what the drivers then do, since ANV lost the device and RADV failed every submission over read-only imported pages. Announced meanwhile as `private-resource-option` and `read-only-pages-written`. diff --git a/docs/HOWTO.md b/docs/HOWTO.md index ea0caeb31..59209c69f 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -321,15 +321,16 @@ happens where: - the caller's gate refuses the import: `HostMemory::with_import_gate(gate)` asks the `ImportGate` once, on the thread making the buffer, heap or rebind and holding no lock of the runtime's, just - before the import, with the pages it would map (`ImportRequest`, the host pages from the first + before the import and before the runtime asks whether the process may write the pages, with the + pages it would map (`ImportRequest`, the host pages from the first byte's through the last's). `false` makes the copy (`WorkCounts::host_imports_refused_by_host`, `copied_host_buffers_refused`). A consumer with a budget of mappings (Linux's `vm.max_map_count`) refuses there, paying in copies instead of a failed call. It is not asked for a buffer or rebind that lies in a live import of the same bytes, memory whose GPU writes Metal's private option bit 24 drops, a rebind whose bytes moved in their page under a texture (below), or where the device refused the pointer before it; -- an import the device and the gate admitted fails (out of memory, another Vulkan error: - `copied_host_buffers_degraded`). +- an import the device and the gate admitted fails, of the pointer or of the dma-bufs of the + caller's source (out of memory, another Vulkan error: `copied_host_buffers_degraded`). The copy is host-visible memory of the device's own; the buffer's `contents` is still the pointer. Each commit writes into the copy every byte the CPU changed in the pages since the copy and the @@ -345,6 +346,14 @@ with read permission: on Linux the kernel's read pins each page, which a mapping (`VM_PFNMAP`) does not allow. Pages not mapped, or mapped without read permission, are never copied: the buffer is refused, as their import is. +Pages the process maps read-only (a VMM's alias of `replaceBackingWithRanges:readOnly:`, its +maximum protection lowered to read) are copied the same way, and the copy drops the GPU's writes, +as Metal drops them: each batch's completion takes the bytes the GPU changed back out of the copy +and writes nothing to the pages (`copied_dropped_bytes`), so later commands of the same command +buffer read the writes back and a later command buffer reads the pages' bytes. The runtime asks +the system whether the process can write the pages as it makes the copy. The announcement's detail +says so. + A no-copy heap's own buffer is copied the same way (`copied_heaps_made`): its buffers lie in the copy, and its textures are shadows of its bytes. `Buffer::rebind_bytes_no_copy` and `Heap::rebind_bytes_no_copy` give the buffer or heap a copy of their new pages the same way