🐛 Reserve the guest's texture ids as the device is made

On Linux, a GPU whose imports of views need their pages mapped from their
files (the Iris Xe on ANV, NVIDIA) runs the fold probe as its device is
adopted, wherever its driver's fold verdict is not kept yet: a user's first
boot, and the first boot after each GPU driver or kernel update, as the
verdict's key holds both. The probe makes a command queue on the device
before the graphics device reserves the guest's texture ids, and Metal, as
the runtime imitates it, then keeps the texture pool's first range beside
the reservation and hands those ids out twice: the host's drawables and
cursor took ids 1 to 16 of the guest's first chunk (a cold boot on the
Iris logged "a texture of the host's took resource id 1, one of the
guest's").

The graphics device now tells the platform the guest's ids before it asks
for its device (ApiPlatform::present_guest_texture_ids), and the Vulkan
platform reserves them as a new device's first call in adopt, before the
library's probes and checks; the graphics device's own reservation of
exactly those ids is answered at once. A device adopted before the
declaration reserves nothing there, and the graphics device reserves as
before. The new test makes a queue between the device's making and the
graphics device and finds no plain texture inside the guest's ids.
This commit is contained in:
Anees Iqbal committed 2026-11-12 16:17:20 -08:00
1 parent f833ad9872
commit 61076b4fd0
8 files changed
+174 -18

No files matched your search

