From 442a9fd5385c9178607ef8d8b2d59d654cb790a4 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 29 Oct 2026 06:13:26 +0200 Subject: [PATCH] Bind no-copy objects over one run of guest RAM in the device's chunk import The NVIDIA chunk route's API (HostRam, Device::use_host_ram, HostMemory::with_runs), the chunk source and one-run route, and a chunk-bound buffer's out-of-bounds writes held to the device's own containment (a device test and a known gap). One work packet, landed as 7 commits on archive/development-linear-2026-10-29, in order: * Add HostRam, Device::use_host_ram and HostMemory::with_runs (d3617f7e1d) The API of the NVIDIA chunk route (guest RAM imported whole): the types the chunk source, the GPU copy and the rebind lanes build on. - HostRam (unsafe new(ranges, keep_alive)): the consumer's guest RAM ranges, checked as non-empty, whole host pages, within the address space and apart; a typed refusal otherwise (Invalid, Problem::HostRam). with_dirty_pages takes one DirtyPages log for the whole RAM whose offsets are host addresses (the log's pointer is 0), so one stamp per commit can serve every copy. The keep-alive is dropped with the HostRam (forgotten while the process exits). - Device::use_host_ram(&Arc) -> HostRamUse: a guard, since runtime devices live for the process while a lease promises its RAM for one guest device's life. Dropping the guard ends the use; a later RAM may be used after. Several RAMs whose ranges are apart may be used at once; one whose ranges meet a used RAM's (itself among them) is refused as misuse (Invalid, Problem::HostRam). A device without VK_EXT_external_memory_host is refused (Unsupported, naming it). - HostMemory::with_runs(RunResolver): RunResolver is Arc Option>> + Send + Sync>, asked with the import window, answering host addresses in the RAM's ranges. Stored here; the routing that calls it comes in a later commit. No Metal counterpart for any of it; the doc comments say so. The chunk import itself (lazy 64 MiB chunks) and the routing in buffer_over_host_memory follow. Verified: cargo clippy -p metal2vulkan-runtime --all-targets --all-features -D warnings (Mac); host_ram unit tests 4/4 (range checks, refusals, keep-alive drop); api_signatures and refusal_surface 7/7 after the re-bless and regeneration; rustdoc -D warnings for the runtime crate. * Re-pin the runtime sources at the landing tip (22c47609a9) * Bind no-copy objects over one run of guest RAM in the device's chunk import (7f07d19b3d) What: the chunk source and the one-run route (host_ram.rs). - Chunk source: a device that uses a HostRam imports it by host pointer in 64 MiB chunks (CHUNK_BYTES), never across a range's end, lazily. Each chunk is imported the first time an object over it is made, on that thread, once, under a lock of its own (ChunkSlot). It goes through the existing Memory::import_host: a coherent type, and the device-address flag where bufferDeviceAddress is on. A whole-chunk VkBuffer is kept for the runtime's own copies only, never named by a Metal buffer, root entry or binding. - Chunk lifetime: chunks are never released while idle (they are no HostImport, so host_residency never sees them). Once the HostRamUse is dropped, a chunk is freed when nothing holds it: Placement gains ram_chunk, so every buffer bound in a chunk holds it, and every command buffer that used one does too. The RAM, and so its keep-alive, goes after the free (release_then's after), dropped as the program's. Exiting leaves it all to the process's end. - Routing in buffer_over_host_memory: a buffer that lies in a live import of the same bytes is unchanged. Otherwise, where the device uses a RAM and the memory has a resolver, the resolver is asked once with the import window, on the calling thread with no lock held, before the writability query and the gate. Memory whose GPU writes bit 24 drops is never routed. - One run inside one chunk: Device::bind_in_chunk makes the VkBuffer with host_buffer against the object's own window, checks it with binds_in against that window, and binds it at run offset + binds_in offset in the chunk's memory. That offset must be a multiple of the buffer's alignment, and the buffer must allow the chunk's memory type. Its placement (Placement::ram_chunk) holds the chunk and maps the caller's pointer, so contents stays the pointer. The buffer gets no import of its own, the gate is not asked, and buffer_of keeps the import fixed (no Again). - Several runs, a run crossing a chunk's end, a chunk that cannot be imported or a buffer that cannot bind exactly: today's gate path (import, or copy where the gate refuses). - The RAM and runs are kept on HostPages (ram_runs) until rebind or release, for the GPU copy lane. - An answer that is not whole pages of one used RAM totalling the window is refused: Invalid, Problem::HostRam. - Heaps over host memory take the same routing (of_heap goes through buffer_over_host_memory). - rebind_host_pages only ignores the new HostParts.runs (`runs: _`). The rebind lane asks the resolver there with Device::route_runs and bind_in_chunk. - New WorkCounts: host_ram_chunks_imported, host_ram_chunk_bytes, host_ram_chunks_live (a gauge), chunk_bound_buffers_made. - Docs: HOWTO "Guest RAM imported whole", the runtime README's extension list. RUNTIME_VERSION 1697 -> 1698. Why: the NVIDIA route (the consumer's spec). On a device that refuses dma-buf views, each import of scattered guest pages takes a kernel mapping per page, past vm.max_map_count at 4K. One-run objects bound in chunks take none. How verified (this Mac, M3 Max, MoltenVK, under memcap + maclock): - host_ram unit tests 8/8: chunk spans and lookup; one run in a chunk, a chunk's last pages and a range's short last chunk; several runs and a run crossing a chunk (gate path); broken answers refused. - New device tests tests::host_ram_device 6/6. The path ran: the log prints "chunks imported 1, chunk-bound buffers 2". - One run binds in the chunk: 1 chunk import of 64 MiB, 0 pointer imports, gate not asked, contents == pointer, the GPU reads the bytes, a fill reaches them, a second buffer in the chunk imports nothing. - Containment: a 1.5-page buffer's copy reach <= its 2-page window, and a fill of all of it leaves the sentinel page before and the bytes after it unchanged. - A no-copy heap binds in the chunk. - None, two runs and a crossing run ask the gate once and import; short and outside answers are refused. - A command buffer held behind an event keeps the chunk (live gauge, and the keep-alive not dropped) after the buffer, the use and the RAM are let go of; once it completes the chunk is freed and the keep-alive dropped. - The same RAM twice and an overlapping RAM are refused, a RAM apart is taken, and a new RAM over the same ranges is taken after the first use and imports again. - Regression on the same Mac: 249/249 for host_|copied|dirty|rebind|heap|no_copy|dma_buf|in_place|detach|alias| degradation|profile (copied_device, dirty_pages_device and the host-import tests among them). - clippy -D warnings plain and --cfg m2v_gpu (runtime, all targets, all features); rustdoc -D warnings for the runtime; api_signatures 3/3 after the re-bless. Not run here: NVIDIA (msi 5080) and lavapipe; dma-buf devices' own tests beyond the Mac's. RUNTIME_VERSION 1699 at landing. * Re-derive the generated documents at the landing tip (a9c042f142) They are generated from the whole case set, and the set grew on `development` while this branch was in flight, so the copy committed here counted a smaller one. Verified: regenerating at this tip leaves no change beyond the `Generated at` stamp. * Re-pin the runtime sources at the landing tip (2cfd8d6ef9) * Hold a chunk-bound buffer's out-of-bounds kernel writes to the device's own containment (1b09d84fad) What: a device test (tests::host_ram_device) whose kernel, the owned fixture's scale_and_offset, writes three pages of words through a one-page buffer bound in a chunk of guest RAM. It asserts that the page before the buffer and the pages after it keep a sentinel, and that the kernel wrote the buffer itself. The page-after assertion applies wherever the device keeps the same write, through a one-page buffer of its own, out of the buffer made after it: the chunk binding is held to the device's own containment, measured in the same test. A known gap in docs/FAST-PATHS.md records the device that does not contain such writes. Why: containment (c) of the route. A chunk-bound VkBuffer ends at the object's last page, but the chunk's memory goes on past it, so containment rests on the device's buffer robustness or in-shader checks, not on the import's end as a per-object import does. Found and how verified: - RTX 5080 laptop (NVIDIA 615.71.09), msi, one hold 06:00-06:02, strict form (no device check): host_ram_device 7/7. The chunk's pages after the buffer were untouched. - lavapipe (linux-gate, slot lava, arm64), strict form: 7/7. - M3 Max (MoltenVK 1.4.2), this form: 15/15 host_ram tests. It prints that out-of-bounds writes changed 32720 bytes of the device's own next buffer and 32720 bytes of the chunk's next pages. A control run (not committed) showed that a no-copy pointer import of one page changed 0 bytes past its page. So MoltenVK's gap is within an allocation; it predates the route, which inherits it. - clippy --cfg m2v_gpu -D warnings (runtime, all targets). Also: the RunResolver doc no longer says rebinds ask it; they do not until rebinds are routed (af9f1e057d). * Re-pin the runtime sources at the landing tip (60c300198f) --- crates/metal2vulkan-runtime/README.md | 5 + crates/metal2vulkan-runtime/src/buffer.rs | 10 + .../src/buffer_descriptor.rs | 167 ++-- crates/metal2vulkan-runtime/src/device/mod.rs | 3 + crates/metal2vulkan-runtime/src/error.rs | 9 + .../metal2vulkan-runtime/src/host_memory.rs | 48 +- crates/metal2vulkan-runtime/src/host_ram.rs | 826 ++++++++++++++++++ crates/metal2vulkan-runtime/src/lib.rs | 4 +- crates/metal2vulkan-runtime/src/memory.rs | 36 + .../src/tests/host_ram_device.rs | 678 ++++++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../metal2vulkan-runtime/src/work_counts.rs | 38 + .../runtime-sources.sha256 | 2 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 16 + docs/FAST-PATHS.md | 7 + docs/HOWTO.md | 34 + docs/REFUSALS.md | 10 +- 18 files changed, 1830 insertions(+), 67 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/host_ram.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/host_ram_device.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 4430f05d5..ace48dd80 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -295,6 +295,11 @@ Calls Metal does not have, for a consumer that emulates a Metal device: - `HostMemory::with_import_gate` and its `ImportGate` (with `ImportRequest`): the consumer's gate over a no-copy buffer's, heap's or rebind's import of its pages; a refusal makes a copy of them. +- `HostRam`, `Device::use_host_ram` (with `HostRamUse`) and `HostMemory::with_runs` (with + `RunResolver`): a guest's RAM imported whole, in 64 MiB chunks, for a device that refuses views + of guest pages made through dma-bufs; a no-copy object whose pages the consumer resolves to one + run inside one chunk is bound in the chunk, with no import of its own + ([HOWTO](../../docs/HOWTO.md#guest-ram-imported-whole)). - `HostBytes`: bytes at a pointer that may change while a call reads them (a guest's memory), which `Texture::replace_region_with_host_bytes` and `BufferContents::CopyHost` copy once through the pointer, where the slice forms would need the caller's own copy first. diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 25cc20247..311c5c54b 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -34,6 +34,7 @@ use super::generated_commands::PREPROCESS_BUFFER; use super::heap::{Heap, HeapType}; use super::host_aliases::Alias; use super::host_memory::{HeldBack, KeepAlive, Release}; +use super::host_ram::RamOnDevice; #[cfg(unix)] use super::host_residency::{Again, Residency}; use super::memory::{Mapped, MemoryClass, Placement, BLOCK_BYTES}; @@ -638,6 +639,9 @@ pub(super) struct HostPages { /// The caller's log of the writes to them, where it gave one with their memory /// (`HostMemory::with_dirty_pages`, `dirty_pages.rs`). dirty: OnceLock>, + /// The guest RAM their caller resolved them to and the runs of it they are, in their byte + /// order (`HostMemory::with_runs`, `host_ram.rs`), kept until the rebind or the release. + ram_runs: OnceLock<(Arc, Box<[Range]>)>, } impl HostPages { @@ -653,6 +657,7 @@ impl HostPages { release: OnceLock::new(), listed: AtomicUsize::new(0), dirty: OnceLock::new(), + ram_runs: OnceLock::new(), } } @@ -666,6 +671,11 @@ impl HostPages { let _kept = self.dirty.set(dirty); } + /// Keep the guest RAM and the runs of it their caller resolved them to (`host_ram.rs`). + pub(super) fn keep_runs(&self, runs: (Arc, Box<[Range]>)) { + let _kept = self.ram_runs.set(runs); + } + /// The caller's log of the writes to them, where it gave one. pub(super) fn dirty(&self) -> Option<&Arc> { self.dirty.get() diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index 59b3c527e..eb726b8a4 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -25,6 +25,7 @@ use super::host_memory::{ refuse_unwritable, refused, Deallocator, HostMemory, HostParts, HostRelease, ImportRequest, ImportWindow, Importer, KeepAlive, Source, }; +use super::host_ram::Routed; #[cfg(unix)] use super::host_residency::Again; use super::memory::{ImportFailure, MemoryClass, Placement}; @@ -486,6 +487,7 @@ impl Device { writable, dirty, gate, + runs, } = memory.into_parts(); let host = host_window(call, importer, pointer, length, source, drops_writes)?; let window = host.window; @@ -515,66 +517,91 @@ impl Device { shared.aliases.place(buffer.identity().key, made_over); return Ok(buffer); } - // 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. - let copyable = !drops_writes; - let refused_by_host = copyable - && host.by_pointer - && gate.as_ref().is_some_and(|gate| { - let request = ImportRequest { - start: NonNull::new(window.start as *mut u8).unwrap_or(pointer), - length: window.size, - }; - !gate(request) - }); - 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. - return unsafe { self.copied_buffer(copy, release, dirty, None) }; - } - // 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 buffer's own import of dma-bufs keeps them, so the device may release it - // while idle and import them again (`host_residency.rs`), as it may its own import of - // the 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 { - // 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. - return unsafe { self.copied_buffer(copy, release, dirty, Some(error)) }; - } - imported => imported, + // Pages the caller resolves to runs of a guest RAM the device uses (`host_ram.rs`): asked + // once, here, holding no lock of the runtime's, before the gate. One run inside one chunk + // is bound in the chunk's import, with no import of its own: no pin, no kernel mapping, + // no gate. Others take the paths below, the runs kept with the buffer. A buffer whose GPU + // writes are dropped is never routed: it imports a read-only view of its pages. + let routed = match (&runs, drops_writes) { + (Some(resolver), false) => self.route_runs(call, importer, resolver, &window)?, + _ => None, }; - 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: the window's pages are the bytes of the run in the RAM (the resolver's + // contract, `HostMemory::with_runs`). + let in_chunk = (routed.as_ref()) + .and_then(|routed| unsafe { self.bind_in_chunk(importer, routed, &window, length) }); + let kept_runs = routed.as_ref().map(Routed::kept); + 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. + let copyable = !drops_writes; + let refused_by_host = copyable + && host.by_pointer + && gate.as_ref().is_some_and(|gate| { + let request = ImportRequest { + start: NonNull::new(window.start as *mut u8).unwrap_or(pointer), + length: window.size, + }; + !gate(request) + }); + 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)); + } + // 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 + // buffer's own import of dma-bufs keeps them, so the device may release it while + // idle and import them again (`host_residency.rs`), as it may its own import of the + // 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 { + // 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, + ) + }?, + }; + (buffer, memory, again, unwritable) } - // 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, - ) - }?, }; if unwritable { self.degrade_read_only_pages(call, pointer, length); @@ -610,6 +637,7 @@ impl Device { pages.keep_dirty(dirty); } } + let buffer = kept_with(buffer, kept_runs); // A buffer over the bytes another no-copy buffer covers joins it (`host_aliases.rs`), and // a later one lies in its import; one whose GPU writes are dropped joins none. // A buffer just made lies in its pages (`HostCell::current`). @@ -676,6 +704,8 @@ impl Device { writable, dirty, gate, + // A rebind's resolver is asked by the rebind's own routing (`host_ram.rs`). + runs: _, } = memory.into_parts(); // A buffer whose GPU writes are dropped keeps them dropped over its new pages. let drops_writes = cell.drops_writes(); @@ -942,7 +972,11 @@ impl Device { /// its length as plain Metal does (`Buffer::copy_reach`); where the device's memory /// requirements of that buffer run past the window, it holds its padded length ([`based_size`]) /// instead. - fn host_buffer(&self, window: &ImportWindow, length: u64) -> Result { + pub(super) fn host_buffer( + &self, + window: &ImportWindow, + length: u64, + ) -> Result { let shared = self.shared(); let raw_device = shared.vk(); let make_sized = |base: u64, size: u64| { @@ -1553,6 +1587,21 @@ impl Device { } } +/// `buffer`, the guest RAM and runs its caller resolved its pages to (`host_ram.rs`) kept with +/// its pages, where there are any. +fn kept_with( + buffer: Buffer, + runs: Option<( + Arc, + Box<[std::ops::Range]>, + )>, +) -> Buffer { + if let (Some(runs), Some(pages)) = (runs, buffer.host_pages()) { + pages.keep_runs(runs); + } + buffer +} + /// The host pages a no-copy buffer (or a heap's own buffer) of some length imports /// ([`host_window`]). struct HostWindow { diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index d54fd09c5..d65e0e3dc 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -432,6 +432,8 @@ pub(super) struct DeviceShared { pub(super) rebinds: super::rebind::Rebinds, /// The no-copy buffers by the host memory they were made over (`host_aliases.rs`). pub(super) aliases: super::host_aliases::HostAliases, + /// The guest RAMs it uses, and their chunks it imported (`host_ram.rs`). + pub(crate) host_ram: super::host_ram::RamSource, /// Its copied host buffers, compared at each commit and each batch's completion /// (`copied.rs`). pub(crate) copied: Arc, @@ -1863,6 +1865,7 @@ impl Device { heap_keys: Default::default(), rebinds: Default::default(), aliases: Default::default(), + host_ram: Default::default(), copied: Default::default(), #[cfg(test)] failing_host_imports: Default::default(), diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index d39858b5a..6b546f1c3 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -545,6 +545,15 @@ pub enum Problem { /// /// Basis: ours (a runtime extension's own contract: Metal imports no dma-buf). DmaBuf, + /// Guest RAM, or a run resolver's answer, that breaks its runtime extension's contract + /// (`HostRam::new`, `Device::use_host_ram`, `HostMemory::with_runs`; Metal has none). For the + /// RAM: no range, or a range that is empty, starts or ends off the host page, runs past the + /// address space's end or overlaps another (of the same RAM, or of another RAM the device + /// uses). For an answer: runs that are not whole host pages or do not cover exactly the pages + /// asked for. + /// + /// Basis: ours (a runtime extension's own contract: Metal imports no guest RAM). + HostRam, /// An image the caller made that cannot be wrapped as a texture of the descriptor /// (`new_texture_with_vk_image`). /// diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index e07a32086..148c6fd3d 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -113,6 +113,7 @@ use ash::vk; use metal2vulkan::device::{EnableSet, VkExtension}; use metal2vulkan::error::{Feature, Unsupported}; use std::ffi::c_void; +use std::ops::Range; use std::ptr::NonNull; use std::sync::{Arc, Mutex}; @@ -131,8 +132,29 @@ pub struct HostMemory { dirty: Option>, /// The caller's gate over the import of the pages ([`HostMemory::with_import_gate`]). gate: Option, + /// The caller's resolver of the pages' runs in its guest RAM ([`HostMemory::with_runs`]). + runs: Option, } +/// A consumer's resolver of a no-copy object's pages to the runs of guest RAM they are views of +/// (a runtime extension, [`HostMemory::with_runs`]): asked with the first byte and the length of +/// the whole host pages the runtime would import for the object (its import window, as an +/// [`ImportRequest`] names it), it answers the host addresses of the same bytes in the RAM's +/// ranges ([`HostRam`](crate::HostRam)), in the object's byte order, as runs of whole host pages +/// that together cover exactly the length asked; or `None` where the pages are no view of the +/// RAM (or not all of them, or some are read-only), which leaves the object on the runtime's +/// other paths. Asked at most once per object, as a no-copy buffer or heap is made over the +/// pages (a rebind to them does not ask it: its pages take the rebind's other paths), on the +/// calling thread, holding no lock of the runtime's, before the import gate ([`ImportGate`]); +/// only on a device that uses a RAM +/// ([`Device::use_host_ram`](crate::Device::use_host_ram)), and only where the object would import +/// the pages itself (not one that lies in a live import of the same bytes, nor one whose GPU +/// writes Metal's private option bit 24 drops). The answer is kept with the object until its +/// rebind or release; a later remap of the view does not change it. An answer that breaks this +/// contract is refused (`Invalid`, `Problem::HostRam`). No Metal counterpart: Metal wires the +/// pages at the pointer. +pub type RunResolver = Arc Option>> + Send + Sync + 'static>; + /// A consumer's gate over the import of a no-copy object's pages (a runtime extension, /// [`HostMemory::with_import_gate`]): asked once, just before the runtime imports the pages for a /// no-copy buffer or heap made over them, or for a buffer's rebind to them @@ -192,6 +214,7 @@ impl std::fmt::Debug for HostMemory { .field("writable", &self.writable) .field("dirty_pages", &self.dirty.is_some()) .field("import_gate", &self.gate.is_some()) + .field("runs", &self.runs.is_some()) .finish() } } @@ -232,6 +255,7 @@ impl HostMemory { writable: false, dirty: None, gate: None, + runs: None, } } @@ -279,6 +303,7 @@ impl HostMemory { writable: false, dirty: None, gate: None, + runs: None, } } @@ -361,6 +386,24 @@ impl HostMemory { } } + /// This memory, with the caller's resolver of its pages to the runs of guest RAM they are + /// views of (a runtime extension, [`RunResolver`]). On a device that uses that RAM + /// ([`Device::use_host_ram`](crate::Device::use_host_ram)), a no-copy buffer or heap whose + /// pages the resolver answers as one run inside one of the device's chunks of the RAM is a + /// `VkBuffer` bound in that chunk's import, at the run, sized and bound against the object's + /// own pages as an import of them would be, so no access through the buffer reaches the rest + /// of the chunk: no import of its own, no kernel mapping of the pages, and the import gate + /// ([`HostMemory::with_import_gate`]) is not asked. 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. + pub fn with_runs(self, resolver: RunResolver) -> HostMemory { + HostMemory { + runs: Some(resolver), + ..self + } + } + /// The pointer. pub fn pointer(&self) -> NonNull { self.pointer @@ -369,7 +412,8 @@ impl HostMemory { /// The pointer, the dma-buf source where the caller gave one, whether the caller vouched /// for the pages' write permission ([`HostMemory::assume_writable`]), and its log of the pages /// written ([`HostMemory::with_dirty_pages`]), kept with the pointer its offsets count from, - /// and its gate over their import ([`HostMemory::with_import_gate`]). + /// its gate over their import ([`HostMemory::with_import_gate`]), and its resolver of their + /// runs in guest RAM ([`HostMemory::with_runs`]). pub(super) fn into_parts(self) -> HostParts { let dirty = (self.dirty).map(|hook| DirtySource::new(hook, self.pointer.as_ptr() as u64)); HostParts { @@ -378,6 +422,7 @@ impl HostMemory { writable: self.writable, dirty, gate: self.gate, + runs: self.runs, } } } @@ -389,6 +434,7 @@ pub(super) struct HostParts { pub(super) writable: bool, pub(super) dirty: Option>, pub(super) gate: Option, + pub(super) runs: Option, } /// A no-copy buffer's deallocator (Metal's block): called once, with the pointer and the length, diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs new file mode 100644 index 000000000..b134bf215 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -0,0 +1,826 @@ +//! Guest RAM imported whole (a runtime extension: Metal has none): a VMM whose device refuses +//! views of guest pages made through dma-bufs gives the device the guest's RAM once +//! ([`HostRam`], [`Device::use_host_ram`]), and each no-copy object over a view of that RAM says +//! which runs of it its pages are (`HostMemory::with_runs`). +//! +//! - **The RAM** is the consumer's ranges of host memory, each mapped, readable and writable, for +//! as long as any device uses it ([`HostRam::new`]). A device that uses it imports it by host +//! pointer (`VK_EXT_external_memory_host`) in chunks of [`CHUNK_BYTES`], never across a range's +//! end, lazily: each chunk the first time an object over it is made, on the thread making that +//! object, once (a lock per chunk). The chunks stay imported while the device uses the RAM, are +//! never released while idle (`host_residency.rs`), and are freed once the use is let go of +//! ([`HostRamUse`]'s drop) and nothing holds them: no buffer bound in them, no command buffer +//! that used one. The RAM's keep-alive is dropped after its last chunk is freed. +//! - **One run in place.** A no-copy object whose pages are one run inside one chunk is a +//! `VkBuffer` bound in that chunk's import (`buffer_descriptor.rs`), made and bound as an import +//! of the object's own pages would be: its size reaches no further than the object's last page, +//! so neither its Metal address range, a descriptor's robust range nor a root entry reaches the +//! rest of the chunk. +//! - **The dirty log** ([`HostRam::with_dirty_pages`]): one log for the whole RAM, its offsets +//! host addresses, so one stamp per commit serves every copy over the RAM. +//! +//! [`Device::use_host_ram`]: crate::Device::use_host_ram + +use super::buffer::usage; +use super::buffer_descriptor::HostBuffer; +use super::device::lock; +use super::dirty_pages::{hook, DirtyPages, DirtySource}; +use super::error::{invalid, vulkan, Error, MemoryKind, Problem}; +use super::exit_guard; +use super::host_memory::{ + binds_in, host_page, import_refused, not_importable, ImportWindow, Importer, KeepAlive, + RunResolver, +}; +use super::memory::{ImportFailure, Mapped, MemoryClass, Placement}; +use super::program_objects::ProgramObject; +use super::Device; +use crate::release; +use ash::vk; +use metal2vulkan::error::{Feature, Unsupported}; +use std::ops::Range; +use std::ptr::NonNull; +use std::sync::{Arc, Mutex}; + +/// The bytes of a chunk of the RAM a device imports at once; the last chunk of a range may be +/// fewer. +pub(crate) const CHUNK_BYTES: u64 = 64 << 20; + +/// A consumer's guest RAM (a runtime extension: Metal has none): ranges of this process's host +/// memory that no-copy objects' pages are views of, which a device imports whole, in chunks +/// ([`Device::use_host_ram`]), so that an object over one run of it is bound in a chunk with no +/// import of its own (`HostMemory::with_runs`). Made once per guest RAM and shared, as an +/// `Arc`, by every device that uses it. +pub struct HostRam { + /// The ranges, as host addresses, by start, apart. + ranges: Vec>, + /// The caller's log of the writes to the RAM, its offsets host addresses. + dirty: Option>, + /// What keeps the ranges mapped, dropped once no device holds a chunk of them. + keep_alive: Mutex>>, +} + +impl std::fmt::Debug for HostRam { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HostRam") + .field("ranges", &self.ranges.len()) + .field("dirty_pages", &self.dirty.is_some()) + .finish() + } +} + +impl HostRam { + /// The RAM of `ranges` (each a first byte and a length), kept mapped by `keep_alive`, which is + /// dropped once no device holds a chunk of it any more (`None` for none). + /// + /// Refused: no range, or a range that is empty, starts or ends off the host page, runs past + /// the address space's end, or overlaps another (`Invalid`, `Problem::HostRam`); a system + /// whose page size the runtime cannot ask (`Unsupported`, `HostMemory`). + /// + /// # Safety + /// + /// Every range is mapped memory of this process, readable and writable, and stays so, at its + /// address and with the same backing, until `keep_alive` is dropped (or, with none, until the + /// `HostRam` is dropped and no device holds a chunk of it: every [`HostRamUse`] of it dropped + /// and every buffer bound in a chunk released, and every command buffer that used one + /// completed); nothing frees, unmaps, remaps or write-protects it meanwhile. Reading or + /// writing its bytes while the GPU writes them is a data race, as Metal's `contents` is. + pub unsafe fn new( + ranges: &[(NonNull, u64)], + keep_alive: Option, + ) -> Result { + const CALL: &str = "HostRam::new"; + let page = host_page() + .ok_or_else(|| Error::Unsupported(Unsupported::not_implemented(Feature::HostMemory)))?; + let pairs = ranges + .iter() + .map(|(start, length)| (start.as_ptr() as u64, *length)); + let ranges = checked_ranges(pairs, page).ok_or_else(|| invalid(CALL, Problem::HostRam))?; + Ok(HostRam { + ranges, + dirty: None, + keep_alive: Mutex::new(keep_alive.map(ProgramObject::new)), + }) + } + + /// This RAM, with the caller's log of the writes to its pages (a runtime extension, + /// [`DirtyPages`]), whose offsets are **host addresses** (the log's pointer is address 0): one + /// log for every range, so that one stamp per commit serves every copy the runtime keeps of + /// pages of the RAM. Objects off the RAM keep their own logs (`HostMemory::with_dirty_pages`). + /// No Metal counterpart. + pub fn with_dirty_pages(mut self, source: Arc) -> HostRam + where + D: DirtyPages + ?Sized + 'static, + D::Watch: 'static, + { + self.dirty = Some(DirtySource::new(hook(source), 0)); + self + } + + /// Whether any range of this RAM meets any of `other`'s. + fn meets(&self, other: &HostRam) -> bool { + (self.ranges.iter()) + .any(|a| (other.ranges.iter()).any(|b| a.start < b.end && b.start < a.end)) + } +} + +impl Drop for HostRam { + fn drop(&mut self) { + let keep_alive = (self.keep_alive.get_mut()) + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); + // The process exiting leaves the ranges imported to its end (`exit_guard`). + if exit_guard::enter().is_none() { + std::mem::forget(keep_alive); + return; + } + if let Some(keep_alive) = keep_alive { + exit_guard::program_release(move || drop(keep_alive)); + } + } +} + +/// `pairs` (first bytes and lengths) as ranges by start, where each is non-empty, whole `page`s, +/// within the address space, and apart from the others; `None` otherwise, or for no range. +fn checked_ranges( + pairs: impl IntoIterator, + page: u64, +) -> Option>> { + let mut ranges = Vec::new(); + for (start, length) in pairs { + let end = start.checked_add(length)?; + let whole = start.is_multiple_of(page) && length.is_multiple_of(page); + if length == 0 || !whole { + return None; + } + ranges.push(start..end); + } + ranges.sort_by_key(|range| range.start); + let apart = ranges.windows(2).all(|pair| pair[0].end <= pair[1].start); + (apart && !ranges.is_empty()).then_some(ranges) +} + +/// A device's use of a [`HostRam`] ([`Device::use_host_ram`]): while it lives, the device imports +/// the RAM's chunks as objects over them are made, and keeps them. Dropping it lets go of the +/// use: each chunk is freed once nothing holds it (no buffer bound in it, no command buffer that +/// used one), and the RAM's keep-alive goes after the last. It holds the device. No Metal +/// counterpart. +#[must_use = "dropping the use lets go of the RAM at once"] +pub struct HostRamUse { + device: Device, + ram: Arc, +} + +impl std::fmt::Debug for HostRamUse { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("HostRamUse") + .field("ram", &self.ram.ram) + .finish() + } +} + +impl Drop for HostRamUse { + fn drop(&mut self) { + let gone = self.device.shared().host_ram.remove(&self.ram); + // The chunks no object holds are freed here, with no lock of the source held. + drop(gone); + } +} + +/// A RAM as one device uses it: the RAM, and its chunks, each imported once, the first time an +/// object over it is made. +pub(crate) struct RamOnDevice { + ram: Arc, + /// Its chunks, by start ([`chunk_spans`]). + slots: Vec, +} + +/// One chunk of a RAM a device uses: its host bytes, and its import once made, behind a lock of +/// its own, so the first objects over it import it once and objects over other chunks wait for +/// none of it. +struct ChunkSlot { + span: Range, + chunk: Mutex>>, +} + +/// The chunks of `ranges` (host addresses, by start): [`CHUNK_BYTES`] from each range's start, +/// the last of each range ending at its end, so that no chunk crosses a range's end. +fn chunk_spans(ranges: &[Range]) -> Vec> { + let mut spans = Vec::new(); + for range in ranges { + let mut start = range.start; + while start < range.end { + let end = range.end.min(start.saturating_add(CHUNK_BYTES)); + spans.push(start..end); + start = end; + } + } + spans +} + +/// The index of the span of `spans` (by start, apart) that holds the host address `address`. +fn span_of(spans: &[Range], address: u64) -> Option { + let after = spans.partition_point(|span| span.start <= address); + let at = after.checked_sub(1)?; + spans[at].contains(&address).then_some(at) +} + +impl RamOnDevice { + /// `ram`, none of its chunks imported. + fn new(ram: &Arc) -> RamOnDevice { + let slots = (chunk_spans(&ram.ranges).into_iter()) + .map(|span| ChunkSlot { + span, + chunk: Mutex::new(None), + }) + .collect(); + RamOnDevice { + ram: Arc::clone(ram), + slots, + } + } + + /// The chunks' spans. + fn spans(&self) -> Vec> { + self.slots.iter().map(|slot| slot.span.clone()).collect() + } + + /// The import of chunk `slot` on `device`: kept, or made now, once, under the chunk's own + /// lock (`Device::import_chunk`). A failed import is not kept: the next object over the chunk + /// tries again. + fn chunk( + &self, + device: &Device, + importer: &Importer, + slot: usize, + ) -> Result, Error> { + let slot = &self.slots[slot]; + let mut held = lock(&slot.chunk); + if let Some(chunk) = held.as_ref() { + return Ok(Arc::clone(chunk)); + } + // SAFETY: the span is pages of the RAM's ranges, which stay mapped, readable and + // writable, while a chunk holds the RAM (`HostRam::new`). + let chunk = + Arc::new(unsafe { device.import_chunk(importer, &self.ram, slot.span.clone()) }?); + *held = Some(Arc::clone(&chunk)); + Ok(chunk) + } +} + +/// A device's import of one chunk of a RAM (`VK_EXT_external_memory_host`): the memory, and a +/// `VkBuffer` over the whole chunk, for the runtime's own copies between the chunk and memory of +/// the device's own alone; no Metal buffer, root entry or binding ever names it. Buffers bound +/// in the chunk ([`Device::bind_in_chunk`]) hold it through their placement (`memory.rs`), and so +/// do the command buffers that use them, until they completed; the device holds it while it uses +/// the RAM ([`HostRamUse`]). The last holder destroys the `VkBuffer` and frees the memory, and the +/// RAM, which the chunk holds, goes after the free: its keep-alive with it once no chunk holds it. +/// Never released while idle (`host_residency.rs`). Left to the process's end while it exits. +pub(crate) struct RamChunk { + device: Device, + /// The host bytes imported. + span: Range, + /// The `VkBuffer` over the whole chunk. + raw: vk::Buffer, + /// The import's placement: a dedicated block of the device's memory (`Memory::import_host`). + placement: Placement, + /// The RAM, let go of once the memory is freed; `None` once let go of. + ram: Option>, +} + +impl std::fmt::Debug for RamChunk { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RamChunk") + .field("start", &self.span.start) + .field("bytes", &(self.span.end - self.span.start)) + .finish() + } +} + +impl RamChunk { + /// The memory imported. + pub(crate) fn memory(&self) -> vk::DeviceMemory { + self.placement.memory + } + + /// The index of the memory's type. + pub(crate) fn type_index(&self) -> u32 { + self.placement.type_index() + } +} + +impl Drop for RamChunk { + fn drop(&mut self) { + let ram = self.ram.take(); + // The Vulkan teardown is a section of the exit guard. + let Some(busy) = exit_guard::enter() else { + // The process is exiting: the chunk stays imported to its end, and the RAM's + // keep-alive with it. + std::mem::forget(ram); + return; + }; + let shared = self.device.shared(); + // SAFETY: nothing uses the buffer: no command names it but the runtime's copies, whose + // command buffers hold the chunk until they completed. + unsafe { release::object(shared.vk(), self.raw) }; + let after = ram.map(|ram| Box::new(RamAfterFree(Some(ram))) as Box); + // Every buffer bound in the chunk went before it (each holds it), and every command + // buffer that used one completed; the free may wait for the batches in flight + // (`freed_memory.rs`), and the RAM with it. + let after = lock(&shared.memory).release_then(shared.vk(), &self.placement, after); + shared.counts.host_ram_chunk_freed(); + drop(busy); + drop(after); + } +} + +/// The RAM a chunk held, let go of once the chunk's memory is freed: as the program's, since its +/// drop may drop the caller's keep-alive. +struct RamAfterFree(Option>); + +impl Drop for RamAfterFree { + fn drop(&mut self) { + let Some(ram) = self.0.take() else { + return; + }; + if exit_guard::enter().is_none() { + std::mem::forget(ram); + return; + } + exit_guard::program_release(move || drop(ram)); + } +} + +/// 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 + /// the chunk ([`Device::bind_in_chunk`]). + InChunk { + ram: Arc, + slot: usize, + start: u64, + }, + /// More than one run, or one crossing a chunk's end: the object takes the gate's path, the + /// runs kept with it. + Runs { + ram: Arc, + runs: Vec>, + }, +} + +impl Routed { + /// The RAM and the runs, kept with the object until its rebind or release. + pub(crate) fn kept(&self) -> (Arc, Box<[Range]>) { + match self { + Routed::InChunk { ram, slot, start } => { + let end = ram.slots[*slot].span.end; + (Arc::clone(ram), std::iter::once(*start..end).collect()) + } + Routed::Runs { ram, runs } => (Arc::clone(ram), runs.clone().into_boxed_slice()), + } + } +} + +/// How `runs`, a resolver's answer for `length` bytes of whole `page`s, lie in the chunks +/// `spans` of a RAM: `Ok(Some(slot))` for one run inside one chunk, `Ok(None)` for runs of the +/// RAM that are not (several, or one crossing a chunk's end); `Err` where the answer breaks the +/// resolver's contract: no run, a run that is empty or off the page, runs that do not total +/// `length`, or a run outside the RAM's `ranges`. +fn place_runs( + runs: &[Range], + length: u64, + page: u64, + ranges: &[Range], + spans: &[Range], +) -> Result, ()> { + let mut total: u64 = 0; + for run in runs { + let whole = run.start.is_multiple_of(page) && run.end.is_multiple_of(page); + if run.start >= run.end || !whole { + return Err(()); + } + let inside = ranges + .iter() + .any(|range| range.start <= run.start && run.end <= range.end); + if !inside { + return Err(()); + } + total = total.checked_add(run.end - run.start).ok_or(())?; + } + if runs.is_empty() || total != length { + return Err(()); + } + let [run] = runs else { + return Ok(None); + }; + let slot = span_of(spans, run.start).ok_or(())?; + Ok((run.end <= spans[slot].end).then_some(slot)) +} + +/// The RAMs a device uses ([`Device::use_host_ram`]). +#[derive(Default)] +pub(crate) struct RamSource { + rams: Mutex>>, +} + +impl RamSource { + /// Add `ram`, unless one of its ranges meets a range of a RAM the device uses. + fn add(&self, ram: &Arc) -> Option> { + let mut rams = lock(&self.rams); + if rams.iter().any(|used| used.ram.meets(ram)) { + return None; + } + let used = Arc::new(RamOnDevice::new(ram)); + rams.push(Arc::clone(&used)); + Some(used) + } + + /// Remove `ram`: what the device held of it, for the caller to drop with no lock held. + fn remove(&self, ram: &Arc) -> Option> { + let mut rams = lock(&self.rams); + let at = rams.iter().position(|used| Arc::ptr_eq(used, ram))?; + Some(rams.swap_remove(at)) + } + + /// The RAMs the device uses now. + fn used(&self) -> Vec> { + lock(&self.rams).clone() + } +} + +impl Device { + /// Use the guest RAM `ram` (a runtime extension: Metal has none): from now on, a no-copy + /// buffer or heap made on this device over pages its caller resolves to one run of the RAM + /// (`HostMemory::with_runs`) is bound in the device's import of the chunk of the RAM that run + /// lies in, imported as the first object over it is made, in place of an import of its own + /// (the module docs of `host_ram.rs`). For a device that refuses views of the pages made + /// through dma-bufs, so that each object's own import would take a kernel mapping per page. + /// The use lasts until the returned [`HostRamUse`] is dropped; a device may use several RAMs + /// at once whose ranges are apart, and a new RAM once an earlier use of the same ranges ended + /// (a VMM's next guest). + /// + /// Refused: a device without `VK_EXT_external_memory_host` (`Unsupported`, naming it); a RAM + /// whose ranges meet those of a RAM the device uses already, itself among them (`Invalid`, + /// `Problem::HostRam`); a lost device. + pub fn use_host_ram(&self, ram: &Arc) -> Result { + const CALL: &str = "use_host_ram"; + if self.is_lost() { + return Err(Error::DeviceLost); + } + let shared = self.shared(); + if let Err(unsupported) = &shared.host_import { + return Err(Error::Unsupported(unsupported.clone())); + } + let used = (shared.host_ram.add(ram)).ok_or_else(|| invalid(CALL, Problem::HostRam))?; + Ok(HostRamUse { + device: self.clone(), + ram: used, + }) + } +} + +impl Device { + /// Where `resolver` puts the pages of `window` (`HostMemory::with_runs`): asked once, here, + /// with no lock of the runtime's held, where the device uses a RAM; `None` where it uses none + /// or the resolver answers `None`. An answer that breaks the resolver's contract (runs that + /// are not whole host pages of one RAM the device uses, or do not total the window) is + /// refused (`Invalid`, `Problem::HostRam`). + pub(crate) fn route_runs( + &self, + call: &'static str, + importer: &Importer, + resolver: &RunResolver, + window: &ImportWindow, + ) -> Result, Error> { + let rams = self.shared().host_ram.used(); + if rams.is_empty() { + return Ok(None); + } + let Some(runs) = resolver(window.start, window.size) else { + return Ok(None); + }; + let refused = || invalid(call, Problem::HostRam); + let first = runs.first().ok_or_else(refused)?.start; + let ram = (rams.into_iter()) + .find(|used| used.ram.ranges.iter().any(|range| range.contains(&first))) + .ok_or_else(refused)?; + let spans = ram.spans(); + let placed = place_runs(&runs, window.size, importer.page, &ram.ram.ranges, &spans); + Ok(Some(match placed.map_err(|()| refused())? { + Some(slot) => Routed::InChunk { + ram, + slot, + start: runs[0].start, + }, + None => Routed::Runs { ram, runs }, + })) + } + + /// A no-copy object's `VkBuffer`, of `length` bytes `window.offset` into `window`, bound in + /// the chunk its pages' one run lies in (`routed`, [`Routed::InChunk`]), the chunk imported + /// first where no object over it was made yet: made as an import of the window's own pages + /// would make it (`Device::host_buffer`) and bound where its bytes lie in the chunk, with + /// `binds_in`'s checks against the window, so its size reaches no page past the window's. + /// The placement holds the chunk; its host address is the window's, so the buffer's + /// `contents` stays the caller's pointer. `None` where the chunk cannot be imported or the + /// buffer cannot be bound there exactly (its alignment, its memory types): the object then + /// takes the runtime's other paths. + /// + /// # Safety + /// + /// The window's pages are the bytes of the run in the RAM's chunk: the same backing. + pub(crate) unsafe fn bind_in_chunk( + &self, + importer: &Importer, + routed: &Routed, + window: &ImportWindow, + length: u64, + ) -> Option<(HostBuffer, Placement)> { + let Routed::InChunk { ram, slot, start } = routed else { + return None; + }; + let chunk = ram.chunk(self, importer, *slot).ok()?; + let shared = self.shared(); + let raw_device = shared.vk(); + let buffer = self.host_buffer(window, length).ok()?; + let requirements = buffer.requirements; + // Where the window starts in the chunk, and the buffer in the window. + let in_chunk = start - chunk.span.start; + let bound_at = binds_in(window, buffer.base, buffer.size, &requirements) + .ok() + .map(|at| in_chunk + at) + .filter(|at| at.is_multiple_of(requirements.alignment.max(1))) + .filter(|_| requirements.memory_type_bits & (1 << chunk.type_index()) != 0); + let mapped = NonNull::new(window.start as *mut u8); + let (Some(bound_at), Some(mapped)) = (bound_at, mapped) else { + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, buffer.raw) }; + return None; + }; + let offset = chunk.placement.offset + bound_at; + // SAFETY: the buffer is unbound and made for host allocations, and the chunk's memory + // holds its size and requirements from `offset` (`binds_in` against the window, which + // lies in the chunk). + let bound = + unsafe { crate::creation::bind_buffer(raw_device, buffer.raw, chunk.memory(), offset) }; + if bound.is_err() { + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, buffer.raw) }; + return None; + } + shared.counts.chunk_bound_buffer_made(); + let placement = Placement::ram_chunk( + Arc::clone(&chunk), + chunk.placement.offset + in_chunk, + window.size, + Mapped::of_caller(mapped), + ); + Some((buffer, placement)) + } + + /// Import `span`, host pages of `ram`, as a chunk: a dedicated block of memory of a coherent + /// type both the pages and a host-allocation buffer allow, with the device-address flag where + /// the device enables `bufferDeviceAddress` (`Memory::import_host`), and a `VkBuffer` over the + /// whole of it. Refused where the device's import alignment misses the span's start or end, + /// it passes the device's allocation size, or the driver refuses the pages. + /// + /// # Safety + /// + /// `span` is pages of `ram`'s ranges, which stay mapped while the chunk holds `ram`. + unsafe fn import_chunk( + &self, + importer: &Importer, + ram: &Arc, + span: Range, + ) -> Result { + let shared = self.shared(); + let raw_device = shared.vk(); + let size = span.end - span.start; + let alignment = importer.alignment.max(1); + if !span.start.is_multiple_of(alignment) || !size.is_multiple_of(alignment) { + return Err(not_importable()); + } + let largest = self + .compile_device() + .allocation() + .max_memory_allocation_size; + if size > largest { + return Err(Error::OutOfMemory(MemoryKind::Device)); + } + let pointer = NonNull::new(span.start as *mut u8).ok_or_else(not_importable)?; + let mut external = vk::ExternalMemoryBufferCreateInfo::default() + .handle_types(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); + let info = shared.sharing().buffer( + vk::BufferCreateInfo::default() + .size(size) + .usage(usage(shared.device_address)) + .push_next(&mut external), + ); + // SAFETY: the device is live and `info` and its chain valid. + let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?; + shared.counts.buffer_made(info.usage); + let discard = || { + // SAFETY: the buffer is unused. + unsafe { release::object(raw_device, raw) }; + }; + // SAFETY: `raw` is a live buffer of this device. + let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; + // SAFETY: the pages are host memory aligned to the import alignment (checked above). + let types = match unsafe { importer.memory_types(raw_device, pointer) } { + Ok(types) => types & requirements.memory_type_bits, + Err(error) => { + discard(); + return Err(import_refused(error)); + } + }; + if requirements.size > size { + discard(); + return Err(not_importable()); + } + // SAFETY: the caller's contract keeps the pages mapped while the chunk, which frees the + // placement as it goes, holds the RAM. + let imported = unsafe { + lock(&shared.memory).import_host( + raw_device, + (pointer, None), + size, + types, + MemoryClass::Shared, + ) + }; + let placement = match imported { + Ok(placement) => placement, + Err(failure) => { + discard(); + return Err(match failure { + ImportFailure::NoMemoryType => not_importable(), + ImportFailure::Vulkan(error) => import_refused(error), + }); + } + }; + // SAFETY: the placement is the pages' memory, of the buffer's size and requirements, and + // the buffer is unbound. + let bound = unsafe { + crate::creation::bind_buffer(raw_device, raw, placement.memory, placement.offset) + }; + if let Err(error) = bound { + lock(&shared.memory).free(raw_device, &placement); + discard(); + return Err(vulkan(error)); + } + shared.counts.host_ram_chunk_imported(size); + Ok(RamChunk { + device: self.clone(), + span, + raw, + placement, + ram: Some(Arc::clone(ram)), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PAGE: u64 = 4096; + + #[test] + fn ranges_of_whole_pages_apart_are_taken_by_start() { + let ranges = checked_ranges([(3 * PAGE, PAGE), (0, 2 * PAGE)], PAGE); + assert_eq!(ranges, Some(vec![0..2 * PAGE, 3 * PAGE..4 * PAGE])); + // Ranges that touch are apart. + let touching = checked_ranges([(0, PAGE), (PAGE, PAGE)], PAGE); + assert_eq!(touching, Some(vec![0..PAGE, PAGE..2 * PAGE])); + } + + #[test] + fn ranges_off_the_page_empty_overlapping_or_none_are_refused() { + assert_eq!(checked_ranges([], PAGE), None); + assert_eq!(checked_ranges([(PAGE, 0)], PAGE), None); + assert_eq!(checked_ranges([(PAGE + 1, PAGE)], PAGE), None); + assert_eq!(checked_ranges([(PAGE, PAGE + 1)], PAGE), None); + assert_eq!(checked_ranges([(0, 2 * PAGE), (PAGE, PAGE)], PAGE), None); + assert_eq!(checked_ranges([(u64::MAX - PAGE + 1, PAGE)], PAGE), None); + } + + #[test] + fn host_ram_new_checks_its_ranges() { + let page = host_page().expect("a Unix host's page size"); + let mut pages = vec![0u8; 4 * page as usize]; + let base = pages.as_mut_ptr() as u64; + let start = base.next_multiple_of(page); + let at = |address: u64| NonNull::new(address as *mut u8).unwrap(); + // SAFETY: the bytes are a live allocation of this test, never imported: no device uses + // the RAM. + let ram = unsafe { HostRam::new(&[(at(start), 2 * page)], None) }.unwrap(); + assert_eq!(ram.ranges, vec![start..start + 2 * page]); + assert!(ram.dirty.is_none()); + // SAFETY: as above; refused before anything is kept. + let off = unsafe { HostRam::new(&[(at(start + 1), page)], None) }; + assert!(matches!( + off, + Err(Error::Invalid(ref invalid)) if invalid.problem == Problem::HostRam + )); + // SAFETY: as above. + let none = unsafe { HostRam::new(&[], None) }; + assert!(none.is_err()); + } + + #[test] + fn host_ram_drops_its_keep_alive_with_it() { + let page = host_page().expect("a Unix host's page size"); + let mut pages = vec![0u8; 2 * page as usize]; + let start = (pages.as_mut_ptr() as u64).next_multiple_of(page); + let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + struct Flag(Arc); + impl Drop for Flag { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::SeqCst); + } + } + let keep: KeepAlive = Box::new(Flag(Arc::clone(&dropped))); + let at = NonNull::new(start as *mut u8).unwrap(); + // SAFETY: the bytes are a live allocation of this test, never imported. + let ram = unsafe { HostRam::new(&[(at, page)], Some(keep)) }.unwrap(); + assert!(!dropped.load(std::sync::atomic::Ordering::SeqCst)); + drop(ram); + assert!(dropped.load(std::sync::atomic::Ordering::SeqCst)); + } + + const MIB: u64 = 1 << 20; + + /// One range, as a list. + fn one(range: Range) -> Vec> { + std::iter::once(range).collect() + } + + #[test] + fn chunks_are_64_mib_from_each_range_start_never_across_its_end() { + let ranges = [0..150 * MIB, 1024 * MIB..1088 * MIB]; + let spans = chunk_spans(&ranges); + assert_eq!( + spans, + vec![ + 0..64 * MIB, + 64 * MIB..128 * MIB, + 128 * MIB..150 * MIB, + 1024 * MIB..1088 * MIB, + ] + ); + assert_eq!(span_of(&spans, 0), Some(0)); + assert_eq!(span_of(&spans, 64 * MIB - 1), Some(0)); + assert_eq!(span_of(&spans, 64 * MIB), Some(1)); + assert_eq!(span_of(&spans, 149 * MIB), Some(2)); + assert_eq!(span_of(&spans, 150 * MIB), None, "between the ranges"); + assert_eq!(span_of(&spans, 1087 * MIB), Some(3)); + assert_eq!(span_of(&spans, 1088 * MIB), None, "past the last"); + } + + #[test] + fn one_run_inside_one_chunk_is_bound_there() { + let ranges = one(0..150 * MIB); + let spans = chunk_spans(&ranges); + let run = one(70 * MIB..70 * MIB + 3 * PAGE); + assert_eq!( + place_runs(&run, 3 * PAGE, PAGE, &ranges, &spans), + Ok(Some(1)) + ); + // The last pages of a chunk. + let last = one(64 * MIB - PAGE..64 * MIB); + assert_eq!(place_runs(&last, PAGE, PAGE, &ranges, &spans), Ok(Some(0))); + // A range's last, shorter chunk. + let tail = one(150 * MIB - PAGE..150 * MIB); + assert_eq!(place_runs(&tail, PAGE, PAGE, &ranges, &spans), Ok(Some(2))); + } + + #[test] + fn several_runs_or_one_crossing_a_chunk_take_the_gates_path() { + let ranges = one(0..150 * MIB); + let spans = chunk_spans(&ranges); + let two = [0..PAGE, 8 * PAGE..9 * PAGE]; + assert_eq!(place_runs(&two, 2 * PAGE, PAGE, &ranges, &spans), Ok(None)); + let crossing = one(64 * MIB - PAGE..64 * MIB + PAGE); + assert_eq!( + place_runs(&crossing, 2 * PAGE, PAGE, &ranges, &spans), + Ok(None) + ); + } + + #[test] + fn answers_that_break_the_contract_are_refused() { + let ranges = one(0..150 * MIB); + let spans = chunk_spans(&ranges); + let place = |runs: &[Range], length| place_runs(runs, length, PAGE, &ranges, &spans); + assert_eq!(place(&[], 0), Err(()), "no run"); + assert_eq!(place(&one(PAGE..PAGE), 0), Err(()), "an empty run"); + assert_eq!(place(&one(1..PAGE + 1), PAGE), Err(()), "off the page"); + assert_eq!( + place(&one(0..PAGE), 2 * PAGE), + Err(()), + "short of the window" + ); + assert_eq!(place(&one(0..2 * PAGE), PAGE), Err(()), "past the window"); + let outside = one(150 * MIB..150 * MIB + PAGE); + assert_eq!(place(&outside, PAGE), Err(()), "outside the RAM"); + } +} diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 7c2ef0260..4bbe34532 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -118,6 +118,7 @@ mod heap_sets; mod host_aliases; mod host_bytes; mod host_memory; +mod host_ram; #[cfg(unix)] mod host_residency; #[cfg(unix)] @@ -291,7 +292,8 @@ pub use function_table::{ pub use gpu_time::host_time; pub use heap::{Heap, HeapDescriptor, HeapProblem, HeapType, SizeAndAlign}; pub use host_bytes::HostBytes; -pub use host_memory::{Deallocator, HostMemory, ImportGate, ImportRequest, KeepAlive}; +pub use host_memory::{Deallocator, HostMemory, ImportGate, ImportRequest, KeepAlive, RunResolver}; +pub use host_ram::{HostRam, HostRamUse}; pub use indirect_command_buffer::{ EncodedComputeCommand, EncodedRenderCommand, IndirectBufferBinding, IndirectCommand, IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandBufferProblem, diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 93b2ca98a..ddbd4ba42 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -51,6 +51,7 @@ use super::dma_buf::DmaBufPages; use super::error::{internal, vulkan, Error, MemoryKind}; use super::freed_memory::{Parked, Parking}; use super::fresh_pages::OwnPages; +use super::host_ram::RamChunk; use super::memory_log::{self, MemoryLog}; use super::range::RangeAllocator; use super::read_only_view::ReadOnlyView; @@ -854,6 +855,9 @@ pub(super) struct Placement { /// freed, the source dropped, when their last holder goes. #[cfg(unix)] dma_buf: Option>, + /// The device's import of a chunk of a guest RAM the placement lies in (`host_ram.rs`), which + /// no block of the placement's holds: kept until the placement goes. + ram_chunk: Option>, } impl Placement { @@ -880,6 +884,35 @@ impl Placement { read_only_view: false, #[cfg(unix)] dma_buf: None, + ram_chunk: None, + } + } + + /// The placement of a no-copy object's `size` bytes of host pages, from `offset` of the + /// memory of `chunk`, the device's import of the chunk of a guest RAM they lie in + /// (`host_ram.rs`), whose host address the caller reaches at `mapped` (its own view of the + /// pages). No block of the runtime's, so freeing it returns nothing; it keeps the chunk until + /// it goes. + pub(super) fn ram_chunk( + chunk: Arc, + offset: u64, + size: u64, + mapped: Mapped, + ) -> Placement { + Placement { + type_index: chunk.type_index(), + holds: Holds::Buffers, + block: None, + size, + memory: chunk.memory(), + offset, + mapped: Some(mapped), + address: None, + own_pages: false, + read_only_view: false, + #[cfg(unix)] + dma_buf: None, + ram_chunk: Some(chunk), } } @@ -909,6 +942,7 @@ impl Placement { own_pages: false, read_only_view: false, dma_buf: Some(pages), + ram_chunk: None, } } @@ -983,6 +1017,7 @@ impl Placement { read_only_view: self.read_only_view, #[cfg(unix)] dma_buf: self.dma_buf.clone(), + ram_chunk: self.ram_chunk.clone(), } } } @@ -1338,6 +1373,7 @@ impl Memory { read_only_view: payload.view.is_some(), #[cfg(unix)] dma_buf: None, + ram_chunk: None, } } diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs new file mode 100644 index 000000000..0aba5cf27 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs @@ -0,0 +1,678 @@ +//! Guest RAM imported whole on a device (`host_ram.rs`): a no-copy object whose caller resolves +//! its pages to one run inside one chunk of a RAM the device uses is bound in that chunk's import. +//! +//! - **One run in a chunk.** The buffer is bound in the chunk, imported once, the first time an +//! object over it is made: no import of its own, its gate not asked, its `contents` the +//! pointer; the GPU reads the CPU's bytes and its fill reaches them. A second buffer over the +//! same chunk imports nothing more. A no-copy heap takes the same path. +//! - **Containment.** The buffer's `VkBuffer` reaches no page past its own: a copy out of it +//! reads no further than the window's end, a fill of all of it leaves the chunk's neighbouring +//! pages as they were, and so does a kernel (the owned fixture's `scale_and_offset`) whose +//! threads write three pages of words through a one-page buffer. +//! - **Other answers.** `None`, several runs and one run crossing a chunk's end take the gate's +//! path (asked once, the pointer imported where it admits); an answer that breaks the +//! resolver's contract is refused (`Invalid`, `Problem::HostRam`). +//! - **The use.** Dropping the use while a command buffer still holds a chunk frees the chunk +//! after that command buffer completed, and the RAM's keep-alive goes after it; the same RAM +//! used twice is refused, a RAM apart from it taken; a new RAM over the same ranges is taken once +//! the first use ended. +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. A device that imports no host memory says so and passes. + +use super::dispatch_pending::state; +use crate::{ + Buffer, CommandBufferStatus, Device, DeviceKind, DeviceOptions, Error, EventRef, HostMemory, + HostRam, ImportGate, ImportRequest, KeepAlive, Problem, ResourceOptions, RunResolver, Size, +}; +use std::ops::Range; +use std::ptr::NonNull; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +const WAIT: Duration = Duration::from_secs(60); +const MIB: u64 = 1 << 20; +/// The RAM's bytes: two whole chunks and a short third. +const RAM_BYTES: u64 = 128 * MIB + 256 * 1024; + +/// Anonymous memory standing in for a guest's RAM, unmapped by the keep-alive it is given to. +struct Mapping { + start: u64, + length: u64, + dropped: Arc, +} + +impl Drop for Mapping { + fn drop(&mut self) { + // SAFETY: the mapping this test made, which no device imports any more: its keep-alive + // is dropped after the last chunk over it is freed. + unsafe { libc::munmap(self.start as *mut libc::c_void, self.length as usize) }; + self.dropped.store(true, Ordering::SeqCst); + } +} + +/// A RAM of `RAM_BYTES` in a pattern, its first byte, and whether its keep-alive was dropped. +fn new_ram() -> (Arc, u64, Arc) { + // SAFETY: a fresh private anonymous mapping. + let start = unsafe { + libc::mmap( + std::ptr::null_mut(), + RAM_BYTES as usize, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANON, + -1, + 0, + ) + }; + assert_ne!(start, libc::MAP_FAILED); + let start = start as u64; + let dropped = Arc::new(AtomicBool::new(false)); + let keep: KeepAlive = Box::new(Mapping { + start, + length: RAM_BYTES, + dropped: Arc::clone(&dropped), + }); + let at = NonNull::new(start as *mut u8).unwrap(); + // SAFETY: the mapping is readable and writable until the keep-alive unmaps it. + let ram = unsafe { HostRam::new(&[(at, RAM_BYTES)], Some(keep)) }.unwrap(); + (Arc::new(ram), start, dropped) +} + +/// The byte the pattern holds at host address `address`. +fn pattern(address: u64) -> u8 { + (address % 251) as u8 +} + +/// Write the pattern over `range` of host addresses, while no command buffer runs. +fn fill_pattern(range: Range) { + for address in range { + // SAFETY: bytes of the test's RAM, which no command buffer uses now. + unsafe { *(address as *mut u8) = pattern(address) }; + } +} + +/// The bytes of `range` of host addresses, while no command buffer runs. +fn bytes(range: Range) -> Vec { + let length = (range.end - range.start) as usize; + // SAFETY: as above. + unsafe { std::slice::from_raw_parts(range.start as *const u8, length) }.to_vec() +} + +/// A device of the cfg's kind; `None` where it imports no host memory. +fn device() -> Option { + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + ..DeviceOptions::default() + }; + let device = Device::system_default_with(&options).unwrap(); + if device.shared().host_import.is_err() { + eprintln!("HOST-RAM: the device imports no host memory here; nothing to test"); + return None; + } + Some(device) +} + +/// A resolver answering `answer` of each window it is asked, each window into `asked`. +fn resolver( + asked: &Arc>>, + answer: impl Fn(u64, u64) -> Option>> + Send + Sync + 'static, +) -> RunResolver { + let asked = Arc::clone(asked); + Arc::new(move |start, length| { + asked.lock().unwrap().push((start, length)); + answer(start, length) + }) +} + +/// The pages are their own run of the RAM (the test's views are the RAM itself). +fn itself(start: u64, length: u64) -> Option>> { + Some(std::iter::once(start..start + length).collect()) +} + +/// A gate answering `answer`, each request into `asked`. +fn gate(asked: &Arc>>, answer: bool) -> ImportGate { + let asked = Arc::clone(asked); + Arc::new(move |request| { + asked.lock().unwrap().push(request); + answer + }) +} + +/// A no-copy buffer of `length` bytes at host address `at`, resolved by `runs`, under `gate`. +fn buffer( + device: &Device, + at: u64, + length: u64, + runs: RunResolver, + gate: ImportGate, +) -> Result { + // SAFETY: the RAM's bytes, mapped until its keep-alive goes, after every device let go. + let memory = unsafe { HostMemory::new(NonNull::new(at as *mut u8).unwrap()) } + .with_runs(runs) + .with_import_gate(gate); + // SAFETY: as above. + unsafe { + device.new_buffer_with_bytes_no_copy(memory, length, ResourceOptions::default(), None) + } +} + +/// Commit one command buffer whose blit encoder `encode` fills, and wait for it. +fn blit(device: &Device, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) { + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encode(&mut encoder); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// The buffer's first `length` bytes as the GPU reads them. +fn gpu_bytes(device: &Device, buffer: &Buffer, length: u64) -> Vec { + let own = device + .new_buffer(length, ResourceOptions::shared()) + .unwrap(); + blit(device, |encoder| { + encoder + .copy_from_buffer_to_buffer(buffer, 0, &own, 0, length) + .unwrap(); + }); + let contents = own.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command writes now. + unsafe { std::slice::from_raw_parts(contents.as_ptr(), length as usize) }.to_vec() +} + +/// Wait until `flag` is set, a release on a handler thread having run. +fn settles(flag: &AtomicBool) -> bool { + let started = Instant::now(); + while !flag.load(Ordering::SeqCst) { + if started.elapsed() > Duration::from_secs(20) { + return false; + } + std::thread::sleep(Duration::from_millis(5)); + } + true +} + +#[test] +fn one_run_inside_a_chunk_is_bound_there_with_no_import_of_its_own() { + let Some(device) = device() else { + return; + }; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let page = device.shared().host_import.as_ref().unwrap().page; + // Three pages a page into the second chunk, the pages around them in the pattern too. + let at = start + 64 * MIB + page; + let length = 3 * page; + fill_pattern(at - page..at + length + page); + let (runs, gates): (Arc>, Arc>) = Default::default(); + let before = device.work_counts(); + let first = buffer( + &device, + at, + length, + resolver(&runs, itself), + gate(&gates, true), + ) + .unwrap(); + let after = device.work_counts(); + assert_eq!( + *runs.lock().unwrap(), + vec![(at, length)], + "asked once, the window" + ); + assert!(gates.lock().unwrap().is_empty(), "the gate was not asked"); + assert_eq!( + after.host_ram_chunks_imported - before.host_ram_chunks_imported, + 1 + ); + assert_eq!( + after.host_ram_chunk_bytes - before.host_ram_chunk_bytes, + 64 * MIB + ); + assert_eq!( + after.chunk_bound_buffers_made - before.chunk_bound_buffers_made, + 1 + ); + assert_eq!( + after.host_pointer_imports_made - before.host_pointer_imports_made, + 0, + "no import of its own" + ); + assert_eq!( + first.contents(), + NonNull::new(at as *mut u8), + "contents are the pointer" + ); + assert!(!first.copied()); + // The GPU reads the CPU's bytes, and a fill reaches them. + assert_eq!(gpu_bytes(&device, &first, length), bytes(at..at + length)); + blit(&device, |encoder| { + encoder.fill_buffer(&first, page..2 * page, 0x5A).unwrap(); + }); + let now = bytes(at..at + length); + assert!(now[page as usize..2 * page as usize] + .iter() + .all(|&b| b == 0x5A)); + assert_eq!(now[..page as usize], bytes(at..at + page)[..]); + // A second buffer over another run of the same chunk imports nothing more. + let other = at + 8 * page; + fill_pattern(other..other + page); + let before = device.work_counts(); + let second = buffer( + &device, + other, + page, + resolver(&runs, itself), + gate(&gates, true), + ) + .unwrap(); + let after = device.work_counts(); + assert_eq!( + after.host_ram_chunks_imported - before.host_ram_chunks_imported, + 0 + ); + assert_eq!( + after.chunk_bound_buffers_made - before.chunk_bound_buffers_made, + 1 + ); + assert_eq!( + gpu_bytes(&device, &second, page), + bytes(other..other + page) + ); + eprintln!( + "HOST-RAM: chunks imported {}, chunk-bound buffers {}", + after.host_ram_chunks_imported, after.chunk_bound_buffers_made + ); + drop((first, second, used, ram)); + assert!( + settles(&dropped), + "the keep-alive goes after the last chunk" + ); +} + +#[test] +fn a_chunk_bound_buffer_reaches_no_page_past_its_own() { + let Some(device) = device() else { + return; + }; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let page = device.shared().host_import.as_ref().unwrap().page; + // A buffer of a page and a half, a few pages into the chunk: its window is two pages, and + // the pages around them hold a sentinel. + let at = start + 4 * page; + let length = page + page / 2; + let sentinel = 0xC3u8; + for address in at - page..at + 3 * page { + // SAFETY: bytes of the test's RAM, which no command buffer uses now. + unsafe { *(address as *mut u8) = sentinel }; + } + let (runs, gates): (Arc>, Arc>) = Default::default(); + let buffer = buffer( + &device, + at, + length, + resolver(&runs, itself), + gate(&gates, true), + ) + .unwrap(); + assert_eq!( + device.work_counts().chunk_bound_buffers_made, + 1, + "bound in the chunk" + ); + // A copy out of it reads no further than its window's end. + assert!( + buffer.copy_reach() <= 2 * page, + "reach {} past the window", + buffer.copy_reach() + ); + // A fill of all of it changes its bytes alone. + blit(&device, |encoder| { + encoder.fill_buffer(&buffer, 0..length, 0x11).unwrap(); + }); + let around = bytes(at - page..at + 3 * page); + let (before, rest) = around.split_at(page as usize); + let (inside, after) = rest.split_at(length as usize); + assert!( + before.iter().all(|&b| b == sentinel), + "the page before stays" + ); + assert!( + inside.iter().all(|&b| b == 0x11), + "the buffer's bytes are filled" + ); + assert!(after.iter().all(|&b| b == sentinel), "the bytes after stay"); + drop((buffer, used, ram)); + assert!(settles(&dropped)); +} + +/// Dispatch the owned fixture's `scale_and_offset` over `words` threads, writing `output`, from +/// an input of `0, 1, 2, ...` and a scale of 2, and wait for it. +fn scale_and_offset(device: &Device, output: &Buffer, words: u64) { + let input: Vec = (0..words).flat_map(|i| (i as f32).to_le_bytes()).collect(); + let input = device + .new_buffer_with_bytes(&input, ResourceOptions::shared()) + .unwrap(); + let scale = device + .new_buffer_with_bytes(&2.0f32.to_le_bytes(), ResourceOptions::shared()) + .unwrap(); + let state = state(device); + let queue = device.new_command_queue().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(&state).unwrap(); + encoder.set_buffer(Some(&input), 0, 0).unwrap(); + encoder.set_buffer(Some(output), 0, 1).unwrap(); + encoder.set_buffer(Some(&scale), 0, 2).unwrap(); + encoder + .dispatch_threads(Size::new(words, 1, 1), Size::new(64, 1, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +/// A kernel whose threads write three pages of words through a one-page buffer bound in a chunk +/// changes none of the chunk's pages around it, wherever the device keeps such writes through a +/// buffer of its own out of the next buffer in the same memory: the chunk binding is held to the +/// device's own containment. Where the device does not (MoltenVK on the M3 Max: its out-of-bounds +/// writes reach other bytes of the buffer's allocation, `docs/FAST-PATHS.md`, known gaps), that +/// is said and the chunk's pages are not held to more. +#[test] +fn a_kernel_writing_past_a_chunk_bound_buffer_reaches_no_neighbouring_page() { + let Some(device) = device() else { + return; + }; + let page = device.shared().host_import.as_ref().unwrap().page; + let words = 3 * page / 4; + let sentinel = 0xC3u8; + // The device's own containment: a one-page buffer of its own and the buffer made after it. + let own = device.new_buffer(page, ResourceOptions::shared()).unwrap(); + let next = device + .new_buffer(4 * page, ResourceOptions::shared()) + .unwrap(); + let next_bytes = next.contents().unwrap(); + // SAFETY: the buffer's bytes, which no command buffer uses now. + unsafe { std::ptr::write_bytes(next_bytes.as_ptr(), sentinel, 4 * page as usize) }; + scale_and_offset(&device, &own, words); + // SAFETY: as above. + let next_now = unsafe { std::slice::from_raw_parts(next_bytes.as_ptr(), 4 * page as usize) }; + let reached = next_now.iter().filter(|&&b| b != sentinel).count(); + let contains = reached == 0; + // A one-page output four pages into the chunk, the pages around it a sentinel. + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let at = start + 4 * page; + for address in at - page..at + 4 * page { + // SAFETY: bytes of the test's RAM, which no command buffer uses now. + unsafe { *(address as *mut u8) = sentinel }; + } + let (runs, gates): (Arc>, Arc>) = Default::default(); + let output = buffer( + &device, + at, + page, + resolver(&runs, itself), + gate(&gates, true), + ) + .unwrap(); + assert_eq!( + device.work_counts().chunk_bound_buffers_made, + 1, + "bound in the chunk" + ); + scale_and_offset(&device, &output, words); + let around = bytes(at - page..at + 4 * page); + let (before, rest) = around.split_at(page as usize); + let (inside, after) = rest.split_at(page as usize); + assert!( + before.iter().all(|&b| b == sentinel), + "the page before stays" + ); + let first = f32::from_le_bytes(inside[4..8].try_into().unwrap()); + assert_eq!( + first, 3.0, + "the kernel wrote the buffer (word 1 is 1 * 2 + 1)" + ); + let past = after.iter().filter(|&&b| b != sentinel).count(); + eprintln!( + "HOST-RAM: out-of-bounds writes changed {reached} bytes of a buffer of the device's own \ + after one, and {past} bytes of the chunk's pages after a chunk-bound one" + ); + if contains { + assert_eq!(past, 0, "no write reached the pages after the buffer"); + } + drop((output, used, ram)); + assert!(settles(&dropped)); +} + +#[test] +fn a_no_copy_heap_over_one_run_is_bound_in_the_chunk() { + let Some(device) = device() else { + return; + }; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let page = device.shared().host_import.as_ref().unwrap().page; + let at = start + 16 * page; + let length = 16 * page; + fill_pattern(at..at + length); + let (runs, gates): (Arc>, Arc>) = Default::default(); + // SAFETY: as `buffer`'s. + let memory = unsafe { HostMemory::new(NonNull::new(at as *mut u8).unwrap()) } + .with_runs(resolver(&runs, itself)) + .with_import_gate(gate(&gates, true)); + let descriptor = crate::HeapDescriptor::new( + crate::HeapType::Placement, + length, + ResourceOptions::default(), + ); + let before = device.work_counts(); + // SAFETY: as above. + let heap = + unsafe { device.new_heap_with_bytes_no_copy(memory, &descriptor, None, None) }.unwrap(); + let after = device.work_counts(); + assert_eq!( + after.chunk_bound_buffers_made - before.chunk_bound_buffers_made, + 1 + ); + assert_eq!( + after.host_pointer_imports_made - before.host_pointer_imports_made, + 0 + ); + assert!(gates.lock().unwrap().is_empty(), "the gate was not asked"); + // A buffer placed at a page reads the RAM's bytes there. + let placed = heap + .new_buffer_at_offset(4 * page, ResourceOptions::default(), page) + .unwrap(); + assert_eq!( + gpu_bytes(&device, &placed, 4 * page), + bytes(at + page..at + 5 * page) + ); + drop((placed, heap, used, ram)); + assert!(settles(&dropped)); +} + +#[test] +fn other_answers_take_the_gates_path_and_broken_ones_are_refused() { + let Some(device) = device() else { + return; + }; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let page = device.shared().host_import.as_ref().unwrap().page; + let runs: Arc>> = Arc::default(); + let gates: Arc>> = Arc::default(); + let path = |at: u64, length: u64, answer: RunResolver| { + fill_pattern(at..at + length); + gates.lock().unwrap().clear(); + let before = device.work_counts(); + let made = buffer(&device, at, length, answer, gate(&gates, true)).unwrap(); + let after = device.work_counts(); + assert_eq!(gates.lock().unwrap().len(), 1, "the gate was asked once"); + assert_eq!( + after.chunk_bound_buffers_made, + before.chunk_bound_buffers_made + ); + assert_eq!( + after.host_ram_chunks_imported, + before.host_ram_chunks_imported + ); + assert_eq!( + gpu_bytes(&device, &made, length), + bytes(at..at + length), + "the import reads the bytes" + ); + made + }; + // `None`: today's path. + let none = path(start, 2 * page, resolver(&runs, |_, _| None)); + // Two runs. + let two = path( + start + 8 * page, + 2 * page, + resolver(&runs, |start, length| { + let middle = start + length / 2; + Some(vec![start..middle, middle..start + length]) + }), + ); + // One run crossing the first chunk's end. + let crossing = path(start + 64 * MIB - page, 2 * page, resolver(&runs, itself)); + // An answer short of the window, and one outside the RAM, are refused. + let short = buffer( + &device, + start + 32 * page, + 2 * page, + resolver(&runs, |start, length| { + Some(std::iter::once(start..start + length / 2).collect()) + }), + gate(&gates, true), + ); + assert!(matches!( + short, + Err(Error::Invalid(ref invalid)) if invalid.problem == Problem::HostRam + )); + let outside = buffer( + &device, + start + 32 * page, + page, + resolver(&runs, move |_, length| { + let past = start + RAM_BYTES + 64 * MIB; + Some(std::iter::once(past..past + length).collect()) + }), + gate(&gates, true), + ); + assert!(matches!( + outside, + Err(Error::Invalid(ref invalid)) if invalid.problem == Problem::HostRam + )); + drop((none, two, crossing, used, ram)); + assert!(settles(&dropped)); +} + +#[test] +fn a_chunk_a_command_buffer_holds_outlives_the_use_and_the_keep_alive_goes_after_it() { + let Some(device) = device() else { + return; + }; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + let page = device.shared().host_import.as_ref().unwrap().page; + let live_before = device.work_counts().host_ram_chunks_live; + let (runs, gates): (Arc>, Arc>) = Default::default(); + let buffer = buffer( + &device, + start, + 4 * page, + resolver(&runs, itself), + gate(&gates, true), + ) + .unwrap(); + assert_eq!(device.work_counts().host_ram_chunks_live, live_before + 1); + // A command buffer that fills it, held back by an event it waits for. + let queue = device.new_command_queue().unwrap(); + let event = device.new_shared_event().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + (command_buffer.encode_wait_for_event(EventRef::Shared(&event), 1)).unwrap(); + let mut encoder = command_buffer.blit_command_encoder().unwrap(); + encoder.fill_buffer(&buffer, 0..4 * page, 0x77).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + // The buffer, the use and the RAM let go of while it waits: the chunk stays. + drop((buffer, used, ram)); + std::thread::sleep(Duration::from_millis(50)); + assert!( + !dropped.load(Ordering::SeqCst), + "the keep-alive waits for the chunk" + ); + assert_eq!(device.work_counts().host_ram_chunks_live, live_before + 1); + event.set_signaled_value(1); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + drop(command_buffer); + assert!( + settles(&dropped), + "the keep-alive goes once the chunk is freed" + ); + assert_eq!(device.work_counts().host_ram_chunks_live, live_before); +} + +#[test] +fn a_ram_is_used_once_at_a_time_and_a_new_one_after() { + let Some(device) = device() else { + return; + }; + let (ram, start, dropped) = new_ram(); + let used = device.use_host_ram(&ram).unwrap(); + // The same RAM again, or one over the same ranges, is misuse. + let again = device.use_host_ram(&ram); + assert!(matches!( + again, + Err(Error::Invalid(ref invalid)) if invalid.problem == Problem::HostRam + )); + let at = NonNull::new(start as *mut u8).unwrap(); + // SAFETY: the same mapping, kept by the first RAM's keep-alive while this one lives. + let twin = Arc::new(unsafe { HostRam::new(&[(at, RAM_BYTES)], None) }.unwrap()); + assert!(device.use_host_ram(&twin).is_err(), "ranges that meet"); + // A RAM apart from it is taken. + let (apart, _, apart_dropped) = new_ram(); + let apart_used = device.use_host_ram(&apart).unwrap(); + drop((apart_used, apart)); + assert!(settles(&apart_dropped)); + // Once the first use ended, a new RAM over the same ranges is taken, and imports again. + drop(used); + let new_used = device.use_host_ram(&twin).unwrap(); + let page = device.shared().host_import.as_ref().unwrap().page; + fill_pattern(start..start + page); + let (runs, gates): (Arc>, Arc>) = Default::default(); + let before = device.work_counts(); + let made = buffer( + &device, + start, + page, + resolver(&runs, itself), + gate(&gates, true), + ) + .unwrap(); + let after = device.work_counts(); + assert_eq!( + after.host_ram_chunks_imported - before.host_ram_chunks_imported, + 1 + ); + assert_eq!(gpu_bytes(&device, &made, page), bytes(start..start + page)); + drop((made, new_used, twin, ram)); + assert!(settles(&dropped)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index cbeec393c..4868c0bf5 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -133,6 +133,8 @@ mod host_bytes; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod host_import_counts; mod host_memory; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod host_ram_device; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod host_residency; mod host_settable_event_waits; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 81052def2..8f5e2c100 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -297,6 +297,10 @@ pub(crate) struct Counters { copied_heaps_made: AtomicU64, copied_copy_in_bytes: AtomicU64, copied_merge_back_bytes: AtomicU64, + host_ram_chunks_imported: AtomicU64, + host_ram_chunk_bytes: AtomicU64, + host_ram_chunks_live: AtomicU64, + chunk_bound_buffers_made: AtomicU64, dma_buf_sparse_buffers: AtomicU64, dma_buf_images: AtomicU64, dma_buf_image_fallbacks: AtomicU64, @@ -2024,6 +2028,24 @@ impl Counters { (self.copied_rebind_pages_made).fetch_add(1, Ordering::Relaxed); } + /// The device imported a chunk of `bytes` of a guest RAM it uses (`host_ram.rs`). + pub(crate) fn host_ram_chunk_imported(&self, bytes: u64) { + (self.host_ram_chunks_imported).fetch_add(1, Ordering::Relaxed); + (self.host_ram_chunk_bytes).fetch_add(bytes, Ordering::Relaxed); + (self.host_ram_chunks_live).fetch_add(1, Ordering::Relaxed); + } + + /// The device freed a chunk of a guest RAM (`host_ram.rs`). + pub(crate) fn host_ram_chunk_freed(&self) { + (self.host_ram_chunks_live).fetch_sub(1, Ordering::Relaxed); + } + + /// A no-copy buffer (or heap's own buffer) was bound in a chunk of a guest RAM + /// (`host_ram.rs`). + pub(crate) fn chunk_bound_buffer_made(&self) { + (self.chunk_bound_buffers_made).fetch_add(1, Ordering::Relaxed); + } + /// A commit copied `bytes` the CPU changed into copied host buffers (`copied.rs`). pub(crate) fn copied_copied_in(&self, bytes: u64) { (self.copied_copy_in_bytes).fetch_add(bytes, Ordering::Relaxed); @@ -4318,6 +4340,18 @@ 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 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, + /// Their bytes. + pub host_ram_chunk_bytes: u64, + /// The chunks of guest RAM imported and not yet freed (a gauge): a chunk is freed once the + /// device's use of its RAM ended and nothing holds it. + pub host_ram_chunks_live: u64, + /// The no-copy buffers (and no-copy heaps' own buffers) bound in a chunk of guest RAM, whose + /// pages their caller resolved to one run inside one chunk (`HostMemory::with_runs`): each + /// made with no import of its own, its import gate not asked. + pub chunk_bound_buffers_made: u64, /// The live host imports the device never releases while idle as a heap's own import (a /// no-copy heap's). With the next three and `host_imports_kept_for_fds`, they are every live /// no-copy import the device keeps imported whatever reads it. @@ -5394,6 +5428,10 @@ 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), + 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), + chunk_bound_buffers_made: counters.chunk_bound_buffers_made.load(Ordering::Relaxed), host_imports_lost: counters.host_imports_lost.load(Ordering::Relaxed), host_import_fds_kept: counters.host_import_fds_kept.load(Ordering::Relaxed), host_imports_kept_for_fds: counters.host_imports_kept_for_fds.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 043b10bb4..2df46f870 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -63bcbd724e3bd5ed5c946c4b46a299fd8312abc3f3a1cd9923db71fe53229179 +6b5ba033881a95f0b9eb02174deececa73e080b9df0255253e6a478c577318c5 diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 6e8e0b658..e882b6b2a 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 = 478; /// 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 = 1697; +pub const RUNTIME_VERSION: u32 = 1698; /// 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 254525d32..6510b505c 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2443,6 +2443,7 @@ field metal2vulkan-runtime::WorkCounts.calibration_readings pub calibration_read field metal2vulkan-runtime::WorkCounts.calibrations pub calibrations: u64 field metal2vulkan-runtime::WorkCounts.chroma_device_decodes pub chroma_device_decodes: u64 field metal2vulkan-runtime::WorkCounts.chroma_device_twins pub chroma_device_twins: u64 +field metal2vulkan-runtime::WorkCounts.chunk_bound_buffers_made pub chunk_bound_buffers_made: u64 field metal2vulkan-runtime::WorkCounts.color_group_draws_skipped pub color_group_draws_skipped: u64 field metal2vulkan-runtime::WorkCounts.color_group_passes pub color_group_passes: u64 field metal2vulkan-runtime::WorkCounts.color_group_twins pub color_group_twins: u64 @@ -2613,6 +2614,9 @@ field metal2vulkan-runtime::WorkCounts.host_keep_alives_kept pub host_keep_alive field metal2vulkan-runtime::WorkCounts.host_mappings_queried pub host_mappings_queried: u64 field metal2vulkan-runtime::WorkCounts.host_pointer_import_bytes_made pub host_pointer_import_bytes_made: u64 field metal2vulkan-runtime::WorkCounts.host_pointer_imports_made pub host_pointer_imports_made: u64 +field metal2vulkan-runtime::WorkCounts.host_ram_chunk_bytes pub host_ram_chunk_bytes: u64 +field metal2vulkan-runtime::WorkCounts.host_ram_chunks_imported pub host_ram_chunks_imported: u64 +field metal2vulkan-runtime::WorkCounts.host_ram_chunks_live pub host_ram_chunks_live: u64 field metal2vulkan-runtime::WorkCounts.host_range_lookups pub host_range_lookups: u64 field metal2vulkan-runtime::WorkCounts.host_rebind_imports_covered pub host_rebind_imports_covered: u64 field metal2vulkan-runtime::WorkCounts.host_rebind_imports_made pub host_rebind_imports_made: u64 @@ -7685,6 +7689,7 @@ method metal2vulkan-runtime::Device::system_default pub fn system_default() -> R method metal2vulkan-runtime::Device::system_default_identity_with pub fn system_default_identity_with(options: &DeviceOptions) -> Result method metal2vulkan-runtime::Device::system_default_with pub fn system_default_with(options: &DeviceOptions) -> Result method metal2vulkan-runtime::Device::texture_level_info pub fn texture_level_info(&self, query: &TextureLevelQuery) -> TextureLevelInfo +method metal2vulkan-runtime::Device::use_host_ram pub fn use_host_ram(&self, ram: &Arc) -> Result method metal2vulkan-runtime::Device::vk_buffer_usage pub fn vk_buffer_usage(&self) -> BufferUsageFlags method metal2vulkan-runtime::Device::with_loader_word pub fn with_loader_word(&self, call: impl FnOnce() -> R) -> R method metal2vulkan-runtime::Device::with_registry_id pub fn with_registry_id(registry_id: u64, options: &DeviceOptions) -> Result @@ -7785,6 +7790,9 @@ method metal2vulkan-runtime::HostMemory::pointer pub fn pointer(&self) -> NonNul method metal2vulkan-runtime::HostMemory::with_dirty_pages pub fn with_dirty_pages(self, source: Arc) -> HostMemory where D: DirtyPages + ?Sized + 'static, D::Watch: 'static, method metal2vulkan-runtime::HostMemory::with_dma_buf #[cfg(unix)] pub unsafe fn with_dma_buf(pointer: NonNull, source: DmaBufSource) -> HostMemory method metal2vulkan-runtime::HostMemory::with_import_gate pub fn with_import_gate(self, gate: ImportGate) -> HostMemory +method metal2vulkan-runtime::HostMemory::with_runs pub fn with_runs(self, resolver: RunResolver) -> HostMemory +method metal2vulkan-runtime::HostRam::new pub unsafe fn new(ranges: &[(NonNull, u64)], keep_alive: Option) -> Result +method metal2vulkan-runtime::HostRam::with_dirty_pages pub fn with_dirty_pages(mut self, source: Arc) -> HostRam where D: DirtyPages + ?Sized + 'static, D::Watch: 'static, method metal2vulkan-runtime::IndirectBufferBinding::new pub fn new(address: GpuAddress, attribute_stride: Option) -> IndirectBufferBinding method metal2vulkan-runtime::IndirectCommandBuffer::allocated_size pub fn allocated_size(&self) -> u64 method metal2vulkan-runtime::IndirectCommandBuffer::as_resource pub fn as_resource(&self) -> ResourceRef<'_> @@ -9250,6 +9258,8 @@ struct metal2vulkan-runtime::Heap #[derive(Clone)] pub struct Heap(Arc struct metal2vulkan-runtime::HostMemory pub struct HostMemory +struct metal2vulkan-runtime::HostRam pub struct HostRam +struct metal2vulkan-runtime::HostRamUse #[must_use = "dropping the use lets go of the RAM at once"] pub struct HostRamUse struct metal2vulkan-runtime::ImportRequest #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ImportRequest struct metal2vulkan-runtime::IndirectBufferBinding #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IndirectBufferBinding struct metal2vulkan-runtime::IndirectCommandBuffer #[derive(Clone)] pub struct IndirectCommandBuffer(Arc) @@ -9758,6 +9768,10 @@ trait-impl metal2vulkan-runtime::HostBytes impl fe impl Sync unsafe impl Sync fo trait-impl metal2vulkan-runtime::HostMemory impl fe impl Send unsafe impl Send for HostMemory trait-impl metal2vulkan-runtime::HostMemory impl fe impl Sync unsafe impl Sync for HostMemory trait-impl metal2vulkan-runtime::HostMemory impl std::fmt::Debug impl std::fmt::Debug for HostMemory +trait-impl metal2vulkan-runtime::HostRam impl Drop impl Drop for HostRam +trait-impl metal2vulkan-runtime::HostRam impl std::fmt::Debug impl std::fmt::Debug for HostRam +trait-impl metal2vulkan-runtime::HostRamUse impl Drop impl Drop for HostRamUse +trait-impl metal2vulkan-runtime::HostRamUse impl std::fmt::Debug impl std::fmt::Debug for HostRamUse trait-impl metal2vulkan-runtime::ImportRequest impl fe impl Send unsafe impl Send for ImportRequest trait-impl metal2vulkan-runtime::ImportRequest impl fe impl Sync unsafe impl Sync for ImportRequest trait-impl metal2vulkan-runtime::IndirectCommandBuffer impl Eq impl Eq for IndirectCommandBuffer @@ -9913,6 +9927,7 @@ type metal2vulkan-runtime::ImportGate pub type ImportGate = Arc type metal2vulkan-runtime::KeepAlive pub type KeepAlive = Box type metal2vulkan-runtime::RangeToken pub type RangeToken = Box +type metal2vulkan-runtime::RunResolver pub type RunResolver = Arc Option>> + Send + Sync + 'static> type metal2vulkan-runtime::SharedEventNotification pub type SharedEventNotification = Box type metal2vulkan-runtime::SubmissionCheck pub type SubmissionCheck = Arc) -> Option + Send + Sync> type metal2vulkan::cache::Hash256 pub type Hash256 = [u8; 32] @@ -11599,6 +11614,7 @@ variant metal2vulkan-runtime::Problem::ForeignObject ForeignObject variant metal2vulkan-runtime::Problem::FunctionTable FunctionTable(FunctionTableProblem) variant metal2vulkan-runtime::Problem::HandlerAfterCommit HandlerAfterCommit variant metal2vulkan-runtime::Problem::Heap Heap(HeapProblem) +variant metal2vulkan-runtime::Problem::HostRam HostRam variant metal2vulkan-runtime::Problem::ImageblockSize ImageblockSize { width: u64, height: u64 } variant metal2vulkan-runtime::Problem::IndexOutOfRange IndexOutOfRange { index: u32, limit: u32 } variant metal2vulkan-runtime::Problem::IndirectCommandBuffer IndirectCommandBuffer(IndirectCommandBufferProblem) diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 17886b3ac..feef8d71d 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -331,6 +331,13 @@ driver's. Each is open work. the event's semaphore, which the batch signals before its completion merges the GPU's writes back, so a CPU that waits for the value may read the pages before them, where Metal's writes are in the pages when the value is seen. +- **On MoltenVK a kernel's out-of-bounds write through a buffer reaches other bytes of the + buffer's memory allocation**, where Metal's GPU faults past the pages of the resource: on the + M3 Max (MoltenVK 1.4.2) a dispatch writing three pages through a one-page buffer of the + runtime's own changed 32,720 bytes of the buffer made after it, and through a buffer bound in a + chunk of guest RAM (`Device::use_host_ram`) as many bytes of the chunk's next pages. A no-copy + buffer's own import ends at its last page, so nothing past it changed. On the RTX 5080 laptop + (NVIDIA 615.71.09) and lavapipe the same write left the chunk's pages untouched. - **A shadowed texture over an IOSurface plane's bytes is copied in whole for every command buffer that samples it**, where it is a shadow: one that only samples or reads is an image in place where its class's check passed (`in_place.rs`), so this holds for a plane that renders or diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 93788bc1d..638f9f9be 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -344,6 +344,40 @@ copy, and its textures are shadows of its bytes. `Buffer::rebind_bytes_no_copy` copy of its new pages the same way (`copied_rebind_pages_made`), except over a buffer with a texture in place over it, which the rebind refuses (`NotImplemented(RebindTextures)`). +### Guest RAM imported whole + +A VMM whose device refuses views of guest pages made through dma-bufs (each import of scattered +pages then takes a kernel mapping per page) can give the device the guest's RAM once instead: + +- `unsafe HostRam::new(ranges, keep_alive)` takes the RAM's ranges of host memory (whole host pages, + mapped readable and writable until the keep-alive goes) and `Device::use_host_ram(&ram)` uses it + on a device, until the returned `HostRamUse` is dropped. A device may use several RAMs whose + ranges are apart, and a new one over the same ranges once the earlier use ended; ranges that + meet a used RAM's are misuse (`Invalid`, `Problem::HostRam`). +- `HostMemory::with_runs(resolver)` gives each no-copy object a `RunResolver`: asked once, at the + object's making, on the calling thread with no lock of the runtime's held and before the import + gate, with the object's import window (whole host pages), it answers the host addresses of the + same bytes in the RAM's ranges, as runs of whole pages in the object's byte order, or `None`. + It is asked only on a device that uses a RAM, only where the object would import its pages + itself, never for memory whose GPU writes Metal's private option bit 24 drops. An answer that + does not cover the window in whole pages of one RAM the device uses is refused (`Invalid`, + `Problem::HostRam`). +- One run inside one chunk: the device imports the RAM by host pointer in chunks of 64 MiB, never + across a range's end, each the first time an object over it is made, on that thread, once + (`WorkCounts::host_ram_chunks_imported`, `host_ram_chunk_bytes`, `host_ram_chunks_live`). The + object's `VkBuffer` is made as an import of its own pages would make it and bound in the chunk + at its run (`chunk_bound_buffers_made`): no import of its own, no gate asked, its `contents` + still the pointer, and its size reaching no page past its own, so neither its Metal range, a + robust descriptor range nor a root entry reaches the rest of the chunk. A no-copy heap's own + buffer takes the same path. +- Any other answer (several runs, one run crossing a chunk's end, `None`) takes the paths above: + the gate, then the import or the copy. The runs are kept with the object. +- The chunks are never released while idle. Once the use is dropped, each is freed when nothing + holds it (no buffer bound in it, no command buffer that used one), and the RAM's keep-alive is + dropped after the last. +- `HostRam::with_dirty_pages` takes one `DirtyPages` log for the whole RAM, its offsets host + addresses. + ## 7. Check the integration `spirv-val` checks structural validity, not agreement with Metal: diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 7b8781b61..3e44163c0 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -34,7 +34,7 @@ Columns: | Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 | | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | -| What a call did wrong | 63 | 63 | 0 | 0 | 0 | 0 | 0 | +| What a call did wrong | 64 | 64 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 164 | 149 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -48,7 +48,7 @@ Columns: | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | -| What a call did wrong | 20 | 3 | 5 | 0 | 10 | 8 | 17 | 0 | +| What a call did wrong | 20 | 3 | 5 | 0 | 11 | 8 | 17 | 0 | | What a call did wrong, in detail | 57 | 27 | 23 | 0 | 31 | 26 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -158,7 +158,7 @@ Columns: | `TextureView` | A texture view Vulkan cannot make exactly on this image | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 9: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`, `crates/metal2vulkan-runtime/src/texture.rs (view)` (+6) | `app`: a texture view Vulkan cannot make exactly | | `TextureSwizzle` | A texture swizzle whose Metal behavior is not measured | devices short of a Vulkan feature the site names; every device (not implemented) | `ours` | 7: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`, `crates/metal2vulkan-runtime/src/texture.rs (may_view)` (+5) | `app`: texture swizzles whose Metal behaviour is unmeasured | | `MipmapGeneration` | `generateMipmapsForTexture:` that cannot run on the device | devices without a format's usage; every device (not implemented) | `ours` | 6: `crates/metal2vulkan-runtime/src/blit_texture.rs (mipmaps)`, `crates/metal2vulkan-runtime/src/mipmap_pick.rs (pick_mipmaps)` (+2) | `app`: generateMipmapsForTexture: of a format or chain neither the device's blits nor the compute filter can run | -| `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 5: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`, `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)` (+1) | `system`: newBufferWithBytesNoCopy: where the device cannot import the memory | +| `HostMemory` | A buffer over the caller's host memory without a copy (`newBufferWithBytesNoCopy:`) | devices without VkExtension::ExtExternalMemoryHost; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 6: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`, `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)` (+2) | `system`: newBufferWithBytesNoCopy: where the device cannot import the memory | | `GpuTimes` | A command buffer's GPU times (`GPUStartTime`, `GPUEndTime`) on a device whose queue family writes no timestamps (`timestampValidBits` 0) | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (gpu_times)` | `rare`: GPU times on a queue without timestamps | | `CountingVisibility` | A `Counting` visibility result (`MTLVisibilityResultModeCounting`) on a device without `occlusionQueryPrecise` | devices without VkFeature::OcclusionQueryPrecise | `device` | 1: `crates/metal2vulkan-runtime/src/visibility.rs (check_mode)` | `rare`: counting occlusion queries on a device without precise queries | | `ViewFormatReinterpretation` | A texture view whose format has other components, or components of other widths, than its texture's (`RGBA8Unorm` as `R32Uint`), on a device whose... | every device (no Vulkan mechanism) | `device` | 1: `crates/metal2vulkan-runtime/src/view_plan.rs (reinterpretation_refused)` | `app`: a view of another component layout on a portability subset (MoltenVK) | @@ -326,6 +326,7 @@ Columns: | `ScheduledSignalAfterCompletion` | A scheduled signal encoded once the command buffer completed, or failed (status `Error`) (`CommandBuffer::encode_signal_event_scheduled`) | every device (a public call's own check of its arguments) | `metal-measured`: an M3 Max, macOS 27.0.1: a segmentation fault in 10 of 15 runs, as the consumer measured | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (encode_signal_event_scheduled)` | `-` | | `ForeignObject` | An object made by another device | every device (a public call's own check of its arguments) | `unknown`: Metal's answer for an object another device made is unmeasured | 30: `crates/metal2vulkan-runtime/src/argument_encoder.rs (check_device)`, `crates/metal2vulkan-runtime/src/argument_encoder.rs (target)` (+28) | `-` | | `DmaBuf` | Dma-bufs a `DmaBufSource` returned (a runtime extension | every device (a public call's own check of its arguments) | `ours`: a runtime extension's own contract: Metal imports no dma-buf | 1: `crates/metal2vulkan-runtime/src/dma_buf.rs (import_from_source)` | `-` | +| `HostRam` | Guest RAM, or a run resolver's answer, that breaks its runtime extension's contract (`HostRam::new`, `Device::use_host_ram`,... | every device (a public call's own check of its arguments) | `ours`: a runtime extension's own contract: Metal imports no guest RAM | 3: `crates/metal2vulkan-runtime/src/host_ram.rs (new)`, `crates/metal2vulkan-runtime/src/host_ram.rs (route_runs)` (+1) | `-` | | `WrappedImage` | An image the caller made that cannot be wrapped as a texture of the descriptor (`new_texture_with_vk_image`) | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal wraps no Vulkan image | 1: `crates/metal2vulkan-runtime/src/texture/wrapped.rs (new_texture_with_vk_image)` | `-` | | `NotShareable` | A handle of a texture that is not shareable, for which Metal answers nil, an [`Error::Nil`] | every device (a public call's own check of its arguments) | `unknown`: Metal's nil for a texture that is not shareable is unmeasured | 1: `crates/metal2vulkan-runtime/src/texture/shared.rs (new_shared_texture_handle)` | `-` | | `Semaphore` | A semaphore that cannot be one of the caller's binary semaphores | every device (a public call's own check of its arguments) | `ours`: a runtime extension: Metal has no binary semaphores | 1: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (binary_command)` | `-` | @@ -659,7 +660,7 @@ Each refusal's sites, with the function that builds it. - `feature::TextureView`: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs (view)`; `crates/metal2vulkan-runtime/src/texture/decoded_twin.rs (make_second_twin)`; `crates/metal2vulkan-runtime/src/texture/view_shadow.rs (apart_refusal)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (converted_view)`; `crates/metal2vulkan-runtime/src/texture/ycbcr_image.rs (luma_view)`; `crates/metal2vulkan-runtime/src/view_plan.rs (check_format)`; `crates/metal2vulkan-runtime/src/view_plan.rs (check_view, 2 sites)` - `feature::TextureSwizzle`: `crates/metal2vulkan-runtime/src/binding_view.rs (binding_view)`; `crates/metal2vulkan-runtime/src/texture.rs (may_view)`; `crates/metal2vulkan/src/bind/plan/resources.rs (plain_texture)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read_as)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_write)`; `crates/metal2vulkan/src/lower/texture/slice.rs (select)` - `feature::MipmapGeneration`: `crates/metal2vulkan-runtime/src/blit_texture.rs (mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_pick.rs (pick_mipmaps)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs (blit_lack, 2 sites)`; `crates/metal2vulkan-runtime/src/mipmap_plan.rs (plan_mipmaps, 2 sites)` -- `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`; `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs (refuse_unwritable)` +- `feature::HostMemory`: `crates/metal2vulkan-runtime/src/host_memory.rs (new, 3 sites)`; `crates/metal2vulkan-runtime/src/host_memory.rs (not_importable)`; `crates/metal2vulkan-runtime/src/host_memory.rs (refuse_unwritable)`; `crates/metal2vulkan-runtime/src/host_ram.rs (new)` - `feature::GpuTimes`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (gpu_times)` - `feature::CountingVisibility`: `crates/metal2vulkan-runtime/src/visibility.rs (check_mode)` - `feature::ViewFormatReinterpretation`: `crates/metal2vulkan-runtime/src/view_plan.rs (reinterpretation_refused)` @@ -792,6 +793,7 @@ Each refusal's sites, with the function that builds it. - `invalid::ScheduledSignalAfterCompletion`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (encode_signal_event_scheduled)` - `invalid::ForeignObject`: `crates/metal2vulkan-runtime/src/argument_encoder.rs (check_device)`; `crates/metal2vulkan-runtime/src/argument_encoder.rs (target)`; `crates/metal2vulkan-runtime/src/binary_archive/mod.rs (check)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (new_buffer_with_descriptor)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (shared_place)`; `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (encode_signal_event_scheduled)`; `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (event_command)`; `crates/metal2vulkan-runtime/src/dynamic_library.rs (new_dynamic_library)`; `crates/metal2vulkan-runtime/src/encoder.rs (check_device)`; `crates/metal2vulkan-runtime/src/function_table.rs (function_handle)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (check_patches)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (draw_indexed_primitives)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_buffer)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_depth_stencil_state)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (set_render_pipeline_state)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (added)`; `crates/metal2vulkan-runtime/src/pipeline/additions.rs (ignored)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs (new_compute_pipeline_state_with_function)`; `crates/metal2vulkan-runtime/src/pipeline/mod.rs (new_compute_pipeline_state_with_function_and_reflection)`; `crates/metal2vulkan-runtime/src/rate_map.rs (copy_parameter_data_to_buffer)`; `crates/metal2vulkan-runtime/src/rate_mapped_pass.rs (check_descriptor)`; `crates/metal2vulkan-runtime/src/render_pass.rs (layout)`; `crates/metal2vulkan-runtime/src/render_pass.rs (target)`; `crates/metal2vulkan-runtime/src/resolve.rs (destination)`; `crates/metal2vulkan-runtime/src/sparse/encoder.rs (sparse)`; `crates/metal2vulkan-runtime/src/sparse/encoder.rs (update_fence)`; `crates/metal2vulkan-runtime/src/sparse/encoder.rs (update_texture_mapping_indirect)`; `crates/metal2vulkan-runtime/src/sparse/encoder.rs (wait_for_fence)`; `crates/metal2vulkan-runtime/src/texture/shared.rs (new_shared_texture_with_handle)` - `invalid::DmaBuf`: `crates/metal2vulkan-runtime/src/dma_buf.rs (import_from_source)` +- `invalid::HostRam`: `crates/metal2vulkan-runtime/src/host_ram.rs (new)`; `crates/metal2vulkan-runtime/src/host_ram.rs (route_runs)`; `crates/metal2vulkan-runtime/src/host_ram.rs (use_host_ram)` - `invalid::WrappedImage`: `crates/metal2vulkan-runtime/src/texture/wrapped.rs (new_texture_with_vk_image)` - `invalid::NotShareable`: `crates/metal2vulkan-runtime/src/texture/shared.rs (new_shared_texture_handle)` - `invalid::Semaphore`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (binary_command)`