From 7cfca1a29d0908f40caf820e492eb3e2c8634e2e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 7 Nov 2026 16:28:57 -0800 Subject: [PATCH] Read a copied host buffer's pages before making its memory, so its own mapping never lies among them Both copied-buffer makings (Device::copied_pages and copied_buffer) made and mapped the copy's memory first and read the caller's pages after (CopiedBuffers::add). Where a page of the caller's range is not mapped, the copy's own mapping could land there, the read find every byte mapped, and the call make a buffer over memory Metal makes no buffer over. On the M3 Max runtime_lane::host_memory::memory_metal_makes_no_buffer_over_is_refused_when_it_is_made made a buffer over a mapped page and an unmapped one in 7 of 20 runs (m3-max-5626); with the test seeing the page mapped again and trying again over a fresh reservation (da25c0efad), the retried runs failed on the failed import each try adds (m3-max-5693), the bug itself still hidden. CopiedBuffers::read now takes the first read (FirstRead: the snapshot and whether the GPU's writes are dropped) before either making allocates, and CopiedBuffers::add registers the copy from it. The test bounds the failed imports by its tries made again. (cherry picked from commit 3c2a300aed4721dad94c3e682e83075a4f5cca1d) --- .../src/buffer_descriptor.rs | 56 ++++----- crates/metal2vulkan-runtime/src/copied.rs | 106 +++++++++++++----- .../src/runtime_lane/host_memory.rs | 12 +- 3 files changed, 118 insertions(+), 56 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index d5b625d20..cccacfbc8 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -1440,6 +1440,20 @@ impl Device { let size = (window.offset.checked_add(length)) .and_then(|end| end.checked_next_multiple_of(16)) .ok_or(Error::OutOfMemory(MemoryKind::Device))?; + // The caller's pages are read before the copy's memory is made, so no mapping made for the + // copy is among them as they are read (`CopiedBuffers::read`). + // SAFETY: the caller's bytes (the caller's contract). + let first = match unsafe { crate::copied::CopiedBuffers::read(pointer, bytes, read_only) } { + Ok(first) => first, + Err(why) => { + return Err(match why { + NotCopied::Unreadable => failed + .filter(|failed| !refused(failed)) + .unwrap_or_else(not_importable), + NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host), + }); + } + }; let fresh = match own_pages { true => self.fresh_page_buffer(window.size.max(size), MemoryClass::Shared)?, false => None, @@ -1468,19 +1482,8 @@ impl Device { }; // SAFETY: the copy is the placement's `length` bytes past the window's offset, mapped, // which nothing uses yet and which stay mapped while the import holds them; the caller's - // bytes stay mapped as long (the caller's contract). - let copied = match unsafe { shared.copied.add(pointer, copy, bytes, read_only) } { - Ok(copied) => copied, - Err(why) => { - discard(&memory); - return Err(match why { - NotCopied::Unreadable => failed - .filter(|failed| !refused(failed)) - .unwrap_or_else(not_importable), - NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host), - }); - } - }; + // bytes, which `first` read, stay mapped as long (the caller's contract). + let copied = unsafe { shared.copied.add(first, pointer, copy) }; // The host address of the window's first byte, as an import's: `contents` is the // pointer, `window.offset` past it. let start = NonNull::new(pointer.as_ptr().wrapping_sub(window.offset as usize)); @@ -1681,6 +1684,18 @@ impl Device { let size = length .checked_next_multiple_of(16) .ok_or_else(|| nil(call, Problem::BufferLength { length }))?; + // The caller's pages are read before the copy's memory is made, so no mapping made for the + // copy is among them as they are read (`CopiedBuffers::read`). + // SAFETY: the caller's bytes (the caller's contract). + let first = match unsafe { crate::copied::CopiedBuffers::read(pointer, bytes, read_only) } { + Ok(first) => first, + Err(why) => { + return Err(match why { + NotCopied::Unreadable => unreadable(failed), + NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host), + }); + } + }; let info = shared.sharing().buffer( vk::BufferCreateInfo::default() .size(size) @@ -1720,18 +1735,9 @@ impl Device { )); }; // SAFETY: the copy is the placement's `length` bytes, mapped, which nothing uses yet and - // which stay mapped while the import holds them; the caller's bytes stay mapped as long - // (the caller's contract). - let copied = match unsafe { shared.copied.add(pointer, copy, bytes, read_only) } { - Ok(copied) => copied, - Err(why) => { - discard(&memory); - return Err(match why { - NotCopied::Unreadable => unreadable(failed), - NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host), - }); - } - }; + // which stay mapped while the import holds them; the caller's bytes, which `first` read, + // stay mapped as long (the caller's contract). + let copied = unsafe { shared.copied.add(first, pointer, copy) }; // Its `contents` is the caller's pointer, as a no-copy buffer's is. memory.mapped = Some(super::memory::Mapped::of_caller(pointer)); let buffer = self.buffer_of(BufferParts { diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index 0d574fe86..bf25aee2a 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -173,7 +173,43 @@ impl CopiesReached { } } -/// Why a copy was not made ([`CopiedBuffers::add`]). +/// The caller's bytes as a copy's first read of them took them ([`CopiedBuffers::read`]), before +/// the copy's memory was made: the bytes the copy and the pages first agree on, and whether the +/// GPU's writes to the copy are dropped. +pub(crate) struct FirstRead { + snapshot: Box<[u8]>, + drops_writes: bool, +} + +impl FirstRead { + /// `length` bytes at `pages`, read by `read`, which answers whether it read every one. + /// + /// # Safety + /// + /// `read` reads `pages` as [`CopiedBuffers::read`]'s contract lets it. + unsafe fn of( + pages: NonNull, + length: usize, + read: impl FnOnce(NonNull, &mut [u8]) -> bool, + drops_writes: bool, + ) -> Result { + let mut snapshot = Vec::new(); + if snapshot.try_reserve_exact(length).is_err() { + return Err(NotCopied::OutOfHostMemory); + } + snapshot.resize(length, 0u8); + let mut snapshot = snapshot.into_boxed_slice(); + if !read(pages, &mut snapshot) { + return Err(NotCopied::Unreadable); + } + Ok(FirstRead { + snapshot, + drops_writes, + }) + } +} + +/// Why a copy was not made ([`CopiedBuffers::read`]). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum NotCopied { /// A page is not mapped, or mapped without read permission: memory Metal makes no buffer over. @@ -346,26 +382,25 @@ impl CopiedBuffers { self.live.load(Ordering::Relaxed) > 0 } - /// Register the copy at `copy` of the `length` bytes at `pages`, its bytes read from the pages - /// now ([`read_caller`]: through the kernel, or where it fails, with plain loads of pages - /// mapped readable). Where the process cannot write every page ([`mapped_writable`]), or - /// `read_only` (memory of Metal's private option bit 24), the GPU's writes to the copy are - /// dropped (the module docs). Refused, registering nothing, where the process cannot read + /// The first read of the `length` bytes at `pages` for a copy of them ([`read_caller`]: + /// through the kernel, or where it fails, with plain loads of pages mapped readable), made + /// before the copy's memory is: a mapping the runtime makes for the copy may land where a + /// page of the caller's is not mapped, and a read after it would find every byte mapped and + /// copy memory Metal makes no buffer over. Where the process cannot write every page + /// ([`mapped_writable`]), or `read_only` (memory of Metal's private option bit 24), the GPU's + /// writes to the copy are dropped (the module docs). Refused where the process cannot read /// every page, or the host has no memory for the bytes the copy and the pages last agreed on. /// /// # Safety /// - /// `copy` is `length` bytes of mapped memory nothing else uses yet, which stays mapped until - /// the answer is dropped; `pages` the caller's bytes, which stay mapped as long + /// `pages` are the caller's bytes, which stay mapped while their copy lives /// (`HostMemory::new`), and which the CPU reads without a fault wherever the process maps /// them with read permission. - pub(crate) unsafe fn add( - self: &Arc, + pub(crate) unsafe fn read( pages: NonNull, - copy: NonNull, length: usize, read_only: bool, - ) -> Result { + ) -> Result { let read = |pages: NonNull, into: &mut [u8]| { // SAFETY: the caller's bytes, read with plain loads only where the process maps them // readable (the caller's contract). @@ -375,15 +410,16 @@ impl CopiedBuffers { let drops_writes = read_only || !mapped_writable(start, start.saturating_add(length as u64)); // SAFETY: the caller's. - unsafe { self.add_reading(pages, copy, length, read, drops_writes) } + unsafe { FirstRead::of(pages, length, read, drops_writes) } } - /// [`CopiedBuffers::add`], the first bytes of the pages read by `read`, which answers whether - /// it read every one; the GPU's writes to the copy dropped where `drops_writes`. + /// [`CopiedBuffers::read`] and [`CopiedBuffers::add`] of the copy at `copy`, the first bytes + /// of the pages read by `read`, which answers whether it read every one; the GPU's writes to + /// the copy dropped where `drops_writes`. /// /// # Safety /// - /// As [`CopiedBuffers::add`]'s. + /// As [`CopiedBuffers::read`]'s and [`CopiedBuffers::add`]'s. pub(crate) unsafe fn add_reading( self: &Arc, pages: NonNull, @@ -392,15 +428,31 @@ impl CopiedBuffers { read: impl FnOnce(NonNull, &mut [u8]) -> bool, drops_writes: bool, ) -> Result { - let mut snapshot = Vec::new(); - if snapshot.try_reserve_exact(length).is_err() { - return Err(NotCopied::OutOfHostMemory); - } - snapshot.resize(length, 0u8); - let mut snapshot = snapshot.into_boxed_slice(); - if !read(pages, &mut snapshot) { - return Err(NotCopied::Unreadable); - } + // SAFETY: the caller's. + let first = unsafe { FirstRead::of(pages, length, read, drops_writes) }?; + // SAFETY: the caller's. + Ok(unsafe { self.add(first, pages, copy) }) + } + + /// Register the copy at `copy` of the caller's bytes at `pages` that `first` read, its bytes + /// those `first` took. + /// + /// # Safety + /// + /// `copy` is as many bytes as `first` read of mapped memory nothing else uses yet, which stays + /// mapped until the answer is dropped; `pages` are the bytes `first` read, which stay mapped + /// as long (`HostMemory::new`). + pub(crate) unsafe fn add( + self: &Arc, + first: FirstRead, + pages: NonNull, + copy: NonNull, + ) -> Copied { + let FirstRead { + snapshot, + drops_writes, + } = first; + let length = snapshot.len(); // SAFETY: the copy is `length` bytes nothing else uses yet (the caller's). unsafe { std::ptr::copy_nonoverlapping(snapshot.as_ptr(), copy.as_ptr(), length) }; let id = self.next.fetch_add(1, Ordering::Relaxed); @@ -414,11 +466,11 @@ impl CopiedBuffers { keys: Vec::new(), }); self.live.fetch_add(1, Ordering::Relaxed); - Ok(Copied { + Copied { buffers: Arc::clone(self), id, drops_writes, - }) + } } /// At a commit: write into each copy the command buffer's commands may reach (`used`: the diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs index 0db917ddc..608306009 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs @@ -1918,11 +1918,14 @@ fn a_gpu_fault_fails_its_command_buffer_and_the_queue_runs_on() { /// (`REFUSED-AT-MAKING`). The driver may report each import it failed, as MoltenVK reports its /// failed `vkAllocateMemory`; nothing else is reported. A mapped page followed by one the test /// unmapped is made again over a fresh reservation where another thread's mapping took the -/// unmapped page before the making looked (seen mapped once the buffer was made: 7 of 20 runs on -/// the M3 Max at d65be37964, m3-max-5626), so the making is held to memory whose page is unmapped -/// as it looks. +/// unmapped page before the making looked (the page seen mapped once a buffer was made), so the +/// making is held to memory whose page is unmapped as it looks. The copied host buffer's own +/// mapping was such a one until it read the caller's pages before making its memory (7 of 20 +/// runs on the M3 Max at d65be37964, m3-max-5626). #[test] fn memory_metal_makes_no_buffer_over_is_refused_when_it_is_made() { + // The half-mapped case's tries made again, each one more failed import the driver may report. + let tries = AtomicUsize::new(0); let reported = on_device_reporting(|device| { let len = 2 * GUEST_PAGE; let reserve = || { @@ -2010,6 +2013,7 @@ fn memory_metal_makes_no_buffer_over_is_refused_when_it_is_made() { assert_eq!(tried.runs.load(Ordering::SeqCst), 0, "{what}: ran"); assert_eq!(tried.dropped.load(Ordering::SeqCst), 1, "{what}: kept"); answers.push(format!("{what}: {error:?} ({retried} tries made again)")); + tries.store(retried, Ordering::SeqCst); // SAFETY: the first page goes too, and with it the reservation. assert_eq!(unsafe { libc::munmap(half.as_ptr().cast(), GUEST_PAGE) }, 0); break; @@ -2053,7 +2057,7 @@ fn memory_metal_makes_no_buffer_over_is_refused_when_it_is_made() { "the validation layer reported: {other:#?}" ); assert!( - failed_imports.len() <= 3, + failed_imports.len() <= 3 + tries.load(Ordering::SeqCst), "more failed imports reported than made: {failed_imports:#?}" ); }