+49 -12
View File
@@ -198,6 +198,9 @@ pub struct DeviceObject {
pub(crate) threads: crate::let_go::DeviceThreads,
/// Its answers of [`GpuDevice::linear_rows_pitch`] so far, by row bytes and rows.
pub(crate) rows_pitches: Mutex<BTreeMap<(u64, u64), Option<u64>>>,
/// The guest's texture resource IDs it reserved as it was adopted, where the process declared
/// them first (`crate::platform::present_guest_texture_ids`).
guest_texture_ids: Option<std::ops::RangeInclusive<u64>>,
}
impl Drop for DeviceObject {
@@ -340,23 +343,26 @@ pub(crate) fn take_if_only_kept()
Ok((std::mem::take(&mut *devices), libraries))
}
/// The handle of `raw`, a device the runtime made: the object of the same device made before, or
/// a new one, kept. The process's first device's sampler ID pool is the one Metal's sampler mempool
/// follows ([`metal_space::count_sampler_ids`]). A new device's class joins the process's
/// placement of degradations ([`crate::answer::native::device_made`]), and its warm pass runs
/// over the pipeline records earlier processes kept ([`crate::records`]), in the background, but
/// in a test build. Its work counts go to the log where its filter names their target
/// ([`crate::work_log`]), its GPU is kept awake while the guest draws ([`crate::awake`]), and the
/// runtime's check of textures over host pages starts ([`start_in_place_checks`]). The exit gate's
/// hook is registered, after the device's driver was loaded ([`crate::exit_gate`]): every process
/// that holds a device of the process's, a test's or a host's, waits at its exit for the library's
/// GPU work in progress.
/// The handle of `raw`, a device the runtime made: the object of the same device made before, or a
/// new one, kept. A new device first reserves the guest's texture resource IDs where the process
/// declared them ([`reserve_guest_texture_ids`]), before any work of the library's below makes a
/// command queue or a texture on it. The process's first device's sampler ID pool is the one
/// Metal's sampler mempool follows ([`metal_space::count_sampler_ids`]). A new device's class joins
/// the process's placement of degradations ([`crate::answer::native::device_made`]), and its warm
/// pass runs over the pipeline records earlier processes kept ([`crate::records`]), in the
/// background, but in a test build. Its work counts go to the log where its filter names their
/// target ([`crate::work_log`]), its GPU is kept awake while the guest draws ([`crate::awake`]),
/// and the runtime's check of textures over host pages starts ([`start_in_place_checks`]). The exit
/// gate's hook is registered, after the device's driver was loaded ([`crate::exit_gate`]): every
/// process that holds a device of the process's, a test's or a host's, waits at its exit for the
/// library's GPU work in progress.
pub fn adopt(raw: rt::Device) -> VulkanDevice {
let id = registry_id(&raw);
let mut devices = DEVICES.lock();
if let Some((_, kept)) = devices.iter().find(|(at, _)| *at == id) {
return kept.clone_ref();
}
let guest_texture_ids = reserve_guest_texture_ids(&raw);
crate::exit_gate::arm();
metal_space::count_sampler_ids(&raw);
crate::answer::native::device_made(raw.properties());
@@ -378,11 +384,33 @@ pub fn adopt(raw: rt::Device) -> VulkanDevice {
caps: OnceLock::new(),
threads,
rows_pitches: Mutex::default(),
guest_texture_ids,
});
devices.push((id, made.clone_ref()));
made
}
/// Reserves the guest's texture resource IDs on `raw` where the process declared them
/// (`crate::platform::present_guest_texture_ids`), the device's first call, before the library's
/// own work on it makes a command queue or a texture ([`adopt`]): the IDs it reserved, or `None`
/// where none were declared or the runtime refused them, which is logged at error.
fn reserve_guest_texture_ids(raw: &rt::Device) -> Option<std::ops::RangeInclusive<u64>> {
let ids = crate::platform::guest_texture_ids()?;
let reserved: Vec<rt::ResourceId> = ids.clone().map(rt::ResourceId).collect();
match raw.reserve_resource_ids(rt::ResourceIdKind::Texture, &reserved) {
Ok(()) => Some(ids),
Err(error) => {
log::error!(
"the guest's texture resource ids {} to {} are not reserved as the device is \
made ({error:?}): its textures may share ids with the host's",
ids.start(),
ids.end()
);
None
}
}
}
/// Starts `raw`'s check of textures over host pages on the runtime's thread for it, where its
/// verdicts are pending: where no record of an earlier process of the same driver and runtime
/// holds them, and the policy takes such textures in place (`REIMS_VGPU_EXACT` names no
@@ -1812,9 +1840,17 @@ impl GpuDevice<VulkanPlatform> for VulkanDevice {
/// an ID of 2^32 or more it drops whole, leaving the reservation to a later call, as Metal
/// does. An ID the runtime refuses dies: a texture or sampler state ID of 2^28 or more, which
/// ended Metal's process, or a texture ID past what the device's texture arrays hold, which
/// Metal takes; so does any other type, which core never reserves.
/// Metal takes; so does any other type, which core never reserves. Textures of exactly the
/// guest's IDs the device reserved as it was adopted ([`adopt`]) are answered at once: they
/// are reserved, and the runtime would ignore the call as a late one.
fn reserve_resource_indices(&self, resource_type: u64, indices: &[u64]) -> RaiseResult<()> {
let sel = "reserveResourceIndicesForResourceType:indices:indexCount:";
if resource_type == 0
&& let Some(ids) = &self.guest_texture_ids
&& indices.iter().copied().eq(ids.clone())
{
return Ok(());
}
let kind = match resource_type {
0 => rt::ResourceIdKind::Texture,
1 => rt::ResourceIdKind::SamplerState,
@@ -2746,6 +2782,7 @@ pub(crate) mod tests {
awake: Default::default(),
threads: Default::default(),
rows_pitches: Mutex::default(),
guest_texture_ids: None,
})
}
@@ -2637,6 +2637,7 @@ pub(crate) fn device_with_own_cache() -> (VulkanDevice, OwnCache) {
awake: Default::default(),
threads: Default::default(),
rows_pitches: crate::core::sync::Mutex::default(),
guest_texture_ids: None,
});
(device, cache)
}
+25
View File
@@ -319,6 +319,31 @@ pub fn present_mac_class(class: rt::MacClass) -> Option<rt::MacClass> {
*MAC_CLASS.get_or_init(|| Some(class))
}
/// The texture resource IDs a guest places its textures at, which every device the process adopts
/// after their declaration reserves first ([`present_guest_texture_ids`]).
static GUEST_TEXTURE_IDS: OnceLock<std::ops::RangeInclusive<u64>> = OnceLock::new();
/// Declares the texture resource IDs the process's guest places its textures at: every device the
/// process adopts from now on reserves them as its first call (`gpu::device::adopt`), before the
/// library's own work on it makes a command queue or a texture (on Linux, the fold probe's queue
/// as the device learns its imports of views, `crate::os::learn_view_imports`). Metal takes a
/// texture reservation only before the device's first texture, and one made after the device's
/// first command queue keeps the pool's first range beside it, handing those IDs out twice; the
/// runtime imitates both. A later call of the device's for exactly these IDs is then answered at
/// once ([`crate::gpu::device::VulkanDevice`]'s `reserve_resource_indices`). A device adopted
/// before the declaration reserves nothing as it is adopted. The first declaration fixes the IDs
/// for the process; answers the IDs it fixed.
pub fn present_guest_texture_ids(
ids: std::ops::RangeInclusive<u64>,
) -> std::ops::RangeInclusive<u64> {
GUEST_TEXTURE_IDS.get_or_init(|| ids).clone()
}
/// The guest's texture resource IDs, where declared ([`present_guest_texture_ids`]).
pub(crate) fn guest_texture_ids() -> Option<std::ops::RangeInclusive<u64>> {
GUEST_TEXTURE_IDS.get().cloned()
}
/// The options every device is made with: the runtime's defaults, whose loader search finds
/// Homebrew's (`vulkan-loader`, beside its `molten-vk`), with the window system's extensions where
/// a display's window presents through Vulkan (on Linux, [`crate::os::add_window_extensions`]), the
+8 -2
View File
@@ -326,9 +326,12 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
// before it makes any queue. A host with no GPU device cannot run the lane. The
// platform learns the guest's architecture first, so the device gives the answers of
// the Macs the guest's frameworks were written against (`GuestArch::mac_class`).
// It learns the guest's texture ids too, which a platform whose device makes queues
// or textures of its own as it is made reserves there first.
platform.present_guest(config.guest_arch);
platform.present_guest_texture_ids(guest_texture_ids());
let gpu_device = platform.metal_device(None).ok_or(Error::HostResources)?;
// Before anything else makes a queue or a texture on it.
// Before anything else of this device makes a queue or a texture on it.
reserve_guest_texture_ids(platform.as_ref(), &gpu_device);
let clock = Arc::clone(&platform);
let pool = CompilePool::new(Box::new(move || clock.clock().now_mono()));
@@ -3037,7 +3040,10 @@ const RESERVATION_CHECKS: usize = 16;
/// Metal takes a texture reservation only before the device's first texture (it ignores a later
/// one, logging so), and one after the device's first command queue keeps the pool's first range
/// beside the ids it leaves, which it hands out twice. So this is the first call on the device,
/// and a few plain textures check it took: one inside the guest's ids is logged as an error.
/// and a few plain textures check it took: one inside the guest's ids is logged as an error. A
/// platform whose device makes a queue or texture of its own as it is made reserves the ids there
/// first, told them before the device ([`ApiPlatform::present_guest_texture_ids`]), and answers
/// this call at once.
fn reserve_guest_texture_ids<P: Platform>(platform: &P, device: &P::Device) {
let ids: Vec<u64> = guest_texture_ids().collect();
if let Err(raise) = refusing(|| device.reserve_resource_indices(0, &ids)) {
+52
View File
@@ -288,6 +288,58 @@ fn on_vulkan_guest_texture_ids_are_kept_from_the_host_s() {
}
}
/// On the Vulkan platform, a command queue made on the device after it is made but before the
/// graphics device's reservation, as the device's fold probe makes one where a GPU's imports of
/// views need their pages' files and its fold verdict is not kept yet (a cold cache, a new driver
/// or kernel), leaves every guest texture id to the guest: the platform was told the ids first and
/// reserved them as the device was made, so no plain texture of the host's takes one. Without that
/// reservation Metal, as the runtime imitates, hands the pool's first range out twice past the
/// queue. Each test runs in a process of its own, so the device is made here
#[test]
fn on_vulkan_a_queue_before_the_graphics_device_takes_no_guest_texture_id() {
use reims_vgpu_vulkan::core::platform::resource::Texture as _;
use reims_vgpu_vulkan::core::platform::values::TextureDesc;
let platform = crate::singleton::platform();
platform.present_guest_texture_ids(guest_texture_ids());
let gpu = platform.metal_device(None).unwrap();
let queue = gpu.new_command_queue().expect("a command queue");
let config = GraphicsConfig {
callbacks: GraphicsCallbacks {
raise_interrupt: None,
..GraphicsCallbacks::default()
},
window: None,
memory_map: None,
guest_arch: GuestArch::X86_64,
};
let _device = GraphicsDevice::with_platform(Arc::clone(&platform), config).unwrap();
let plain_desc = platform.texture_descriptor(&TextureDesc {
pixel_format: 80,
width: 4,
height: 4,
usage: 1,
resource_options: Some(0x20),
..TextureDesc::default()
});
let plain: Vec<_> = (0..256)
.map(|_| {
gpu.new_texture(OnFault::Return, &plain_desc)
.unwrap()
.unwrap()
})
.collect();
let inside: Vec<u64> = plain
.iter()
.map(|t| t.gpu_resource_id())
.filter(|id| guest_texture_ids().contains(id))
.collect();
assert!(
inside.is_empty(),
"plain textures took the guest's ids {inside:?}"
);
drop(queue);
}
/// The variable naming the guest architecture of [`the_guest_s_class_decides_the_answers`]'s
/// child, `x86_64` or `arm64`.
const GUEST_CLASS_CHILD: &str = "RVG_GUEST_CLASS_CHILD";
+9
View File
@@ -39,6 +39,15 @@ pub trait ApiPlatform: Platform {
let _ = guest;
}
/// Tells the platform the texture resource IDs a graphics device keeps for its guest
/// (`crate::graphics`'s `guest_texture_ids`), before the device asks for its Metal device
/// ([`ApiPlatform::metal_device`]): a platform whose devices make command queues or textures
/// of their own as they are made reserves them there first, before those, and answers the
/// graphics device's own reservation of them at once. Nothing by default.
fn present_guest_texture_ids(&self, ids: std::ops::RangeInclusive<u64>) {
let _ = ids;
}
/// Copies the whole of `texture` into `dst`: `height` rows of `width * 4` bytes, each
/// `bytes_per_row` after the last. The caller has checked that `dst` holds them.
fn read_pixels(&self, texture: &Self::Texture, dst: &mut [u8], bytes_per_row: usize);
+21
View File
@@ -54,6 +54,27 @@ impl ApiPlatform for VulkanPlatform {
}
}
/// The guest's texture resource IDs, declared for every device the process makes from now on
/// (`reims_vgpu_vulkan::platform::present_guest_texture_ids`), which reserves them as its
/// first call: on Linux a device that needs imported pages mapped from their files makes a
/// command queue of its own as it is made where its driver's fold verdict is not kept yet (a
/// cold cache, a new driver or kernel), which would otherwise come before the graphics
/// device's reservation, and Metal, as the runtime imitates, then hands the pool's first
/// range out twice. The first declaration fixes the IDs; a later one of others is warned of.
fn present_guest_texture_ids(&self, ids: std::ops::RangeInclusive<u64>) {
let fixed = reims_vgpu_vulkan::platform::present_guest_texture_ids(ids.clone());
if fixed != ids {
log::warn!(
"the process's devices reserve texture ids {} to {} as they are made, fixed before \
this graphics device's {} to {}",
fixed.start(),
fixed.end(),
ids.start(),
ids.end()
);
}
}
/// Memory of the library's own, which it frees through the platform's VM as the region
/// drops, so the unmap waits until the runtime has freed every import of its pages: the
/// region's last reference can go in a no-copy buffer's deallocator, which the runtime runs
+9 -4
View File
@@ -1840,10 +1840,15 @@ than the 1024 contexts the GPU addresses hold (a busy desktop held 74,
"Contexts"), where small chunks let 1020; the pool's ids are as many either way.
The host reserves the pool's ids on its device as it makes the graphics device,
its first call on the device (`reserve_guest_texture_ids`,
`crates/reims-vgpu/src/graphics.rs`). Metal hands the id of a texture placed at
one out again to plain allocation, so without it the guest's textures would share
ids with the host's own (the window's drawables, the cursor), and a texture placed
past the table a fresh device has corrupts Metal's heap (placements from 10000 up
`crates/reims-vgpu/src/graphics.rs`). The Vulkan platform is told the ids before
the device is made and reserves them as the device's first call, before its own
probes: on Linux, a GPU whose imports of views need their pages mapped from
their files makes a command queue as its device is made, where its driver's
fold verdict is not kept yet (a cold cache, a new driver or kernel). Metal hands
the id of a texture placed at one out again to plain allocation, so without it
the guest's textures would share ids with the host's own (the window's
drawables, the cursor), and a texture placed past the table a fresh device has
corrupts Metal's heap (placements from 10000 up
crashed some runs). The reservation keeps the ids from plain allocation and grows
the table to hold them (measured on an M3 Max, macOS 27; metal2vulkan imitates
both). Metal takes one only before the device's first texture, and once the device