🐛 Keep a surface's pages mapped while a device imports them

On Linux a buffer over a surface at no offset imports the surface
stand-in's own memory (or its view of the guest's pages) at its base
address, and gave the runtime a keep-alive that held nothing. The runtime
runs the deallocator at Metal's moment, as it lets go of the buffer, but
keeps the import while a command buffer may still reach the texture over
it (a retired image waiting on a heap-set ticket, a live table held by a
deferred pass). The surface's last reference could go then, and its
memory was unmapped under a live userptr import. A surface over a single
range of the guest's pages has no memory of its own, and core's unmap of
that range could land in the same window.

ANV on i915 lists every live import in each execbuffer, so the next
submission from any queue failed with EFAULT, which ANV answers as
VK_ERROR_DEVICE_LOST. Boots on ms01's Iris Xe under preloaded jemalloc
died so (2 of 8), each after a watched munmap over a live userptr range;
the allocator only shifts the timing.

The surface's memory is now an Arc of its own, freed with its last holder,
and the keep-alive holds it, plus an unmap hold on a single-range
surface's pages, until the runtime frees the import. A hold is no
reference: the retain count, and so what the guest sees, is unchanged.
macOS keeps nothing: IOSurface's memory is the surface's, and Metal wires
a no-copy buffer's pages. The pattern test covers both surfaces.
This commit is contained in:
Anees Iqbal committed 2026-10-14 12:06:09 +03:00
1 parent 203c3d96bf
commit be81ac03ca
6 files changed
+302 -33

No files matched your search

