🐛 Let go of a refused Managed buffer's CPU copy at the refusal

The Vulkan platform keeps a refused no-copy buffer's deallocator unrun with
everything it holds (keep_unrun), as Metal runs no deallocator for a buffer
it does not make. MANAGED_BUFFER_CREATE's deallocator holds the CPU copy's
buffer, an rt handle that holds the device. A refused create therefore leaked
that handle for good, which could hold off let_go_of_device until its bound.

The decoder now shares the CPU copy's hold with the deallocator. Where the
make answers nil or raises, it takes the hold back once the platform's call
has returned, outside every callback of rt's, and lets go of it as any hold
goes, the buffer on the surface worker. The forgotten deallocator keeps an
emptied slot and the region, which is guest-visible. No other deallocator
handed to a refusable no-copy make holds an rt handle: the others hold the
region, a pages view, a guest-RAM lease or a pool piece's keep.

The testkit now keeps a refused no-copy buffer's deallocator unrun, as the
Vulkan platform does, rather than dropping it (World::refused_deallocators).
A refused heap's deallocator is still dropped, as the platform drops it.
Nothing changes for the guest: its CPU copy's object holds the buffer.
This commit is contained in:
Anees Iqbal committed 2026-11-20 18:32:54 -08:00
1 parent 415d453172
commit b68085c6b9
5 files changed
+113 -15

No files matched your search

