From 9b60da4bee03514df7f4ef5a1aefa8f9ecd28bca Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 3 Nov 2026 09:38:57 -0800 Subject: [PATCH] host_ram: import a used RAM's chunks ahead, on a thread of the device's What: Device::use_host_ram now starts a thread ("m2v-host-ram", through exit_guard::spawn) that imports the RAM's 64 MiB chunks one after another, ahead of the objects over them. It goes on from the chunk past the one an object last took, then from the RAM's start. It skips a chunk whose lock is held (an object is importing it) and one it failed to import (left to the first object over it, as before). It stops once every chunk is imported, the use ends, the device goes or is lost, or the process exits (each import inside an exit_guard section). It holds the device and the RAM weakly between chunks. An object over a chunk the thread has not reached imports it on its own thread, as before. One over the chunk being imported waits for that one import. New counter: WorkCounts::host_ram_chunks_imported_ahead. Why: a consumer makes 2 MiB heaps over consecutive fresh guest RAM (memfd). Each 32nd heap was the first object over a chunk. Its making waited for the chunk's import, which faults in and pins 64 MiB of fresh pages. That took ~7.5 ms exclusive on the RTX 5080 laptop, and 0.4-4.0 s in a shared boot with compaction (compact_stall +10,889). Keeping chunks imported for the RAM's life already held at the start of this branch (a chunk stays in its slot while the use lasts). Measured here: a heap made again after every heap was dropped imported 0 chunks. The trade-off: the whole RAM is resident and pinned from soon after use_host_ram, not only the chunks objects touch. 16 GiB of fresh THP memfd RAM took 3.47 s on the thread, with compact_stall 1152, compact_fail 56, pgmigrate_success 935291 and allocstall_normal 54, all off the making threads. No kernel, boot or module parameter is needed. Recorded in docs/HOWTO.md ("One run inside one chunk"). Vulkan rules relied on (checked against the 1.4.366 spec): the import itself is Device::import_chunk, unchanged, under VUID-VkImportMemoryHostPointerInfoEXT-pHostPointer-01749 "pHostPointer must be a pointer aligned to an integer multiple of VkPhysicalDeviceExternalMemoryHostPropertiesEXT::minImportedHostPointerAlignment", VUID-VkImportMemoryHostPointerInfoEXT-handleType-01750 "pHostPointer must be a pointer to allocationSize number of bytes of host memory", VUID-VkMemoryAllocateInfo-allocationSize-01745 "allocationSize must be an integer multiple of ...minImportedHostPointerAlignment", and VUID-VkMemoryAllocateInfo-memoryTypeIndex-01744 "the value of memoryTypeIndex must be one of those returned by vkGetMemoryHostPointerPropertiesEXT". The spec's "Externally Synchronized Parameters" list names no parameter of vkAllocateMemory, so the thread's imports may run while other threads use the device. Each chunk's import is made once, under the chunk's own lock. A chunk is freed only on the existing path (vkFreeMemory's memory parameter is externally synchronized: one owner frees it). Verified on the RTX 5080 laptop (NVIDIA 615.71.09), release, --cfg m2v_gpu: - All 21 host_ram tests pass, among them the new device test chunks_are_imported_ahead_so_no_making_waits_for_one. It covers 4 chunks of fresh memfd RAM under MADV_HUGEPAGE, imported ahead in 32.5 ms. Then 40 heaps of 2 MiB over consecutive runs: 0 chunk imports, 0 host-pointer imports and 40 chunk-bound buffers during the makings, the slowest making 78 us. Heap 33 passes a CPU write -> GPU read -> GPU write -> CPU read round trip. A heap made again after all were dropped imports nothing. The other device tests hold the thread back (Device::hold_host_ram_imports, test-only), so they still see each chunk imported by its first object. - Negative control: with the spawn disabled, the new test fails ("the device's thread imported 0 of 4 chunks"). - On the M3 Max (MoltenVK, macOS 27.0.1), release, --cfg m2v_gpu: all 19 host_ram tests pass (the two dma-buf tests are Linux-only). In the new test, 4 chunks were imported ahead in 7.2 ms; across the 40 makings the slowest took 35 us. - Unit test the_devices_thread_goes_on_past_the_chunk_an_object_took_then_from_the_start covers the order, the skip of a held or failed chunk, and the end. Heap makings, 128 heaps of 2 MiB over fresh THP memfd RAM (wall time per new_heap_with_bytes_no_copy): case p50 p90 max makings > 5 ms before, 1 GiB RAM 0.001 ms 0.002 ms 7.39 ms heaps 0, 32, 64, 96 after, made at once 0.001 ms 0.003 ms 7.54 ms heaps 0, 32, 64, 96 after, made once the thread is done (122 ms) 0.001 ms 0.002 ms 0.05 ms none before, 16 GiB RAM 0.001 ms 0.002 ms 7.54 ms heaps 0, 32, 64, 96 after, 16 GiB, made once done (3468 ms) 0.001 ms 0.002 ms 0.03 ms none Made at once, the makings outran the thread: 5 chunks were imported during them, 4 of them by the thread. Once the thread is done, no making waits for an import. (cherry picked from commit 7baa553a75515909f2ce9701c1e1bea4c408845a) (cherry picked from commit 97a69f70ab96d37dcdf269192a6935f8c4126749) --- crates/metal2vulkan-runtime/src/host_ram.rs | 206 ++++++++++++++++-- .../src/tests/host_ram_device.rs | 183 +++++++++++++++- .../metal2vulkan-runtime/src/work_counts.rs | 16 +- crates/metal2vulkan/tests/api_signatures.tsv | 1 + docs/HOWTO.md | 10 +- 5 files changed, 388 insertions(+), 28 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs index f71a613ea..26e6f3748 100644 --- a/crates/metal2vulkan-runtime/src/host_ram.rs +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -6,11 +6,19 @@ //! - **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 +//! end, each 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. +//! - **Ahead of the objects.** From [`Device::use_host_ram`] on, a thread of the device's imports +//! the chunks one after another ([`import_ahead`]): first those past the chunk an object last +//! took, then those from the RAM's start, until every chunk is imported or the use ends. An +//! object over a chunk that thread has not reached imports it on the thread making the object, +//! and one over the chunk the thread is importing waits for that import alone; once the thread +//! is done, no making waits for an import. Each import faults in and pins its pages, which is +//! what an object over fresh RAM waited for at every chunk's first object (a 2 MiB heap in 32 +//! over consecutive fresh RAM): so the whole RAM is resident and pinned from soon after the +//! use begins. Counted: `WorkCounts::host_ram_chunks_imported_ahead`. //! - **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, @@ -34,12 +42,14 @@ use super::host_memory::{ use super::memory::{ImportFailure, Mapped, MemoryClass, Placement}; use super::program_objects::ProgramObject; use super::Device; +use crate::device::WeakDevice; use crate::release; use ash::vk; use metal2vulkan::error::{Feature, Unsupported}; use std::ops::Range; use std::ptr::NonNull; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, TryLockError, Weak}; /// The bytes of a chunk of the RAM a device imports at once; the last chunk of a range may be /// fewer. @@ -186,20 +196,33 @@ impl Drop for HostRamUse { } } -/// A RAM as one device uses it: the RAM, and its chunks, each imported once, the first time an -/// object over it is made. +/// A RAM as one device uses it: the RAM, and its chunks, each imported once, by the device's +/// thread ahead of the objects over it ([`import_ahead`]) or by the first object over it. pub(crate) struct RamOnDevice { ram: Arc, /// Its chunks, by start ([`chunk_spans`]). slots: Vec, + /// The slot after the one an object last took: where the device's thread goes on from + /// ([`RamOnDevice::next_ahead`]). + cursor: AtomicUsize, } /// 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. +/// its own, so the chunk is imported once and objects over other chunks wait for none of it. struct ChunkSlot { span: Range, chunk: Mutex>>, + /// The device's thread failed to import the chunk: it does not try again, and the first + /// object over it does, as it would have. + tried: AtomicBool, +} + +/// Who imports a chunk: the first object over it, on the thread making it, or the device's +/// thread, ahead of every object over it ([`import_ahead`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum By { + Object, + Ahead, } /// The chunks of `ranges` (host addresses, by start): [`CHUNK_BYTES`] from each range's start, @@ -237,11 +260,13 @@ impl RamOnDevice { .map(|span| ChunkSlot { span, chunk: Mutex::new(None), + tried: AtomicBool::new(false), }) .collect(); RamOnDevice { ram: Arc::clone(ram), slots, + cursor: AtomicUsize::new(0), } } @@ -250,27 +275,88 @@ impl RamOnDevice { 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. + /// The import of chunk `slot` on `device`, for `by`: kept, or made now, once, under the + /// chunk's own lock (`Device::import_chunk`), so an object over the chunk the device's thread + /// is importing waits for that import. A failed import is not kept: the next object over the + /// chunk tries again. An object's call moves the device's thread on to the chunks past this + /// one ([`RamOnDevice::next_ahead`]). fn chunk( &self, device: &Device, importer: &Importer, slot: usize, + by: By, ) -> Result, Error> { - let slot = &self.slots[slot]; - let mut held = lock(&slot.chunk); + if by == By::Object { + self.cursor.store(slot + 1, Ordering::Relaxed); + } + let span = &self.slots[slot]; + let mut held = lock(&span.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()) }?); + Arc::new(unsafe { device.import_chunk(importer, &self.ram, span.span.clone()) }?); + if by == By::Ahead { + device.shared().counts.host_ram_chunk_imported_ahead(); + } *held = Some(Arc::clone(&chunk)); Ok(chunk) } + + /// The chunk the device's thread imports next: the first, from the slot after the one an + /// object last took and then from the RAM's start, that is neither imported nor failed by + /// that thread, nor being imported now (its lock held: by an object, which imports it + /// itself); `None` once there is none. + fn next_ahead(&self) -> Option { + let count = self.slots.len(); + let from = self.cursor.load(Ordering::Relaxed).min(count); + (from..count).chain(0..from).find(|&index| { + let slot = &self.slots[index]; + if slot.tried.load(Ordering::Relaxed) { + return false; + } + match slot.chunk.try_lock() { + Ok(held) => held.is_none(), + Err(TryLockError::Poisoned(held)) => held.into_inner().is_none(), + Err(TryLockError::WouldBlock) => false, + } + }) + } +} + +/// The device's thread that imports a RAM's chunks ahead of the objects over them +/// ([`Device::use_host_ram`]): one chunk at a time ([`RamOnDevice::next_ahead`]), each under its +/// own lock and inside a section of the exit guard, until every chunk is imported or failed, the +/// use ended, the device went or was lost, or the process exits. It holds the device and the RAM +/// weakly between chunks, so neither outlives its last holder for it by more than one import. A +/// chunk it fails to import (out of memory, pages the driver or the runtime refuses) is left to +/// the first object over it, which meets the same answer on its own thread, as without this thread. +fn import_ahead(device: WeakDevice, ram: Weak) { + loop { + let (Some(device), Some(ram)) = (device.upgrade(), ram.upgrade()) else { + return; + }; + let shared = device.shared(); + let Ok(importer) = shared.host_import.as_ref() else { + return; + }; + if device.is_lost() || !shared.host_ram.uses(&ram) { + return; + } + let Some(slot) = ram.next_ahead() else { + return; + }; + let Some(busy) = exit_guard::enter() else { + return; + }; + if ram.chunk(&device, importer, slot, By::Ahead).is_err() { + ram.slots[slot].tried.store(true, Ordering::Relaxed); + } + drop(busy); + } } /// A device's import of one chunk of a RAM (`VK_EXT_external_memory_host`): the memory, and a @@ -426,6 +512,10 @@ fn place_runs( #[derive(Default)] pub(crate) struct RamSource { rams: Mutex>>, + /// The tests' hold on the device's thread ([`Device::hold_host_ram_imports`]): a use begun + /// while it is set starts none, so its chunks are imported by the objects over them alone. + #[cfg(test)] + held: AtomicBool, } impl RamSource { @@ -451,18 +541,38 @@ impl RamSource { fn used(&self) -> Vec> { lock(&self.rams).clone() } + + /// Whether the device still uses `ram`: its use has not ended. + fn uses(&self, ram: &Arc) -> bool { + lock(&self.rams).iter().any(|used| Arc::ptr_eq(used, ram)) + } +} + +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +impl Device { + /// Start no thread importing a RAM's chunks ahead ([`import_ahead`]) for the uses begun from + /// now on: the tests' way to see each chunk imported by the first object over it, as one the + /// thread has not reached is. + pub(crate) fn hold_host_ram_imports(&self) { + self.shared().host_ram.held.store(true, Ordering::Relaxed); + } } 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). + /// lies in, 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 device imports the RAM's chunks ahead, on a + /// thread of its own started here, one after another: an object over a chunk that thread has + /// not reached imports it as it is made, one over the chunk the thread is importing waits for + /// that import, and once the thread is done no making waits for one + /// (`WorkCounts::host_ram_chunks_imported_ahead`). So the whole RAM's pages are faulted in + /// and pinned from soon after this call. A system that cannot start the thread leaves every + /// chunk to the first object over it. 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`, @@ -477,6 +587,16 @@ impl Device { return Err(Error::Unsupported(unsupported.clone())); } let used = (shared.host_ram.add(ram)).ok_or_else(|| invalid(CALL, Problem::HostRam))?; + #[cfg(test)] + let held = shared.host_ram.held.load(Ordering::Relaxed); + #[cfg(not(test))] + let held = false; + if !held { + let (device, ram) = (self.downgrade(), Arc::downgrade(&used)); + let builder = std::thread::Builder::new().name("m2v-host-ram".to_owned()); + // A thread the system cannot start leaves every chunk to the first object over it. + let _ = exit_guard::spawn(builder, move || import_ahead(device, ram)); + } Ok(HostRamUse { device: self.clone(), ram: used, @@ -544,7 +664,7 @@ impl Device { let Routed::InChunk { ram, slot, start } = routed else { return None; }; - let chunk = ram.chunk(self, importer, *slot).ok()?; + let chunk = ram.chunk(self, importer, *slot, By::Object).ok()?; let shared = self.shared(); let raw_device = shared.vk(); let buffer = self.host_buffer(window, length).ok()?; @@ -816,6 +936,50 @@ mod tests { ); } + #[test] + fn the_devices_thread_goes_on_past_the_chunk_an_object_took_then_from_the_start() { + // Three chunks of address space, mapped and never touched (no device imports them). + let length = 2 * CHUNK_BYTES + MIB; + // SAFETY: a fresh anonymous mapping that reserves no memory until touched. + let start = unsafe { + libc::mmap( + std::ptr::null_mut(), + length as usize, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANON | libc::MAP_NORESERVE, + -1, + 0, + ) + }; + assert_ne!(start, libc::MAP_FAILED); + let at = NonNull::new(start.cast::()).unwrap(); + // SAFETY: the mapping is readable and writable until the end of the test, and nothing + // imports it. + let ram = Arc::new(unsafe { HostRam::new(&[(at, length)], None) }.unwrap()); + let on = RamOnDevice::new(&ram); + assert_eq!(on.slots.len(), 3); + assert_eq!(on.next_ahead(), Some(0), "from the start"); + // An object took chunk 1: the thread goes on with chunk 2, then wraps to chunk 0. + on.cursor.store(2, Ordering::Relaxed); + assert_eq!(on.next_ahead(), Some(2)); + on.slots[2].tried.store(true, Ordering::Relaxed); + assert_eq!( + on.next_ahead(), + Some(0), + "a chunk it failed is not tried again" + ); + // A chunk whose lock is held is being imported by an object: the thread passes it. + let held = lock(&on.slots[0].chunk); + assert_eq!(on.next_ahead(), Some(1)); + drop(held); + on.slots[0].tried.store(true, Ordering::Relaxed); + on.slots[1].tried.store(true, Ordering::Relaxed); + assert_eq!(on.next_ahead(), None, "every chunk done"); + drop((on, ram)); + // SAFETY: the test's mapping, which nothing uses any more. + unsafe { libc::munmap(start, length as usize) }; + } + #[test] fn answers_that_break_the_contract_are_refused() { let ranges = one(0..150 * MIB); diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs index 995498390..25e40f306 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_device.rs @@ -26,15 +26,22 @@ //! 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. +//! - **Ahead of the objects.** The device's thread imports every chunk of fresh RAM (a `memfd` +//! advised for huge pages, as QEMU's RAM is) once the use begins, so the consumer's 2 MiB heaps +//! over consecutive runs, past a chunk's end, import nothing as they are made; a heap's bytes +//! go from the CPU to the GPU and back; every heap gone, one made again imports nothing. +//! +//! Every other test holds the device's thread back (`Device::hold_host_ram_imports`), so that +//! each chunk is imported by the first object over it, as one the thread has not reached is. //! //! 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, HostBacking, - HostMemory, HostRam, ImportGate, ImportRequest, KeepAlive, Problem, ResourceOptions, - RunResolver, Size, + Buffer, CommandBufferStatus, Device, DeviceKind, DeviceOptions, Error, EventRef, + HeapDescriptor, HeapType, HostBacking, HostMemory, HostRam, ImportGate, ImportRequest, + KeepAlive, Problem, ResourceOptions, RunResolver, Size, }; use std::ops::Range; use std::ptr::NonNull; @@ -110,8 +117,16 @@ fn bytes(range: Range) -> Vec { 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. +/// A device of the cfg's kind whose uses of a RAM start no thread importing its chunks ahead +/// (`Device::hold_host_ram_imports`); `None` where it imports no host memory. fn device() -> Option { + let device = ahead_device()?; + device.hold_host_ram_imports(); + Some(device) +} + +/// A device of the cfg's kind, as the product makes it; `None` where it imports no host memory. +fn ahead_device() -> Option { let options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { true => vec![DeviceKind::Cpu], @@ -214,6 +229,166 @@ fn settles(flag: &AtomicBool) -> bool { true } +/// Fresh RAM of `length` bytes, never touched: a `memfd` mapped shared and advised for huge pages, +/// as QEMU's `memory-backend-memfd,share=on` RAM is (anonymous shared memory off Linux), unmapped +/// by the keep-alive it is given to; its first byte, and whether its keep-alive was dropped. +fn fresh_ram(length: u64) -> (Arc, u64, Arc) { + #[cfg(target_os = "linux")] + let (flags, fd) = { + // SAFETY: a name and flags the call takes. + let fd = unsafe { libc::memfd_create(c"m2v-fresh-ram".as_ptr(), libc::MFD_CLOEXEC) }; + assert!(fd >= 0); + // SAFETY: the descriptor was just made, and is closed below. + assert_eq!(unsafe { libc::ftruncate(fd, length as libc::off_t) }, 0); + (libc::MAP_SHARED, fd) + }; + #[cfg(not(target_os = "linux"))] + let (flags, fd) = (libc::MAP_SHARED | libc::MAP_ANON, -1); + // SAFETY: a fresh mapping of the file's first `length` bytes (or of anonymous memory). + let start = unsafe { + libc::mmap( + std::ptr::null_mut(), + length as usize, + libc::PROT_READ | libc::PROT_WRITE, + flags, + fd, + 0, + ) + }; + assert_ne!(start, libc::MAP_FAILED); + if fd >= 0 { + // SAFETY: the test's descriptor; the mapping keeps the file. + unsafe { libc::close(fd) }; + } + #[cfg(target_os = "linux")] + // SAFETY: advice on the test's own mapping; a kernel without huge pages refuses it, harmlessly. + unsafe { + libc::madvise(start, length as usize, libc::MADV_HUGEPAGE); + } + let start = start as u64; + let dropped = Arc::new(AtomicBool::new(false)); + let keep: KeepAlive = Box::new(Mapping { + start, + length, + 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, length)], Some(keep)) }.unwrap(); + (Arc::new(ram), start, dropped) +} + +#[test] +fn chunks_are_imported_ahead_so_no_making_waits_for_one() { + let Some(device) = ahead_device() else { + return; + }; + const CHUNKS: u64 = 4; + let (ram, start, dropped) = fresh_ram(CHUNKS * 64 * MIB); + let before = device.work_counts(); + let began = Instant::now(); + let used = device.use_host_ram(&ram).unwrap(); + // The device's thread imports every chunk, none of them asked for by an object. + let ahead = loop { + let now = device.work_counts(); + if now.host_ram_chunks_imported_ahead - before.host_ram_chunks_imported_ahead == CHUNKS { + break now; + } + assert!( + began.elapsed() < WAIT, + "the device's thread imported {} of {CHUNKS} chunks", + now.host_ram_chunks_imported_ahead - before.host_ram_chunks_imported_ahead + ); + std::thread::sleep(Duration::from_millis(2)); + }; + let imported_in = began.elapsed(); + assert_eq!( + ahead.host_ram_chunks_imported - before.host_ram_chunks_imported, + CHUNKS + ); + assert_eq!( + ahead.host_ram_chunks_live - before.host_ram_chunks_live, + CHUNKS + ); + // The consumer's heaps: 2 MiB each over consecutive runs from the RAM's start, past the + // first chunk's end (heap 32 starts the second). + const HEAP: u64 = 2 * MIB; + const HEAPS: u64 = 40; + let (runs, gates): (Arc>, Arc>) = Default::default(); + let heap_over = |at: u64| { + // 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(resolver(&runs, itself)) + .with_import_gate(gate(&gates, true)); + let descriptor = HeapDescriptor::new(HeapType::Placement, HEAP, ResourceOptions::default()); + // SAFETY: as above. + unsafe { device.new_heap_with_bytes_no_copy(memory, &descriptor, None, None) }.unwrap() + }; + let mut slowest = Duration::ZERO; + let heaps: Vec<_> = (0..HEAPS) + .map(|index| { + let making = Instant::now(); + let heap = heap_over(start + index * HEAP); + slowest = slowest.max(making.elapsed()); + heap + }) + .collect(); + let made = device.work_counts(); + assert_eq!( + made.host_ram_chunks_imported, ahead.host_ram_chunks_imported, + "no making imported a chunk" + ); + assert_eq!( + made.chunk_bound_buffers_made - ahead.chunk_bound_buffers_made, + HEAPS + ); + assert_eq!( + made.host_pointer_imports_made - ahead.host_pointer_imports_made, + 0 + ); + assert!(gates.lock().unwrap().is_empty(), "the gate was not asked"); + // A heap in the second chunk: the CPU's bytes reach the GPU, and the GPU's fill the CPU. + let page = device.shared().host_import.as_ref().unwrap().page; + let at = start + 33 * HEAP; + fill_pattern(at..at + 4 * page); + let placed = heaps[33] + .new_buffer_at_offset(4 * page, ResourceOptions::default(), 0) + .unwrap(); + assert_eq!( + gpu_bytes(&device, &placed, 4 * page), + bytes(at..at + 4 * page) + ); + blit(&device, |encoder| { + encoder.fill_buffer(&placed, page..2 * page, 0xA5).unwrap(); + }); + let now = bytes(at..at + 4 * page); + let pattern_of = |range: Range| range.map(pattern).collect::>(); + assert_eq!(now[..page as usize], pattern_of(at..at + page)[..]); + assert!(now[page as usize..2 * page as usize] + .iter() + .all(|&byte| byte == 0xA5)); + assert_eq!( + now[2 * page as usize..], + pattern_of(at + 2 * page..at + 4 * page)[..] + ); + // A chunk is not imported twice: every heap gone, one made again imports nothing. + drop((placed, heaps)); + let again = heap_over(start); + assert_eq!( + device.work_counts().host_ram_chunks_imported, + made.host_ram_chunks_imported + ); + eprintln!( + "HOST-RAM: {CHUNKS} chunks of fresh RAM imported ahead in {imported_in:?}; {HEAPS} heap \ + makings, the slowest {slowest:?}" + ); + drop((again, used, ram)); + assert!( + settles(&dropped), + "the keep-alive goes after the last chunk" + ); +} + #[test] fn one_run_inside_a_chunk_is_bound_there_with_no_import_of_its_own() { let Some(device) = device() else { diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index dfe1094b9..024cde64a 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -335,6 +335,7 @@ pub(crate) struct Counters { copied_merges_skipped: AtomicU64, copied_dropped_bytes: AtomicU64, host_ram_chunks_imported: AtomicU64, + host_ram_chunks_imported_ahead: AtomicU64, host_ram_chunk_bytes: AtomicU64, host_ram_chunks_live: AtomicU64, chunk_bound_buffers_made: AtomicU64, @@ -2326,6 +2327,12 @@ impl Counters { (self.host_ram_chunks_live).fetch_add(1, Ordering::Relaxed); } + /// The device's thread imported a chunk of a guest RAM ahead of every object over it + /// (`host_ram.rs`), besides counting it as [`Counters::host_ram_chunk_imported`] does. + pub(crate) fn host_ram_chunk_imported_ahead(&self) { + (self.host_ram_chunks_imported_ahead).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); @@ -4903,8 +4910,12 @@ pub struct WorkCounts { /// place, never written to the pages, as Metal drops the GPU's writes to read-only memory. pub copied_dropped_bytes: u64, /// The chunks of guest RAM the device imported (`Device::use_host_ram`): 64 MiB of a RAM's - /// range each (its last fewer), imported the first time a no-copy object over it was made. + /// range each (its last fewer), each once, by the device's own thread ahead of the objects + /// over it or by the first object made over it before that thread reached it. pub host_ram_chunks_imported: u64, + /// Of `host_ram_chunks_imported`, those the device's own thread imported ahead of every + /// object over them, so that no making waited for their import. + pub host_ram_chunks_imported_ahead: 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 @@ -6068,6 +6079,9 @@ impl Device { copied_merges_skipped: counters.copied_merges_skipped.load(Ordering::Relaxed), copied_dropped_bytes: counters.copied_dropped_bytes.load(Ordering::Relaxed), host_ram_chunks_imported: counters.host_ram_chunks_imported.load(Ordering::Relaxed), + host_ram_chunks_imported_ahead: counters + .host_ram_chunks_imported_ahead + .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), diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 545e66879..2e8e61269 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2709,6 +2709,7 @@ field metal2vulkan-runtime::WorkCounts.host_pointer_import_bytes_made pub host_p 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_imported_ahead pub host_ram_chunks_imported_ahead: 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 diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 869c61446..88445b26c 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -443,8 +443,14 @@ pages then takes a kernel mapping per page) can give the device the guest's RAM 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 + across a range's end, each once (`WorkCounts::host_ram_chunks_imported`, `host_ram_chunk_bytes`, + `host_ram_chunks_live`). From `use_host_ram` on, a thread of the device's imports them one after + another, ahead of the objects over them (`host_ram_chunks_imported_ahead`): an object over a + chunk it has not reached imports that chunk as it is made, on its own thread, one over the chunk + it is importing waits for that import, and once it is done no making waits for one. So the whole + RAM is faulted in and pinned from soon after `use_host_ram`, where a chunk's pages were faulted + in only when an object over it was first made (on an RTX 5080 laptop with no other load: 7.5 ms + a chunk of fresh `memfd` RAM under `MADV_HUGEPAGE`, 2 s for 16 GiB). 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