[Vulkan] Add drop_guard to Buffer for externally owned buffers (#9452)

This commit is contained in:
AdrianEddy authored and GitHub committed 2026-05-03 16:53:29 +02:00
1 parent 1ab3b90289
commit cd80751e6b
3 files changed
+97 -44

No files matched your search

+6 -2
View File
@@ -350,9 +350,13 @@ pub struct DropGuard {
#[cfg(all(any(gles, vulkan), any(native, Emscripten)))]
impl DropGuard {
fn from_option(callback: Option<DropCallback>) -> Option<Self> {
callback.map(|callback| Self {
callback.map(Self::new)
}
fn new(callback: DropCallback) -> Self {
Self {
callback: Some(callback),
})
}
}
}
+54 -39
View File
@@ -235,7 +235,10 @@ impl super::DeviceShared {
buffer: &'a super::Buffer,
ranges: I,
) -> Option<impl 'a + Iterator<Item = vk::MappedMemoryRange<'a>>> {
let allocation = buffer.allocation.as_ref()?.lock();
let super::BufferOwnership::Managed(ref allocation) = buffer.ownership else {
return None;
};
let allocation = allocation.lock();
let mask = self.private_caps.non_coherent_map_mask;
Some(ranges.map(move |range| {
vk::MappedMemoryRange::default()
@@ -988,24 +991,35 @@ impl crate::Device for super::Device {
Ok(super::Buffer {
raw,
allocation: Some(Mutex::new(super::BufferMemoryBacking::Managed(allocation))),
ownership: super::BufferOwnership::Managed(Mutex::new(
super::BufferMemoryBacking::Managed(allocation),
)),
})
}
unsafe fn destroy_buffer(&self, buffer: super::Buffer) {
unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) };
if let Some(allocation) = buffer.allocation {
let allocation = allocation.into_inner();
self.counters.buffer_memory.sub(allocation.size() as isize);
match allocation {
super::BufferMemoryBacking::Managed(allocation) => {
let result = self.mem_allocator.lock().free(allocation);
if let Err(err) = result {
log::warn!("Failed to free buffer allocation: {err}");
match buffer.ownership {
super::BufferOwnership::Managed(allocation) => {
unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) };
let allocation = allocation.into_inner();
self.counters.buffer_memory.sub(allocation.size() as isize);
match allocation {
super::BufferMemoryBacking::Managed(allocation) => {
let result = self.mem_allocator.lock().free(allocation);
if let Err(err) = result {
log::warn!("Failed to free buffer allocation: {err}");
}
}
super::BufferMemoryBacking::VulkanMemory { memory, .. } => unsafe {
self.shared.raw.free_memory(memory, None);
},
}
super::BufferMemoryBacking::VulkanMemory { memory, .. } => unsafe {
self.shared.raw.free_memory(memory, None);
},
}
super::BufferOwnership::RawHandle => {
unsafe { self.shared.raw.destroy_buffer(buffer.raw, None) };
}
super::BufferOwnership::External(_drop_guard) => {
// The caller owns the `vk::Buffer` and its memory. Dropping
// `_drop_guard` at the end of this arm runs the cleanup callback.
}
}
@@ -1021,35 +1035,36 @@ impl crate::Device for super::Device {
buffer: &super::Buffer,
range: crate::MemoryRange,
) -> Result<crate::BufferMapping, crate::DeviceError> {
if let Some(ref allocation) = buffer.allocation {
let mut allocation = allocation.lock();
if let super::BufferMemoryBacking::Managed(ref mut allocation) = *allocation {
let is_coherent = allocation
.memory_properties()
.contains(vk::MemoryPropertyFlags::HOST_COHERENT);
Ok(crate::BufferMapping {
ptr: unsafe {
allocation
.mapped_ptr()
.unwrap()
.cast()
.offset(range.start as isize)
},
is_coherent,
})
} else {
crate::hal_usage_error("tried to map externally created buffer")
}
} else {
let super::BufferOwnership::Managed(ref allocation) = buffer.ownership else {
crate::hal_usage_error("tried to map external buffer")
}
};
let mut allocation = allocation.lock();
let super::BufferMemoryBacking::Managed(ref mut allocation) = *allocation else {
crate::hal_usage_error("tried to map externally created buffer")
};
let is_coherent = allocation
.memory_properties()
.contains(vk::MemoryPropertyFlags::HOST_COHERENT);
Ok(crate::BufferMapping {
ptr: unsafe {
allocation
.mapped_ptr()
.unwrap()
.cast()
.offset(range.start as isize)
},
is_coherent,
})
}
unsafe fn unmap_buffer(&self, buffer: &super::Buffer) {
if buffer.allocation.is_some() {
// gpu-allocator maps the buffer when allocated and unmap it when free'd
} else {
crate::hal_usage_error("tried to unmap external buffer")
match buffer.ownership {
super::BufferOwnership::Managed(_) => {
// gpu-allocator maps the buffer when allocated and unmaps it when free'd
}
super::BufferOwnership::RawHandle | super::BufferOwnership::External(_) => {
crate::hal_usage_error("tried to unmap external buffer")
}
}
}
+37 -3
View File
@@ -654,10 +654,28 @@ impl BufferMemoryBacking {
}
}
}
/// Describes who owns a [`Buffer`]'s `vk::Buffer` handle and its backing memory,
/// and therefore what cleanup is required when the buffer is destroyed.
#[derive(Debug)]
enum BufferOwnership {
/// wgpu-hal owns the `vk::Buffer` and its backing memory. On cleanup the buffer
/// handle is destroyed and the memory is released.
Managed(Mutex<BufferMemoryBacking>),
/// wgpu-hal owns the `vk::Buffer` handle but the backing memory is kept alive
/// by the caller. On cleanup only the buffer handle is destroyed.
RawHandle,
/// Caller owns the `vk::Buffer` and its backing memory. On cleanup the
/// [`crate::DropGuard`] runs the caller's cleanup callback and wgpu-hal touches
/// neither the handle nor the memory.
External(crate::DropGuard),
}
#[derive(Debug)]
pub struct Buffer {
raw: vk::Buffer,
allocation: Option<Mutex<BufferMemoryBacking>>,
// This field must be last, because it may contain a `DropGuard` which needs to be dropped after all other fields.
ownership: BufferOwnership,
}
impl Buffer {
/// # Safety
@@ -667,9 +685,25 @@ impl Buffer {
pub unsafe fn from_raw(vk_buffer: vk::Buffer) -> Self {
Self {
raw: vk_buffer,
allocation: None,
ownership: BufferOwnership::RawHandle,
}
}
/// # Safety
/// - `vk_buffer` must outlive the returned `Buffer`.
/// - wgpu-hal will NOT call `vkDestroyBuffer`; the caller remains responsible for the buffer handle's destruction.
/// The `drop_callback` runs when the `Buffer` drops and may be used to release caller-side bookkeeping.
/// - Externally imported buffers can't be mapped by `wgpu`.
pub unsafe fn from_raw_externally_owned(
vk_buffer: vk::Buffer,
drop_callback: crate::DropCallback,
) -> Self {
Self {
raw: vk_buffer,
ownership: BufferOwnership::External(crate::DropGuard::new(drop_callback)),
}
}
/// # Safety
/// - We will use this buffer and the buffer's backing memory range as if we have exclusive ownership over it, until the wgpu resource is dropped and the wgpu-hal object is cleaned up
/// - Externally imported buffers can't be mapped by `wgpu`
@@ -682,7 +716,7 @@ impl Buffer {
) -> Self {
Self {
raw: vk_buffer,
allocation: Some(Mutex::new(BufferMemoryBacking::VulkanMemory {
ownership: BufferOwnership::Managed(Mutex::new(BufferMemoryBacking::VulkanMemory {
memory,
offset,
size,