@@ -32,6 +32,9 @@ use crate::core::raise::{OnFault, RaiseResult};
/// ([`GpuDevice::new_heap_over_host_memory`]): it runs once the platform no longer reads or
/// writes the bytes, which may be well after the object went (the Vulkan platform runs it from
/// rt's release of its import of them), so it holds what keeps them mapped. `None` is a nil block.
/// Where a buffer's make answers nil, the platform may keep its deallocator unrun for good, with
/// all it holds, as Metal runs none for a buffer it does not make (the Vulkan platform's does): a
/// caller lets go itself of what it handed it that is not to be kept so, a platform handle.
pub type NoCopyDeallocator = Box<dyn FnOnce() + Send>;
thread_local! {
@@ -219,7 +219,8 @@ impl GpuDevice<FakePlatform> for Fk<kind::Device> {
deallocator: Option<NoCopyDeallocator>,
) -> RaiseResult<Option<<FakePlatform as Platform>::Buffer>> {
let (pointer, length) = (bytes.ptr(), bytes.len());
self.make(
let mut deallocator = deallocator;
let made = self.make(
Policy::On(on),
"newBufferWithBytesNoCopy:length:options:deallocator:",
vec![
@@ -231,11 +232,16 @@ impl GpuDevice<FakePlatform> for Fk<kind::Device> {
|w| {
let b = new_buffer(w, length, options, Backing::At(pointer), None)?;
if let Model::Buffer(m) = &mut b.state().model {
m.deallocator = deallocator;
m.deallocator = deallocator.take();
}
Some(b)
},
)
);
// Refused: kept unrun, as the Vulkan platform keeps it (`World::refused_deallocators`).
if let Some(deallocator) = deallocator {
self.world().refused(Box::new(deallocator));
}
made
}
fn new_buffer_of_length(
@@ -719,17 +725,22 @@ impl GpuDevice<FakePlatform> for Fk<kind::Device> {
length,
pinned_gpu_address,
contents,
deallocator,
mut deallocator,
..
} = desc;
self.make(Policy::Caught, "newBufferWithDescriptor:", vec![arg], |w| {
let made = self.make(Policy::Caught, "newBufferWithDescriptor:", vec![arg], |w| {
let backing = contents.map_or(Backing::Fresh, |c| Backing::At(c.ptr()));
let b = new_buffer(w, length, opts, backing, w.kept_pin(pinned_gpu_address))?;
if let Model::Buffer(m) = &mut b.state().model {
m.desc_deallocator = deallocator.map(DescDeallocator);
m.desc_deallocator = deallocator.take().map(DescDeallocator);
}
Some(b)
})
});
// Refused: kept unrun, as the Vulkan platform keeps it (`World::refused_deallocators`).
if let Some(deallocator) = deallocator {
self.world().refused(Box::new(deallocator));
}
made
}
/// A heap of the value's size, with its options folded as Metal's heap descriptor folds
@@ -929,6 +929,9 @@ pub struct World {
/// ([`World::run_deallocators_late`]), in the order the objects died; `None` while they run at
/// the death.
late_deallocators: Mutex<Option<Vec<NoCopyDeallocator>>>,
/// The deallocators of the no-copy buffers the devices refused, kept unrun, in the order
/// refused ([`World::refused_deallocators`]).
refused_deallocators: Mutex<Vec<Box<dyn Send>>>,
/// The handles let go of while a deallocator ran, each its class and object, in the order
/// they went ([`World::handles_dropped_in_deallocators`]).
dropped_in_deallocators: Mutex<Vec<(&'static str, ObjId)>>,
@@ -1074,6 +1077,7 @@ impl World {
release_dies: Mutex::new(Vec::new()),
release_holds: Mutex::new(Vec::new()),
late_deallocators: Mutex::new(None),
refused_deallocators: Mutex::new(Vec::new()),
dropped_in_deallocators: Mutex::new(Vec::new()),
held_submissions: Mutex::new(None),
release_at_commit: AtomicBool::new(false),
@@ -1436,6 +1440,22 @@ impl World {
ran
}
/// How many no-copy buffers the devices refused, their deallocators kept unrun with all they
/// hold for the world's life, as the Vulkan platform keeps them, since Metal runs no
/// deallocator for a buffer it does not make (`rt_platform::buffer`'s `keep_unrun`):
/// `newBufferWithBytesNoCopy:length:options:deallocator:`'s, and a no-copy
/// `newBufferWithDescriptor:`'s. A heap's over host memory, refused, is dropped, as the
/// Vulkan platform drops it.
pub fn refused_deallocators(&self) -> usize {
self.refused_deallocators.lock().len()
}
/// Keeps the deallocator of a no-copy buffer a device refused, unrun
/// ([`World::refused_deallocators`]).
pub(crate) fn refused(&self, deallocator: Box<dyn Send>) {
self.refused_deallocators.lock().push(deallocator);
}
/// The handles let go of while a deallocator ran, on its thread, each its class and object,
/// in the order they went: what the Vulkan platform's deallocators may not do, as rt runs them
/// from its release of an import, which drops no handle of rt's ([`run_deallocator`]).
@@ -1316,7 +1316,10 @@ fn run(slot: &Slot) {
}
/// The deallocator in `slot`, never to run: taken out, and its captures kept for good, as Metal
/// runs none for a buffer it does not make.
/// runs none for a buffer it does not make. A caller lets go itself of what it handed one that is
/// not to be kept so, a handle of the platform's among it, once the make answered nil (the
/// reims-graphics decoder's `MANAGED_BUFFER_CREATE`): rt holds nothing of ours after an `Err`,
/// and its call has returned by then.
fn keep_unrun(slot: &Slot) {
if let Some(deallocator) = slot.lock().take() {
std::mem::forget(deallocator);
@@ -102,6 +102,7 @@ use reims_vgpu_vulkan::core::platform::types::{MtlOrigin, MtlRegion, MtlSize, Ns
use reims_vgpu_vulkan::core::platform::values::{BufferDesc, OptionSet};
use reims_vgpu_vulkan::core::platform::{Handle, HostRange, Platform};
use reims_vgpu_vulkan::core::raise::{OnFault, RaiseResult};
use reims_vgpu_vulkan::core::sync::Mutex;
use super::surface_pages::TEARDOWN;
use super::tables::{Entry, GuestBytes};
@@ -170,8 +171,10 @@ pub(crate) struct ManagedCopy<P: Platform> {
/// deallocator, so the bytes stay mapped until then ([`GraphicsDecoder::buffer_over_bytes`]).
enum BytesHold<P: Platform> {
/// The `Shared` buffer whose contents the bytes are (`MANAGED_BUFFER_CREATE`), which holds
/// what keeps them mapped: its block of the region, its heap, or a pages block's view.
Buffer(CopyBufferHold<P>),
/// what keeps them mapped: its block of the region, its heap, or a pages block's view. Shared
/// with the create, which takes it back where the platform refuses the buffer
/// ([`CopyBufferHold`]).
Buffer(Arc<Mutex<Option<CopyBufferHold<P>>>>),
/// What keeps the bytes of the heap they lie in mapped, where it lies over any but the
/// region's ([`Entry::ram_kept`], `BUFFER_MANAGED_AT_OFFSET`).
Kept {
@@ -197,6 +200,14 @@ enum BytesHold<P: Platform> {
/// platform's handle of it and rt's own, and rt tears a device down only once every handle of it
/// and of every object made from it is gone, so a hold still in a release keeps its device from
/// teardown until the release has run and the worker has let go of the buffer.
///
/// Where the platform refuses the no-copy buffer, it may keep the deallocator unrun for good,
/// with all it holds: the Vulkan platform does, as Metal runs no deallocator for a buffer it does
/// not make (`rt_platform::buffer`'s `keep_unrun`). A buffer kept so would hold its device for
/// good, past the platform's let-go of it. So the create takes the hold back from the slot it
/// shares with the deallocator once the platform's call has returned, outside every callback of
/// rt's, and lets go of it as any hold goes, the buffer on the surface worker; the deallocator
/// keeps an emptied slot. The guest sees nothing of it: its CPU copy's object holds the buffer.
struct CopyBufferHold<P: Platform> {
/// The CPU copy's guest object, which names it where its release is refused.
obj_id: u64,
@@ -532,15 +543,23 @@ impl<P: Platform> GraphicsDecoder<P> {
let cpu = cpu.clone_ref();
let pin = (m.gpu_address != 0).then_some(m.gpu_address);
let kind = super::unkept::Kind::managed(self.unified());
let keep = BytesHold::Buffer(CopyBufferHold {
let hold = Arc::new(Mutex::new(Some(CopyBufferHold {
obj_id: m.cpu_buffer_obj_id,
buffer: Some(cpu),
worker: Arc::clone(&self.shared.surface_worker),
});
let Some(buffer) = kind.making(|| {
})));
let keep = BytesHold::Buffer(Arc::clone(&hold));
let made = kind.making(|| {
self.buffer_over_bytes(device, bytes, m.length, options, pin, keep, zero_from)
})?
else {
});
// Refused: the hold is taken back from a deallocator the platform may keep unrun
// ([`CopyBufferHold`]).
if !matches!(made, Ok(Some(_))) {
let taken = hold.lock().take();
drop(taken);
}
drop(hold);
let Some(buffer) = made? else {
return Ok(Err(DecodeError::Refused));
};
let made = buffer.gpu_address();
@@ -2617,6 +2636,48 @@ mod tests {
}
}
/// Where the platform refuses a `MANAGED_BUFFER_CREATE`'s buffer and keeps its deallocator
/// unrun, as the Vulkan platform does (the testkit's, `World::refused_deallocators`), the
/// create lets go of the CPU copy's buffer it handed the deallocator, wherever the copy lies,
/// so no handle of the platform's is kept for good; what else the deallocator holds is kept
/// with it, the region among it, and no deallocator runs.
#[test]
fn a_refused_managed_buffer_lets_go_of_its_cpu_copy_s_buffer_and_runs_no_deallocator() {
let (mut r, ram, page) = pages_rig();
let copies = shared_copies(&mut r, &ram, page);
let refused = r.p.world().refused_deallocators();
for (i, (cpu, _)) in copies.into_iter().enumerate() {
let obj_id = 60 + i as u64;
let buffer = match r.dec.named(cpu) {
Some(ObjHandle::Buffer(b)) => Arc::clone(b.obj()),
_ => panic!("no buffer {cpu:#x}"),
};
r.dec.surface_worker().flush();
let (handles, regions) = (buffer.handle_count(), Arc::strong_count(&r.region));
r.p.script().push("newBufferWithDescriptor:", Step::Nil);
assert_eq!(
r.send(&managed_over(obj_id, cpu, 0x300, MANAGED)),
Err(DecodeError::Refused),
"copy {cpu}"
);
r.dec.surface_worker().flush();
assert_eq!(buffer.handle_count(), handles, "copy {cpu}: let go of");
assert_eq!(
r.p.world().refused_deallocators(),
refused + i + 1,
"copy {cpu}: its deallocator kept unrun"
);
assert_eq!(
Arc::strong_count(&r.region),
regions + 1,
"copy {cpu}: the region kept with it"
);
assert!(r.dec.named(cpu).is_some(), "copy {cpu}: its object kept");
}
let dropped = r.p.world().handles_dropped_in_deallocators();
assert!(dropped.is_empty(), "{dropped:?}");
}
/// A `MANAGED_BUFFER_CREATE` names a `Shared` buffer over the guest's memory the sender
/// holds, of at least its length: none, a heap, a `Managed` buffer, or a shorter one is a bad
/// reference; a buffer of no bytes is malformed; one not `Managed` is refused.