From cd80751e6b7310cebe5c611fa4b09129a71ef69c Mon Sep 17 00:00:00 2001 From: AdrianEddy Date: Sun, 3 May 2026 16:53:29 +0200 Subject: [PATCH] [Vulkan] Add `drop_guard` to `Buffer` for externally owned buffers (#9452) --- wgpu-hal/src/lib.rs | 8 ++- wgpu-hal/src/vulkan/device.rs | 93 ++++++++++++++++++++--------------- wgpu-hal/src/vulkan/mod.rs | 40 +++++++++++++-- 3 files changed, 97 insertions(+), 44 deletions(-) diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index 51815774d..8a93dcebe 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -350,9 +350,13 @@ pub struct DropGuard { #[cfg(all(any(gles, vulkan), any(native, Emscripten)))] impl DropGuard { fn from_option(callback: Option) -> Option { - callback.map(|callback| Self { + callback.map(Self::new) + } + + fn new(callback: DropCallback) -> Self { + Self { callback: Some(callback), - }) + } } } diff --git a/wgpu-hal/src/vulkan/device.rs b/wgpu-hal/src/vulkan/device.rs index c9d6a6438..f5f76de4e 100644 --- a/wgpu-hal/src/vulkan/device.rs +++ b/wgpu-hal/src/vulkan/device.rs @@ -235,7 +235,10 @@ impl super::DeviceShared { buffer: &'a super::Buffer, ranges: I, ) -> Option>> { - 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 { - 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") + } } } diff --git a/wgpu-hal/src/vulkan/mod.rs b/wgpu-hal/src/vulkan/mod.rs index 92f38d903..124df07c8 100644 --- a/wgpu-hal/src/vulkan/mod.rs +++ b/wgpu-hal/src/vulkan/mod.rs @@ -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), + /// 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>, + + // 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,