+202 -7
View File
@@ -531,9 +531,10 @@ impl VulkanDevice {
/// allocation size), whose deallocator holds `surface` until the runtime releases the buffer,
/// at Metal's moment (given a keep-alive), and whose range token is
/// `token`, which the runtime drops as it frees the buffer's range. Over the surface's memory
/// itself, nothing of this platform's keeps it mapped: the surface's last release may unmap
/// it before the runtime frees its import (`crate::remap`'s docs, "What is not ours to
/// unmap"); over an alias, the keep-alive holds the alias until then.
/// itself, the keep-alive holds that memory until the runtime frees its import on Linux,
/// whatever the surface's last release (`crate::os::surface_memory_hold`), and nothing holds
/// it on macOS, where the surface's last release may unmap it before (`crate::remap`'s docs,
/// "What is not ours to unmap"); over an alias, the keep-alive holds the alias until then.
///
/// At an offset into the surface's allocation (`kIOSurfaceOffset`,
/// [`crate::os::surface_offset`]) the base address lies that far into it, and the buffer's last
@@ -588,7 +589,10 @@ impl VulkanDevice {
address",
crate::os::memory_kind(surface)
);
(base, backing::keep_alive(()))
// The runtime runs the deallocator as it lets go of the buffer, which may drop the
// surface's last reference, and frees its import once nothing else holds it.
let hold = crate::os::surface_memory_hold(surface);
(base, backing::keep_alive(hold))
} else {
let first = u64::try_from(base.as_ptr().addr())
.unwrap_or(u64::MAX)
@@ -628,9 +632,10 @@ impl VulkanDevice {
.wrapping_add(usize::try_from(offset).unwrap_or(usize::MAX));
(pointer(sel, HostPtr::from_ptr(from)), keep)
};
// SAFETY: the surface's memory stays mapped while the surface lives, which the
// deallocator holds until the runtime lets go of the buffer; an alias of its allocation,
// which the keep-alive holds, until the runtime freed its import.
// SAFETY: an alias of the surface's allocation stays mapped until the runtime freed its
// import, which the keep-alive holds, and so does the surface's own memory on Linux
// (`surface_memory_hold`); on macOS that memory stays while the surface lives, which the
// deallocator holds until the runtime lets go of the buffer, Metal's moment.
let memory = unsafe { crate::os::host_memory(base) };
let contents = rt::BufferContents::NoCopy {
memory,
@@ -1985,6 +1990,196 @@ pub(crate) mod tests {
assert_eq!(d.raw.work_counts().host_deallocators_delayed, 0);
}
/// A texture on a surface, whose buffer imports the surface's memory at its base address,
/// released with the surface's last reference while a command buffer that binds the device's
/// heap set runs: that command buffer may read any live texture through its ID, so the runtime
/// keeps the texture's image, which holds the import, until it completes, while the texture and
/// its buffer go at the release, Metal's moment, and with the buffer the deallocator runs,
/// which drops the surface's last reference. The surface's memory stays mapped until the
/// runtime freed the import, after the command buffer completed
/// ([`crate::os::surface_memory_hold`]): its own memory, and a single range of core's mapping
/// of the guest's pages, which core then unmaps through the platform's VM. An i915 execbuffer
/// that lists an import whose pages are unmapped fails, which ANV answers as the device lost
/// (`crate::remap`'s docs). The command buffer reads another texture through its ID, so no
/// command of it names the surface's. Linux's: on macOS IOSurface's memory is the surface's own
#[cfg(target_os = "linux")]
#[test]
fn a_surface_textures_image_keeps_the_surfaces_memory() {
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use reims_vgpu_core::host::PhysicalMemoryRange;
use reims_vgpu_core::num::ToU64 as _;
use reims_vgpu_core::platform::blit::ResourceRef;
use reims_vgpu_core::platform::command::{CommandBuffer, CommandQueue};
use reims_vgpu_core::platform::compute::{ComputeCmd, ComputeEncoder};
use reims_vgpu_core::platform::os::surface::{IoSurfaces as _, Surface as _, SurfaceSpec};
use reims_vgpu_core::platform::os::vm::HostVm as _;
use reims_vgpu_core::platform::resource::{Buffer, Library, Texture as _};
use reims_vgpu_core::platform::types::{CommandBufferStatus, MtlSize, NsRange};
use crate::gpu::resource::tests::bgra;
/// The kernel that keeps the GPU busy (`src/gpu/spin.metal`), as the test above uses it.
const SPIN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/spin.metallib"));
/// The kernels that read a texture an argument buffer holds (`src/gpu/rgbx.metal`).
const RGBX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rgbx.metallib"));
const ROUNDS: u32 = 1_000;
/// `MTLResourceUsageRead`.
const READ: u64 = 1;
/// The surface's bytes: 64 x 32 BGRA texels.
const LEN: u64 = 64 * 32 * 4;
let wait = Duration::from_secs(30);
// Whether `done` came true within `wait`, polled each millisecond.
let within = |done: &dyn Fn() -> bool| {
(0..wait.as_millis()).any(|_| {
done() || {
std::thread::sleep(Duration::from_millis(1));
false
}
}) || done()
};
let d = dev();
let state = |metallib: &[u8], kernel: &str| {
let library = d.new_library(metallib).unwrap().unwrap().unwrap();
let function = library.new_function(OnFault::Die, kernel).unwrap().unwrap();
d.new_compute_pipeline_state_for_function(Some(&function))
.unwrap()
.unwrap()
};
let buffer = |length: u64| {
d.new_buffer_of_length(OnFault::Die, length, 0)
.unwrap()
.unwrap()
};
let spin = state(SPIN, "spin");
let held_read = state(RGBX, "rgbx_read_held_float");
let other = d
.new_texture(OnFault::Die, &bgra(4, 4, 0))
.unwrap()
.unwrap();
let queue = d.new_command_queue().unwrap();
// Core's mapping of the guest's pages the second surface lies in, as a memory map's.
let vm = crate::remap::VulkanVm::new();
let pages = vm.allocate_anywhere(LEN).unwrap();
let over_pages = SurfaceSpec {
pixel_format: u32::from_be_bytes(*b"BGRA"),
alloc_size: LEN,
width: 64,
height: 32,
bytes_per_element: 4,
bytes_per_row: 64 * 4,
element_width: 1,
element_height: 1,
client_address_ranges: Some(vec![PhysicalMemoryRange {
physical_address: pages.addr().to_u64(),
physical_length: LEN,
}]),
..SurfaceSpec::default()
};
let surfaces = [
(crate::os::tests::bgra_surface(64, 32), false),
(
crate::os::OsSurfaces::new().create(&over_pages).unwrap(),
true,
),
];
for (surface, cores) in surfaces {
let base = surface.base_address();
let texture = d
.new_texture_on_surface(&bgra(64, 32, 0), Some(&surface), 0)
.unwrap()
.unwrap();
let (words, read, held) = (buffer(16), buffer(16), buffer(8));
let word = |i: usize| {
// SAFETY: one of the buffer's four words, which the kernel reads and writes.
unsafe { AtomicU32::from_ptr(words.contents().as_ptr::<u32>().add(i)) }
};
word(0).store(ROUNDS, Ordering::SeqCst);
// SAFETY: the argument buffer's 8 bytes, which no command uses yet.
unsafe {
held.contents()
.as_ptr::<u64>()
.write(other.gpu_resource_id())
};
let cb = queue.command_buffer(OnFault::Die).unwrap().unwrap();
let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap();
let resident = [Some(ResourceRef::Texture(&other))];
let one = MtlSize::new(1, 1, 1);
for cmd in [
ComputeCmd::SetComputePipelineState { state: Some(&spin) },
ComputeCmd::SetBuffers {
buffers: &[Some(&words)],
offsets: &[0],
range: NsRange::new(0, 1),
},
ComputeCmd::DispatchThreads {
threads_per_grid: one,
threads_per_threadgroup: one,
},
ComputeCmd::SetComputePipelineState {
state: Some(&held_read),
},
ComputeCmd::SetBuffers {
buffers: &[Some(&read), Some(&held)],
offsets: &[0, 0],
range: NsRange::new(0, 2),
},
ComputeCmd::UseResources {
resources: &resident,
usage: READ,
},
ComputeCmd::DispatchThreads {
threads_per_grid: one,
threads_per_threadgroup: one,
},
ComputeCmd::EndEncoding,
] {
e.encode(OnFault::Die, cmd).unwrap();
}
cb.commit(OnFault::Die).unwrap();
cb.wait_until_scheduled().unwrap();
let running = word(1).load(Ordering::SeqCst) == 0;
drop((texture, surface));
// Core's mapping's release (`Teardown::Vm`), once the surface went.
let unmapped = !cores
|| crate::remap::VulkanVm::new()
.deallocate(pages, LEN)
.is_success();
let mapped_while_running = crate::os::mapped(base);
assert!(
running,
"released while the kernel ran (core's mapping: {cores})"
);
assert_eq!(
word(1).load(Ordering::SeqCst),
0,
"checked while the kernel ran (core's mapping: {cores})"
);
assert!(unmapped, "core's unmap answers success");
assert!(
mapped_while_running,
"the surface's memory stays mapped while the device imports it (core's mapping: \
{cores})"
);
let ended = [CommandBufferStatus::COMPLETED, CommandBufferStatus::ERROR];
assert!(
within(&|| ended.contains(&cb.status())),
"the command buffer did not complete"
);
assert_eq!(
cb.status(),
CommandBufferStatus::COMPLETED,
"{:?}",
cb.error()
);
assert!(
within(&|| !crate::os::mapped(base)),
"unmapped once the import was freed (core's mapping: {cores})"
);
}
}
/// Every handle to one runtime device is one object
#[test]
fn a_device_is_one_object() {
+1 -1
View File
@@ -30,7 +30,7 @@ use std::sync::Arc;
pub(crate) use host_os::{
Drawables, METAL_LEVEL, TWINS_READ_ONLY, allocate_zeros, dma_buf_refusal, host_memory,
import_view, plane_shape, shown_at,
import_view, plane_shape, shown_at, surface_memory_hold,
};
pub use host_os::{
GuestMemoryLease, OsClock, OsSurface, OsSurfaces, OsThreads, OsVm, default_gpu_core_count,
+1 -1
View File
@@ -28,7 +28,7 @@ pub use vm::LinuxVm;
pub(crate) use import::{
TWINS_READ_ONLY, allocate_zeros, dma_buf_refusal, host_memory, import_view, shown_at,
};
pub(crate) use surface::{plane_at, plane_shape, recorded_mut, ycbcr_matrix};
pub(crate) use surface::{plane_at, plane_shape, recorded_mut, surface_memory_hold, ycbcr_matrix};
#[cfg(test)]
pub(crate) use vm::allocate_aliasable;
#[cfg(test)]
@@ -14,6 +14,16 @@
//! the CPU where it is read-only for the GPU (`kIOSurfaceClientDirection` 2), as IOSurface maps
//! it on macOS. A protected surface (protection options other than 0) has no memory the CPU
//! reaches: its base address is NULL.
//! The mapping goes with the surface's last object, or later with the last hold on it
//! ([`surface_memory_hold`]): a device's import of the pages at the surface's base address
//! holds one until the runtime has freed the import, so the pages stay mapped while it lives
//! (`VK_EXT_external_memory_host`), though the surface's last reference went at Metal's
//! moment. One over a single range maps nothing of its own: the range is core's mapping, which
//! core unmaps through the platform's VM, so the hold holds that unmap instead
//! ([`crate::remap::UnmapHold`]). A hold is no reference: the retain count stays the objects'.
//! Measured on an Iris
//! Xe (Mesa 26.2.4's ANV, i915): ANV puts every live import in each execbuffer, and one whose
//! pages are unmapped fails it with `EFAULT`, which ANV answers as the device lost.
//! - **What it answers** is the spec's: its planes, rows and sizes, its allocation size exactly
//! as given. It holds no values (`IOSurfaceCopyValue`): nothing in the process sets one.
//! `lock` and `unlock` do nothing.
@@ -41,6 +51,7 @@
//! byte per element and rows of its width rounded up to 128 bytes (measured on the M3 Max:
//! widths 16, 17, 32 and 65535).
use std::ptr::NonNull;
use std::sync::Arc;
use reims_vgpu_core::host::{HostPtr, PhysicalMemoryRange};
@@ -98,15 +109,23 @@ struct Data {
alloc_size: u64,
/// The base address; 0 for a protected surface.
base: u64,
/// Its own memory, freed with it.
own: Option<OwnMemory>,
/// The view of the guest's pages it made, its first byte and length, freed with it.
view: Option<(u64, u64)>,
/// The memory it mapped, freed with the last holder of it.
memory: Arc<Memory>,
/// What it was made over ([`crate::os::surface_memory`] and the helpers beside it).
made: Mutex<MadeOver>,
}
impl Drop for Data {
/// The memory a surface mapped: its own, or its view of the guest's pages; none for one over a
/// single range of them, or a protected one.
#[derive(Debug)]
struct Memory {
/// Its own memory.
own: Option<OwnMemory>,
/// The view of the guest's pages it made, its first byte and length.
view: Option<(u64, u64)>,
}
impl Drop for Memory {
/// Frees the view the surface made, and its own memory.
fn drop(&mut self) {
if let Some((first, length)) = self.view {
@@ -116,6 +135,23 @@ impl Drop for Data {
}
}
/// A hold on the memory `surface` mapped, which keeps it mapped while it lives, the surface gone
/// or not, and counts no reference of the surface; for one over a single range of the guest's
/// pages, which maps nothing, an unmap hold on that range of core's mapping (module docs).
pub(crate) fn surface_memory_hold(surface: &LinuxSurface) -> impl Send + 'static {
let data = surface.data();
let memory = &data.memory;
let cores_unmap = (memory.own.is_none() && memory.view.is_none())
.then(|| {
NonNull::new(std::ptr::with_exposed_provenance_mut::<u8>(
data.base.to_usize(),
))
})
.flatten()
.map(|first| crate::remap::UnmapHold::new(first, data.alloc_size));
(Arc::clone(memory), cores_unmap)
}
impl LinuxSurface {
/// A new surface: one reference to a new object over `data`.
fn new(data: Data) -> LinuxSurface {
@@ -454,8 +490,10 @@ impl IoSurfaces<VulkanPlatform> for LinuxSurfaces {
protection_options: protection,
alloc_size: spec.alloc_size,
base: if base == 0 { 0 } else { base + spec.offset },
own,
view: view_made,
memory: Arc::new(Memory {
own,
view: view_made,
}),
made: Mutex::new(made),
}))
}
@@ -497,8 +535,10 @@ impl IoSurfaces<VulkanPlatform> for LinuxSurfaces {
protection_options: 0,
alloc_size,
base: own.first(),
own: Some(own),
view: None,
memory: Arc::new(Memory {
own: Some(own),
view: None,
}),
made: Mutex::new(MadeOver::default()),
}))
}
@@ -560,11 +600,11 @@ mod tests {
/// view.
fn mapped_range(s: &LinuxSurface) -> Option<(u64, u64)> {
let data = s.data();
let own = data.own.as_ref().map(|own| {
let own = data.memory.own.as_ref().map(|own| {
let length = data.alloc_size.next_multiple_of(page_size());
(own.first(), length)
});
own.or(data.view)
own.or(data.memory.view)
}
fn free(at: u64, length: u64) {
@@ -622,6 +662,31 @@ mod tests {
assert!(!mapped(base));
}
/// A hold on a surface's memory keeps it mapped past the surface's last object and counts no
/// reference of it, its own memory and its view of the guest's pages alike; the memory goes
/// with the hold
#[test]
fn a_hold_keeps_the_memory_past_the_last_reference() {
let page = page_size();
let (at, ranges) = guest_pages(2);
let several = SurfaceSpec {
alloc_size: 2 * page,
client_address_ranges: Some(ranges),
..host_only()
};
for spec in [host_only(), several] {
let s = LinuxSurfaces::new().create(&spec).unwrap();
let base = s.base_address();
let hold = surface_memory_hold(&s);
assert_eq!(s.retain_count(), 1);
drop(s);
assert!(mapped(base), "{spec:?}");
drop(hold);
assert!(!mapped(base), "{spec:?}");
}
free(at, 2 * page);
}
/// The layouts IOSurface refuses are refused (module docs), and those at its limits made
#[test]
fn refused_layouts_are_none() {
+5
View File
@@ -321,6 +321,11 @@ pub(crate) fn plane_shape(surface: &MetalSurface, plane: u64) -> Option<(u64, u6
))
}
/// What keeps `surface`'s memory mapped while a device imports it at its base address, the
/// surface gone or not: nothing here. IOSurface's memory is the surface's own, and nothing but a
/// reference of the surface, which the guest counts, keeps it.
pub(crate) fn surface_memory_hold(_surface: &MetalSurface) -> impl Send + 'static {}
/// The surface's key that names its YCbCr matrix (`kIOSurfaceYCbCrMatrix`).
pub(crate) const MATRIX_KEY: &str = "IOSurfaceYCbCrMatrix";
+17 -13
View File
@@ -94,19 +94,23 @@
//! - **What is not ours to unmap**: memory a no-copy buffer lies in whose unmap is the host's or
//! the system's, which no hold defers: the host's own mapping in a device without a memory map
//! (`unmapMemory`, the blocks setup; QEMU passes a memory map, so a guest under QEMU never
//! reaches it, and only the suite's runner makes the blocks setup), an IOSurface's memory that
//! a buffer over it at no offset imports as it is (core's buffer over a guest's IOSurface,
//! `MapperRef`, whichever guest maps one), and on Linux the surface stand-in's own memory and
//! views (`os::linux::surface`). There the deallocator (the host's unmap, the surface's
//! release) may unmap the pages before the free, in the same release, or, where a command
//! buffer submitted before a texture over them was released still holds the import, until it
//! completes. Ground: MoltenVK's no-copy buffer keeps the
//! pages it was made over, which Metal wires as it makes the buffer (`tests/no_copy_remap.rs`
//! measures a remap under one), and NVIDIA's host-pointer import pins its
//! pages as it imports them (Linux drivers pin imported pages, the runtime's `host_memory`), so
//! on this platform's devices the GPU still reads the pages it imported, as Metal's reads those
//! it wired. A driver that validates such pages again at each submission (ANV's and i915's
//! userptr) would fail a submission that lists the import in that window.
//! reaches it, and only the suite's runner makes the blocks setup), and on macOS an IOSurface's
//! memory that a buffer over it at no offset imports as it is (core's buffer over a guest's
//! IOSurface, `MapperRef`, whichever guest maps one). There the deallocator (the host's unmap,
//! the surface's release) may unmap the pages before the free, in the same release, or, where
//! a command buffer submitted before a texture over them was released still holds the import,
//! until it completes. Ground: MoltenVK's no-copy buffer keeps the pages it was made over,
//! which Metal wires as it makes the buffer (`tests/no_copy_remap.rs` measures a remap under
//! one), and NVIDIA's host-pointer import pins its pages as it imports them (Linux drivers pin
//! imported pages, the runtime's `host_memory`), so on those devices the GPU still reads the
//! pages it imported, as Metal's reads those it wired. A driver that validates such pages again
//! at each submission fails a submission that lists the import in that window: on Linux the
//! surface stand-in's own memory and views (`os::linux::surface`) are therefore held until the
//! free, by the keep-alive of a buffer over a surface at no offset (`surface_memory_hold`), and
//! so is core's unmap of the single range of its mapping a surface lies in, by an [`UnmapHold`].
//! Measured on an Iris Xe (Mesa 26.2.4's ANV, i915) before that hold: ANV lists every live
//! import in each execbuffer, and one listing an import whose pages a surface's release had
//! unmapped failed with `EFAULT`, which ANV answers as the device lost.
//!
//! What a report costs, measured on the M3 Max (release build, 100,000 calls, three runs): with
//! no no-copy buffer live, about 11 ns per wrapped block call, the task lookup and the runtime's