#[cfg(oa_profile = "compatibility")]
use std::sync::Arc;
use std::sync::Mutex;
#[cfg(oa_profile = "compatibility")]
use std::sync::atomic::AtomicU32;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::{Error, Result};
use super::super::physical::DeviceLimits;
#[cfg(oa_profile = "compatibility")]
use crate::runtime::Device;
pub(in crate::runtime::device) struct DescriptorHeap {
#[cfg(oa_profile = "core")]
pool: vk::DescriptorPool,
layout: vk::DescriptorSetLayout,
#[cfg(oa_profile = "compatibility")]
bounded_layouts: Vec<vk::DescriptorSetLayout>,
set: vk::DescriptorSet,
buffer_capacity: u32,
image_capacity: u32,
write_count: AtomicU64,
free_storage_indices: Mutex<Vec<u32>>,
#[cfg(oa_profile = "core")]
free_image_indices: Mutex<Vec<u32>>,
#[cfg(oa_profile = "compatibility")]
virtual_next: AtomicU32,
}
impl DescriptorHeap {
pub(in crate::runtime::device) fn capacities(&self) -> (u32, u32) {
(self.buffer_capacity, self.image_capacity)
}
pub(in crate::runtime::device) fn write_count(&self) -> u64 {
self.write_count.load(Ordering::Relaxed)
}
#[cfg(oa_profile = "core")]
pub(in crate::runtime::device) fn new(
device: &vk::Device,
mut limits: DeviceLimits,
) -> Result<Self> {
let minimum_capacity = limits.storage_buffer_descriptors.min(65_536);
loop {
match Self::try_new(device, limits) {
Ok(heap) => return Ok(heap),
Err(_) if limits.storage_buffer_descriptors > minimum_capacity => {
limits.storage_buffer_descriptors =
(limits.storage_buffer_descriptors / 2).max(minimum_capacity);
}
Err(error) => return Err(error),
}
}
}
#[cfg(oa_profile = "core")]
fn try_new(device: &vk::Device, limits: DeviceLimits) -> Result<Self> {
let buffer_binding = vk::DescriptorSetLayoutBinding::new()
.set_binding(0)
.set_descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.set_descriptor_count(limits.storage_buffer_descriptors)
.set_stage_flags(vk::ShaderStageFlagBits::COMPUTE_BIT);
let image_binding = vk::DescriptorSetLayoutBinding::new()
.set_binding(1)
.set_descriptor_type(vk::DescriptorType::STORAGE_IMAGE)
.set_descriptor_count(limits.storage_image_descriptors)
.set_stage_flags(vk::ShaderStageFlagBits::COMPUTE_BIT);
let bindings = [buffer_binding, image_binding];
let binding_flags = [
vk::DescriptorBindingFlagBits::UPDATE_AFTER_BIND_BIT
| vk::DescriptorBindingFlagBits::UPDATE_UNUSED_WHILE_PENDING_BIT
| vk::DescriptorBindingFlagBits::PARTIALLY_BOUND_BIT,
vk::DescriptorBindingFlagBits::UPDATE_AFTER_BIND_BIT
| vk::DescriptorBindingFlagBits::UPDATE_UNUSED_WHILE_PENDING_BIT
| vk::DescriptorBindingFlagBits::PARTIALLY_BOUND_BIT,
];
let mut binding_flags_info = vk::DescriptorSetLayoutBindingFlagsCreateInfo::new()
.set_binding_flags(&binding_flags)
.map_err(Error::from)?;
let layout_info = vk::DescriptorSetLayoutCreateInfo::new()
.set_flags(vk::DescriptorSetLayoutCreateFlagBits::UPDATE_AFTER_BIND_POOL_BIT)
.set_bindings(&bindings)
.map_err(Error::from)?
.push_next(&mut binding_flags_info)
.map_err(Error::from)?;
let layout =
unsafe { device.create_descriptor_set_layout(&layout_info, None) }.map_err(|source| {
Error::backend_failure("Vulkan", "compute descriptor-layout creation", source)
})?;
let pool_sizes = [
vk::DescriptorPoolSize::new()
.set_type(vk::DescriptorType::STORAGE_BUFFER)
.set_descriptor_count(limits.storage_buffer_descriptors),
vk::DescriptorPoolSize::new()
.set_type(vk::DescriptorType::STORAGE_IMAGE)
.set_descriptor_count(limits.storage_image_descriptors),
];
let pool_info = vk::DescriptorPoolCreateInfo::new()
.set_flags(vk::DescriptorPoolCreateFlagBits::UPDATE_AFTER_BIND_BIT)
.set_max_sets(1)
.set_pool_sizes(&pool_sizes)
.map_err(Error::from)?;
let pool = match unsafe { device.create_descriptor_pool(&pool_info, None) } {
Ok(pool) => pool,
Err(source) => {
destroy_layout(device, layout);
return Err(Error::backend_failure(
"Vulkan",
"compute descriptor-pool creation",
source,
));
}
};
let layouts = [layout];
let allocate_info = vk::DescriptorSetAllocateInfo::new()
.set_descriptor_pool(pool)
.set_set_layouts(&layouts)
.map_err(Error::from)?;
let mut sets = [vk::DescriptorSet::default()];
match unsafe { device.allocate_descriptor_sets(&allocate_info, &mut sets) } {
Ok(()) => {}
Err(source) => {
destroy_pool(device, pool);
destroy_layout(device, layout);
return Err(Error::backend_failure(
"Vulkan",
"compute descriptor-set allocation",
source,
));
}
};
let set = sets[0];
Ok(Self {
pool,
layout,
write_count: AtomicU64::new(0),
set,
buffer_capacity: limits.storage_buffer_descriptors,
image_capacity: limits.storage_image_descriptors,
free_storage_indices: Mutex::new((0..limits.storage_buffer_descriptors).rev().collect()),
free_image_indices: Mutex::new((0..limits.storage_image_descriptors).rev().collect()),
})
}
#[cfg(oa_profile = "compatibility")]
pub(in crate::runtime::device) fn new(device: &vk::Device, limits: DeviceLimits) -> Result<Self> {
let capacity = limits.storage_buffer_descriptors;
if capacity == 0 {
return Err(Error::missing_capability(
"bounded descriptors require a nonzero capacity",
));
}
let mut bounded_layouts = Vec::new();
for count in 1..=capacity {
let binding = vk::DescriptorSetLayoutBinding::new()
.set_binding(0)
.set_descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.set_descriptor_count(count)
.set_stage_flags(vk::ShaderStageFlagBits::COMPUTE_BIT);
let layout_info = vk::DescriptorSetLayoutCreateInfo::new()
.set_bindings(std::slice::from_ref(&binding))
.map_err(Error::from)?;
let layout = unsafe { device.create_descriptor_set_layout(&layout_info, None) };
match layout {
Ok(layout) => bounded_layouts.push(layout),
Err(source) => {
for layout in bounded_layouts {
destroy_layout(device, layout);
}
return Err(Error::backend_failure(
"Vulkan",
"bounded descriptor-layout creation",
source,
));
}
}
}
let layout = bounded_layouts[0];
Ok(Self {
layout,
bounded_layouts,
set: vk::DescriptorSet::default(),
buffer_capacity: capacity,
image_capacity: 0,
write_count: AtomicU64::new(0),
free_storage_indices: Mutex::new(Vec::new()),
virtual_next: AtomicU32::new(0),
})
}
#[cfg(oa_profile = "compatibility")]
pub(in crate::runtime::device) fn bind_storage_buffer(
&self,
device: &vk::Device,
buffer: vk::Buffer,
size: vk::DeviceSize,
) -> Result<u32> {
let _ = (device, buffer, size);
if let Some(index) = self
.free_storage_indices
.lock()
.map_err(|_| Error::internal("bounded descriptor identity allocator lock poisoned"))?
.pop()
{
return Ok(index);
}
self
.virtual_next
.try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
next.checked_add(1)
})
.map_err(|_| Error::resource_exhausted("bounded storage identity space exhausted"))
}
#[cfg(oa_profile = "core")]
pub(in crate::runtime::device) fn bind_storage_buffer(
&self,
device: &vk::Device,
buffer: vk::Buffer,
size: vk::DeviceSize,
) -> Result<u32> {
let mut free = self.free_storage_indices.lock().map_err(|_| {
Error::backend_failure(
"Vulkan",
"storage-descriptor allocation",
std::io::Error::other("storage descriptor allocator lock was poisoned"),
)
})?;
let index = free
.pop()
.ok_or_else(|| Error::resource_exhausted("Vulkan storage descriptor capacity exhausted"))?;
let buffer_info = vk::DescriptorBufferInfo::new()
.set_buffer(buffer)
.set_offset(0)
.set_range(size);
let buffer_infos = [buffer_info];
let write = vk::WriteDescriptorSet::new()
.set_dst_set(self.set)
.set_dst_binding(0)
.set_dst_array_element(index)
.set_descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.set_buffer_info(&buffer_infos);
unsafe {
device
.update_descriptor_sets(&[write.map_err(Error::from)?], &[])
.map_err(Error::from)?;
}
self.write_count.fetch_add(1, Ordering::Relaxed);
Ok(index)
}
pub(in crate::runtime::device) fn release_storage_buffer(&self, index: u32) {
let mut free = match self.free_storage_indices.lock() {
Ok(free) => free,
Err(poisoned) => poisoned.into_inner(),
};
free.push(index);
}
#[cfg(oa_profile = "compatibility")]
pub(in crate::runtime::device) fn bind_storage_image(
&self,
device: &vk::Device,
view: vk::ImageView,
) -> Result<u32> {
let _ = (device, view);
Ok(0)
}
#[cfg(oa_profile = "core")]
pub(in crate::runtime::device) fn bind_storage_image(
&self,
device: &vk::Device,
view: vk::ImageView,
) -> Result<u32> {
let mut free = self.free_image_indices.lock().map_err(|_| {
Error::backend_failure(
"Vulkan",
"storage-image descriptor allocation",
std::io::Error::other("storage image descriptor allocator lock was poisoned"),
)
})?;
let index = free.pop().ok_or_else(|| {
Error::resource_exhausted("Vulkan storage image descriptor capacity exhausted")
})?;
let image_info = vk::DescriptorImageInfo::new()
.set_image_view(view)
.set_image_layout(vk::ImageLayout::GENERAL);
let image_infos = [image_info];
let write = vk::WriteDescriptorSet::new()
.set_dst_set(self.set)
.set_dst_binding(1)
.set_dst_array_element(index)
.set_descriptor_type(vk::DescriptorType::STORAGE_IMAGE)
.set_image_info(&image_infos);
unsafe {
device
.update_descriptor_sets(&[write.map_err(Error::from)?], &[])
.map_err(Error::from)?;
}
self.write_count.fetch_add(1, Ordering::Relaxed);
Ok(index)
}
#[cfg(oa_profile = "compatibility")]
pub(in crate::runtime::device) fn release_storage_image(&self, index: u32) {
let _ = index;
}
#[cfg(oa_profile = "core")]
pub(in crate::runtime::device) fn release_storage_image(&self, index: u32) {
let mut free = match self.free_image_indices.lock() {
Ok(free) => free,
Err(poisoned) => poisoned.into_inner(),
};
free.push(index);
}
#[cfg(oa_profile = "compatibility")]
pub(in crate::runtime::device) fn destroy(&mut self, device: &vk::Device) {
for layout in self.bounded_layouts.drain(..) {
destroy_layout(device, layout);
}
}
#[cfg(oa_profile = "core")]
pub(in crate::runtime::device) fn destroy(&mut self, device: &vk::Device) {
destroy_pool(device, self.pool);
destroy_layout(device, self.layout);
}
#[cfg(oa_profile = "compatibility")]
pub(in crate::runtime::device) fn bounded_layout(
&self,
count: u32,
) -> Option<vk::DescriptorSetLayout> {
let index = usize::try_from(count.checked_sub(1)?).ok()?;
self.bounded_layouts.get(index).copied()
}
#[cfg(oa_profile = "core")]
pub(in crate::runtime::device) fn bounded_layout(
&self,
_count: u32,
) -> Option<vk::DescriptorSetLayout> {
None
}
pub(in crate::runtime::device) const fn layout(&self) -> vk::DescriptorSetLayout {
self.layout
}
pub(in crate::runtime::device) const fn set(&self) -> vk::DescriptorSet {
self.set
}
}
fn destroy_pool(device: &vk::Device, pool: vk::DescriptorPool) {
let _ = unsafe { device.destroy_descriptor_pool(pool, None) };
}
fn destroy_layout(device: &vk::Device, layout: vk::DescriptorSetLayout) {
let _ = unsafe { device.destroy_descriptor_set_layout(layout, None) };
}
#[cfg(oa_profile = "compatibility")]
pub(in crate::runtime::device) struct BoundedSets {
device: Arc<Device>,
pool: vk::DescriptorPool,
sets: Vec<vk::DescriptorSet>,
}
#[cfg(oa_profile = "compatibility")]
impl BoundedSets {
pub(in crate::runtime::device) fn new(
context: &Arc<Device>,
layouts: &[vk::DescriptorSetLayout],
buffers: &[Vec<vk::DescriptorBufferInfo>],
) -> Result<Self> {
let device = context.raw();
if layouts.is_empty() || layouts.len() != buffers.len() {
return Err(Error::internal(
"bounded descriptor layouts and dispatches must be nonempty and match",
));
}
for (&layout, infos) in layouts.iter().zip(buffers) {
let required = u32::try_from(infos.len())
.map_err(|_| Error::resource_exhausted("bounded dispatch descriptor count overflow"))?;
if context.bounded_descriptor_layout(required) != Some(layout) {
return Err(Error::internal(
"bounded descriptor layout does not match dispatch",
));
}
}
let count = u32::try_from(buffers.len())
.map_err(|_| Error::resource_exhausted("too many bounded compute dispatches"))?;
let descriptor_count = buffers.iter().try_fold(0_u32, |total, infos| {
let len = u32::try_from(infos.len())
.map_err(|_| Error::resource_exhausted("bounded dispatch descriptor count overflow"))?;
total
.checked_add(len)
.ok_or_else(|| Error::resource_exhausted("bounded descriptor count overflow"))
})?;
let sizes = [vk::DescriptorPoolSize::new()
.set_type(vk::DescriptorType::STORAGE_BUFFER)
.set_descriptor_count(descriptor_count)];
let info = vk::DescriptorPoolCreateInfo::new()
.set_max_sets(count)
.set_pool_sizes(&sizes)
.map_err(Error::from)?;
let pool = unsafe { device.create_descriptor_pool(&info, None) }.map_err(|source| {
Error::backend_failure("Vulkan", "bounded descriptor-pool creation", source)
})?;
let allocate = vk::DescriptorSetAllocateInfo::new()
.set_descriptor_pool(pool)
.set_set_layouts(layouts)
.map_err(Error::from)?;
let mut sets = vec![vk::DescriptorSet::default(); layouts.len()];
match unsafe { device.allocate_descriptor_sets(&allocate, &mut sets) } {
Ok(()) => {}
Err(source) => {
destroy_pool(device, pool);
return Err(Error::backend_failure(
"Vulkan",
"bounded descriptor-set allocation",
source,
));
}
};
for (&set, infos) in sets.iter().zip(buffers) {
let write = vk::WriteDescriptorSet::new()
.set_dst_set(set)
.set_dst_binding(0)
.set_descriptor_type(vk::DescriptorType::STORAGE_BUFFER)
.set_buffer_info(infos);
unsafe {
device
.update_descriptor_sets(&[write.map_err(Error::from)?], &[])
.map_err(Error::from)?
};
}
Ok(Self {
device: context.clone(),
pool,
sets,
})
}
pub(in crate::runtime::device) fn set(&self, index: usize) -> vk::DescriptorSet {
self.sets[index]
}
}
#[cfg(oa_profile = "compatibility")]
impl Drop for BoundedSets {
fn drop(&mut self) {
destroy_pool(self.device.raw(), self.pool);
}
}
#[cfg(oa_profile = "core")]
pub(in crate::runtime::device) type BoundedSets = std::convert::Infallible;