🆕 Refuse GPUs whose driver imports no shared memory

A user's macOS 15 guest died on every boot on an AMD host (RX 7600 and
760M, RADV, Mesa 26.2.4) at the library's first import of guest RAM:
newBufferWithBytesNoCopy: refused with Unsupported { HostMemory,
NotRepresentable }. Guest RAM on Linux is a shared mapping of a memfd, and
libdrm's amdgpu_create_bo_from_user_mem asks the kernel for anonymous
memory only (AMDGPU_GEM_USERPTR_ANONONLY), which amdgpu refuses for any
mapping with a file behind it (read from libdrm's and the kernel's code;
metal2vulkan's host_memory.rs measured the refusal on RADV). No AMD GPU on
Linux can run a guest.

reims-ctl's Vulkan probe now asks each driver to import a page of a shared
memfd mapping through VK_EXT_external_memory_hosts, as the library does. A
start refuses a GPU that refused it, naming why and whether another GPU of
the host can run the guest, instead of booting into the death; reims-ctl
gpus, doctor, the bug report and the TUI mark such GPUs. A probe that
could not ask leaves the GPU as it was.
This commit is contained in:
Anees Iqbal committed 2026-10-11 22:03:43 +03:00
1 parent 6ebf462388
commit f6fcaf5f44
4 files changed
+288 -6

No files matched your search

+5 -4
View File
@@ -94,10 +94,11 @@ reims-ctl start mac # a window opens for each guest
### x86-64 guest on Linux (KVM)
1. **Host prep.** You need KVM (`/dev/kvm`) and a Vulkan driver; `reims-ctl gpus` lists the GPUs a
VM can be given. The library's views of guest memory take a kernel mapping for each run of
guest pages, so raise `vm.max_map_count`: `sudo sysctl -w vm.max_map_count=1048576` covers a
12 GiB guest, and a file in `/etc/sysctl.d` keeps it. `scripts/install-ctl.sh` and `reims-ctl`
warn when it is too low.
VM can be given. AMD GPUs cannot run guests yet: their Linux drivers import no shared memory,
and guest RAM is shared memory, so `reims-ctl gpus` marks them and a start refuses them. The
library's views of guest memory take a kernel mapping for each run of guest pages, so raise
`vm.max_map_count`: `sudo sysctl -w vm.max_map_count=1048576` covers a 12 GiB guest, and a file
in `/etc/sysctl.d` keeps it. `scripts/install-ctl.sh` and `reims-ctl` warn when it is too low.
2. **Get OpenCore and an installer with [OSX-KVM](https://github.com/kholia/OSX-KVM)** (or ULTMOS).
Follow that project's docs to fetch the recovery image and build OpenCore. You only need its
+4 -1
View File
@@ -883,6 +883,9 @@ fn gpus(host: Host) {
g.device_id,
g.driver_file.display()
);
if !g.runs_guests() {
println!(" {}", gpu::NO_SHARED_MEMORY);
}
}
println!("Give a VM one with: reims-ctl set NAME --gpu NUMBER");
}
@@ -986,7 +989,7 @@ fn doctor(host: Host) -> Result<i32> {
}
let gpus = gpu::list();
line(
!gpus.is_empty(),
gpus.iter().any(|g| g.runs_guests()),
"vulkan",
if gpus.is_empty() {
"no GPU found".into()
+263 -1
View File
@@ -7,6 +7,14 @@
//! asking each manifest's driver in a child process (`reims-ctl __vulkan-probe`), so a driver
//! that hangs or crashes costs only that one.
//!
//! Each GPU's driver is also asked whether it imports a page of shared memory through
//! `VK_EXT_external_memory_host`, as the library imports guest RAM, a shared mapping of a memfd
//! (docs/qemu.md, "The files behind guest RAM"). AMD's drivers refuse it: libdrm's
//! `amdgpu_create_bo_from_user_mem` asks the kernel for anonymous memory only
//! (`AMDGPU_GEM_USERPTR_ANONONLY`), and amdgpu refuses a mapping with a file behind it, so the
//! library dies at its first import of guest RAM there. A start refuses such a GPU
//! (`runtime::preflight`), and the lists mark it.
//!
//! On macOS the library runs on the system's default Metal device; there is nothing to choose.
use serde::{Deserialize, Serialize};
@@ -23,8 +31,16 @@ pub struct GpuInfo {
/// Whether another GPU shares the driver (the device ID then picks it).
#[serde(default)]
pub shares_driver: bool,
/// Whether the driver imported a page of shared memory, as the library imports guest RAM:
/// `None` where the probe could not ask (module docs).
#[serde(default)]
pub imports_shared_memory: Option<bool>,
}
/// Why a GPU whose driver refuses shared memory runs no guest (module docs).
pub const NO_SHARED_MEMORY: &str = "cannot run guests: its driver imports no shared memory, which \
guest RAM is (AMD's Linux drivers import only private memory)";
impl GpuInfo {
pub fn label(&self) -> String {
let file = self
@@ -32,7 +48,17 @@ impl GpuInfo {
.file_name()
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_default();
format!("{} ({}, {file})", self.name, self.kind)
let note = match self.runs_guests() {
true => String::new(),
false => format!(": {NO_SHARED_MEMORY}"),
};
format!("{} ({}, {file}){note}", self.name, self.kind)
}
/// Whether the library can run a guest on the GPU: not where its driver refused shared
/// memory.
pub fn runs_guests(&self) -> bool {
self.imports_shared_memory != Some(false)
}
pub fn to_config(&self) -> crate::vm::Gpu {
@@ -151,6 +177,16 @@ pub fn list() -> Vec<GpuInfo> {
gpus
}
/// The GPU of `list` the library takes for a VM given `gpu`: the first of those its driver
/// manifest and device ID keep, or with neither the first of all, as `list` puts discrete GPUs
/// first. `None` where none is kept, as for a manifest `list` does not name.
pub fn chosen<'a>(gpu: &crate::vm::Gpu, list: &'a [GpuInfo]) -> Option<&'a GpuInfo> {
list.iter().find(|g| {
gpu.driver_file.as_ref().is_none_or(|f| *f == g.driver_file)
&& gpu.device_id.is_none_or(|id| id == g.device_id)
})
}
fn probe(exe: &std::path::Path, file: &std::path::Path) -> Vec<GpuInfo> {
use std::process::{Command, Stdio};
let child = Command::new(exe)
@@ -227,6 +263,7 @@ pub fn probe_main() -> i32 {
kind: kind.into(),
driver_file: PathBuf::new(),
shares_driver: false,
imports_shared_memory: imports_shared_memory(&instance, pd, &p),
};
println!("{}", serde_json::to_string(&info).unwrap());
}
@@ -236,7 +273,232 @@ pub fn probe_main() -> i32 {
0
}
/// Whether `pd`'s driver imports a page of shared memory, a shared mapping of a memfd as QEMU's
/// `memory-backend-memfd,share=on` maps guest RAM, through `VK_EXT_external_memory_host`, as the
/// library does: `Some(false)` where the device lacks the extension, has no host-visible coherent
/// memory type for the page, or refuses the import as the library's runtime counts a refusal
/// (`VK_ERROR_INVALID_EXTERNAL_HANDLE`, or `VK_ERROR_UNKNOWN`, which RADV of Mesa 26.0 answers);
/// `None` where the probe could not ask.
///
/// # Safety
///
/// `pd` is one of `instance`'s physical devices, and `p` its properties.
#[cfg(target_os = "linux")]
unsafe fn imports_shared_memory(
instance: &ash::Instance,
pd: ash::vk::PhysicalDevice,
p: &ash::vk::PhysicalDeviceProperties,
) -> Option<bool> {
use ash::vk;
let ext = ash::ext::external_memory_host::NAME;
// SAFETY: the caller's `pd` and `p`; the device made here is destroyed before it returns,
// after the import is freed, and the page outlives both.
unsafe {
let has = instance.enumerate_device_extension_properties(pd).ok()?;
if !has.iter().any(|e| e.extension_name_as_c_str() == Ok(ext)) {
return Some(false);
}
if p.api_version < vk::API_VERSION_1_1 {
return None;
}
let mut host = vk::PhysicalDeviceExternalMemoryHostPropertiesEXT::default();
let mut props = vk::PhysicalDeviceProperties2::default().push_next(&mut host);
instance.get_physical_device_properties2(pd, &mut props);
let page = u64::try_from(libc::sysconf(libc::_SC_PAGESIZE)).ok()?;
let len = page.max(host.min_imported_host_pointer_alignment);
let shared = SharedPage::new(usize::try_from(len).ok()?)?;
let priorities = [1.0f32];
let queues = [vk::DeviceQueueCreateInfo::default()
.queue_family_index(0)
.queue_priorities(&priorities)];
let names = [ext.as_ptr()];
let info = vk::DeviceCreateInfo::default()
.queue_create_infos(&queues)
.enabled_extension_names(&names);
let device = instance.create_device(pd, &info, None).ok()?;
let answer = import(instance, pd, &device, shared.at, len);
device.destroy_device(None);
answer
}
}
/// The import of `len` bytes at `at` on `device` (`imports_shared_memory`), freed at once.
///
/// # Safety
///
/// `device` is made on `pd` with `VK_EXT_external_memory_host`, and the bytes stay mapped
/// meanwhile.
#[cfg(target_os = "linux")]
unsafe fn import(
instance: &ash::Instance,
pd: ash::vk::PhysicalDevice,
device: &ash::Device,
at: *mut std::ffi::c_void,
len: u64,
) -> Option<bool> {
use ash::vk;
let refused = |e: vk::Result| match e {
vk::Result::ERROR_INVALID_EXTERNAL_HANDLE | vk::Result::ERROR_UNKNOWN => Some(false),
_ => None,
};
let handle = vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT;
let ext = ash::ext::external_memory_host::Device::new(instance, device);
let mut host = vk::MemoryHostPointerPropertiesEXT::default();
// SAFETY: the caller's device and bytes; the memory is freed before this returns.
unsafe {
let asked = (ext.fp().get_memory_host_pointer_properties_ext)(
device.handle(),
handle,
at,
&mut host,
);
if asked != vk::Result::SUCCESS {
return refused(asked);
}
let types = instance.get_physical_device_memory_properties(pd);
let wanted = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT;
let index = (0..types.memory_type_count).find(|&i| {
host.memory_type_bits & (1 << i) != 0
&& usize::try_from(i)
.ok()
.and_then(|i| types.memory_types.get(i))
.is_some_and(|t| t.property_flags.contains(wanted))
});
let Some(index) = index else {
return Some(false);
};
let mut pointer = vk::ImportMemoryHostPointerInfoEXT::default()
.handle_type(handle)
.host_pointer(at);
let info = vk::MemoryAllocateInfo::default()
.allocation_size(len)
.memory_type_index(index)
.push_next(&mut pointer);
match device.allocate_memory(&info, None) {
Ok(memory) => {
device.free_memory(memory, None);
Some(true)
}
Err(e) => refused(e),
}
}
}
/// A shared mapping, read and write, of a fresh memfd, as QEMU maps guest RAM; unmapped when it
/// drops. The file goes with the mapping.
#[cfg(target_os = "linux")]
struct SharedPage {
at: *mut std::ffi::c_void,
len: usize,
}
#[cfg(target_os = "linux")]
impl SharedPage {
fn new(len: usize) -> Option<SharedPage> {
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
// SAFETY: a new file of this process's, closed when `fd` drops, and a new mapping of it,
// which `SharedPage` owns.
unsafe {
let fd = libc::memfd_create(c"reims-ctl-probe".as_ptr(), libc::MFD_CLOEXEC);
if fd < 0 {
return None;
}
let fd = OwnedFd::from_raw_fd(fd);
if libc::ftruncate(fd.as_raw_fd(), libc::off_t::try_from(len).ok()?) != 0 {
return None;
}
let at = libc::mmap(
std::ptr::null_mut(),
len,
libc::PROT_READ | libc::PROT_WRITE,
libc::MAP_SHARED,
fd.as_raw_fd(),
0,
);
(at != libc::MAP_FAILED).then_some(SharedPage { at, len })
}
}
}
#[cfg(target_os = "linux")]
impl Drop for SharedPage {
fn drop(&mut self) {
// SAFETY: the mapping `new` made, which nothing imports any more.
unsafe { libc::munmap(self.at, self.len) };
}
}
#[cfg(not(target_os = "linux"))]
pub fn probe_main() -> i32 {
1
}
#[cfg(test)]
mod tests {
use super::*;
fn gpu(name: &str, file: &str, device_id: u32, imports: Option<bool>) -> GpuInfo {
GpuInfo {
name: name.into(),
vendor_id: 0x1002,
device_id,
kind: "discrete".into(),
driver_file: file.into(),
shares_driver: false,
imports_shared_memory: imports,
}
}
#[test]
fn a_probe_line_without_the_answer_reads_as_unasked() {
let line =
r#"{"name":"G","vendor_id":4098,"device_id":29824,"kind":"discrete","driver_file":""}"#;
let g: GpuInfo = serde_json::from_str(line).unwrap();
assert_eq!(g.imports_shared_memory, None);
assert!(g.runs_guests());
}
#[test]
fn only_a_refusal_of_shared_memory_stops_guests() {
assert!(gpu("A", "/a.json", 1, Some(true)).runs_guests());
assert!(gpu("A", "/a.json", 1, None).runs_guests());
let amd = gpu(
"AMD Radeon RX 7600 (RADV NAVI33)",
"/icd/radeon_icd.json",
1,
Some(false),
);
assert!(!amd.runs_guests());
assert_eq!(
amd.label(),
format!(
"AMD Radeon RX 7600 (RADV NAVI33) (discrete, radeon_icd.json): {NO_SHARED_MEMORY}"
)
);
}
#[test]
fn the_chosen_gpu_is_the_first_the_config_keeps() {
let list = [
gpu("dGPU", "/icd/radeon.json", 0x7480, Some(false)),
gpu("iGPU", "/icd/radeon.json", 0x15bf, Some(false)),
gpu("nv", "/icd/nvidia.json", 0x2204, Some(true)),
];
let of = |file: Option<&str>, id: Option<u32>| {
let g = crate::vm::Gpu {
driver_file: file.map(Into::into),
device_id: id,
name: None,
};
chosen(&g, &list).map(|g| g.name.clone())
};
assert_eq!(of(None, None).as_deref(), Some("dGPU"));
assert_eq!(of(Some("/icd/radeon.json"), None).as_deref(), Some("dGPU"));
assert_eq!(
of(Some("/icd/radeon.json"), Some(0x15bf)).as_deref(),
Some("iGPU")
);
assert_eq!(of(Some("/icd/nvidia.json"), None).as_deref(), Some("nv"));
assert_eq!(of(Some("/icd/other.json"), None), None);
}
}
+16
View File
@@ -141,6 +141,22 @@ pub fn preflight(vm: &Vm, host: Host) -> Result<()> {
yourself to the kvm group (sudo usermod -aG kvm $USER, then log in again)"
);
}
// The library dies at its first import of guest RAM on a GPU whose driver refuses shared
// memory (gpu.rs).
let gpus = crate::gpu::list();
if let Some(g) = crate::gpu::chosen(&c.gpu, &gpus)
&& !g.runs_guests()
{
let other = match gpus.iter().any(|g| g.runs_guests()) {
true => format!(
"; give the VM another GPU: reims-ctl gpus lists them, and reims-ctl set {} \
--gpu NUMBER gives one",
c.name
),
false => "; this host has no GPU that can".into(),
};
bail!("{} {}{other}", g.name, crate::gpu::NO_SHARED_MEMORY);
}
}
Ok(())
}