From 1b97a620c8b222c4c422293c2e5ca24b8f70bbae Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Tue, 17 Nov 2026 13:23:55 -0800 Subject: [PATCH] rt: set 1 and index grants Every pipeline of the new runtime takes set 1, one descriptor set the device makes at creation: 65,536 sampled textures (binding 0), 4,096 storage-capable textures (binding 1) and 4,000 samplers of each use, plain, depth comparison and integer texture (bindings 2, 3 and 4), each partially bound, updated after bind and while unused elements are pending, seen by every stage. Set 0 is empty. The pipeline layout is made once from it, in Device::new, and every pipeline and dispatch uses that layout. Every element no object owns is defined: a texture element is a null descriptor (VK_EXT_robustness2 nullDescriptor, which joins the floor; the robust buffer and image access beside it stay off), and a sampler element is its array's default sampler, nearest and clamped to the edge, the comparison array's comparing with NEVER. The device writes every element at creation and holds the two default VkSamplers (Gauges::device_samplers). The translator is told of VK_EXT_robustness2, so its profile has nullDescriptor. Device::grant_indices(class, first, count) grants the consumer the range it names, so the IDs it picks reproduce in replay: storage-capable textures 1 to 4,095, other textures 4,096 to 65,535, samplers 1 to 3,999, 0 nil and never granted (IndexClass, IndexGrant). Limit::IndexRange, Refusal::IndicesGranted and Refusal::IndicesNotGranted, with Basis lines; docs/REFUSALS.md regenerated. The floor's sampler limits are now three arrays' (12,000 samplers per stage and set, 81,632 update-after-bind descriptors in all pools). README: "Set 1 and index grants", and the floor's extension, feature and limit rows. Device::new output is unchanged: no translator source changes. Verified: - m3-max-42273 (msi): clippy -p metal2vulkan-rt --all-targets --all-features, plain, --cfg m2v_gpu and --cfg m2v_cpu_icd, green; rustdoc -D warnings green; rt tests 33/33; every device test on lavapipe with the Khronos validation layer, 0 validation errors; making a second set 1 takes 106 ms there. refusal_surface.py --check clean. - m3-max-42305 (Radeon 780M, RADV, gem10) and m3-max-42306 (RTX 3090, um870), validation layer on: every device test passes with 0 validation errors, gauges zero at drop; a second set 1 takes 15.1 ms on the 780M and 4.6 ms on the 3090. The three tests that read the source tree fail on those nodes only because the carried archive names msi's paths; they pass on msi. --- crates/metal2vulkan-rt/README.md | 44 +- crates/metal2vulkan-rt/src/arrays.rs | 479 +++++++++++++++++++++ crates/metal2vulkan-rt/src/counters.rs | 8 + crates/metal2vulkan-rt/src/device.rs | 44 +- crates/metal2vulkan-rt/src/error.rs | 49 +++ crates/metal2vulkan-rt/src/floor.rs | 34 +- crates/metal2vulkan-rt/src/lib.rs | 2 + crates/metal2vulkan-rt/src/tests/arrays.rs | 157 +++++++ crates/metal2vulkan-rt/src/tests/device.rs | 17 +- crates/metal2vulkan-rt/src/tests/floor.rs | 54 ++- crates/metal2vulkan-rt/src/tests/mod.rs | 1 + docs/REFUSALS.md | 14 +- 12 files changed, 849 insertions(+), 54 deletions(-) create mode 100644 crates/metal2vulkan-rt/src/arrays.rs create mode 100644 crates/metal2vulkan-rt/src/tests/arrays.rs diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index e4ec4e90a..ca6fd3d20 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -3,9 +3,9 @@ The Metal API on Vulkan, with one path for every device. It replaces `metal2vulkan-runtime` and takes its name when it does; until then it is unpublished. -Its public API so far: the instance and the device, memory blocks and the buffers in them, command -queues, command buffers and events, the device's counters, and `floor`, the check of a Vulkan -device against the floor below. +Its public API so far: the instance and the device, memory blocks and the buffers in them, the +grants of texture and sampler indices, command queues, command buffers and events, the device's +counters, and `floor`, the check of a Vulkan device against the floor below. ## Instance and device @@ -117,6 +117,30 @@ teardown, on the thread that tears down, after the runtime's other threads are j into the runtime. Blocks the consumer never took are freed without it, and so is every block freed after a quiesce. +## Set 1 and index grants + +Shaders reach textures and samplers by index (`docs/RESOURCE-ID.md`). Every pipeline takes set 1, +one descriptor set the device makes at creation, of five arrays whose element `i` is the object +whose `gpuResourceID` holds index `i`: 65,536 sampled textures (binding 0), 4,096 +storage-capable textures (binding 1), and 4,000 samplers of each use, plain, depth comparison and +integer texture (bindings 2, 3 and 4). Every binding is partially bound, updated after bind and +updated while unused elements are pending, so an object's element is written once, as it is +made, with no lock, and never rewritten for layouts. + +- Every element no object owns is defined. A texture element is a null descriptor + (`nullDescriptor`): it reads zeros, sizes 0 and drops writes, as Metal's nil texture does. A + sampler element is its array's default sampler, nearest and clamped to the edge; the + comparison array's compares with `NEVER`, so a comparison through it answers 0, as Metal's + default compare function does. Vulkan has no null sampler. The device writes every element so + at creation and holds two `VkSampler`s for the defaults (`Gauges::device_samplers`). +- `Device::grant_indices(class, first, count)` grants the consumer the range it names, so the IDs + it chooses from it on the guest's side reproduce in replay. The three classes are disjoint + (`IndexClass::range`): storage-capable textures (shader-write or unknown usage) take 1 to 4,095, + one index valid in both texture arrays; other textures 4,096 to 65,535; samplers 1 to 3,999. + Index 0 is nil and never granted. A range that is empty or leaves its class's is + `Limit::IndexRange`, and one holding an index granted already `Refusal::IndicesGranted`. + `Device::release_indices` returns a grant; one not granted is `Refusal::IndicesNotGranted`. + ## Queues, command buffers and events - `Device::new_command_queue(max)` is `newCommandQueueWithMaxCommandBufferCount:` @@ -400,6 +424,7 @@ Presenting runs on the runtime's own device; nothing is exported or imported. | `VK_KHR_surface` | instance | presenting | | `VK_KHR_swapchain` | device | presenting | | `VK_KHR_workgroup_memory_explicit_layout` | device | threadgroup memory laid out as Metal lays it | +| `VK_EXT_robustness2` | device | null descriptors | | `VK_KHR_shader_maximal_reconvergence` | device, where listed | SIMD groups that reconverge as Metal's do | | `VK_KHR_shader_subgroup_uniform_control_flow` | device, where listed | SIMD groups' reconvergence where maximal reconvergence is not offered | @@ -419,6 +444,7 @@ Presenting runs on the runtime's own device; nothing is exported or imported. | `shaderSampledImageArrayNonUniformIndexing` | `VkPhysicalDeviceVulkan12Features` | a `gpuResourceID` that differs between threads | | `shaderStorageImageArrayNonUniformIndexing` | `VkPhysicalDeviceVulkan12Features` | a `gpuResourceID` that differs between threads | | `shaderStorageImageWriteWithoutFormat` | `VkPhysicalDeviceFeatures` | writes to array elements of any pixel format | +| `nullDescriptor` | `VkPhysicalDeviceRobustness2FeaturesEXT` | every texture element no texture owns: a nil, freed or unowned index reads zeros, sizes 0 and drops writes, as Metal's nil texture does. The robust buffer and image access beside it stay off | | `shaderInt16` | `VkPhysicalDeviceFeatures` | `short` and `ushort` in shaders | | `shaderInt8` | `VkPhysicalDeviceVulkan12Features` | `char` and `uchar` in shaders | | `storageBuffer16BitAccess` | `VkPhysicalDeviceVulkan11Features` | 16-bit values in buffers | @@ -441,8 +467,8 @@ Presenting runs on the runtime's own device; nothing is exported or imported. ### Limits The descriptor limits are what the runtime's fixed arrays need: 65,536 sampled textures, 4,096 -read-write textures and 4,000 samplers. 4,000 is Vulkan's minimum `maxSamplerAllocationCount`, so -every slot can hold a live sampler on every device. The compute limits let a threadgroup take +read-write textures and three arrays of 4,000 samplers, one per use (plain, depth comparison, +integer texture). 4,000 is Vulkan's minimum `maxSamplerAllocationCount`. The compute limits let a threadgroup take Metal's 1,024 threads in any shape up to 1,024 by 1,024 by 64. A Boolean limit's minimum is 1, `VK_TRUE`; `timestampValidBits` is the queue family's. @@ -452,11 +478,11 @@ Metal's 1,024 threads in any shape up to 1,024 by 1,024 by 64. A Boolean limit's | `maxDescriptorSetUpdateAfterBindSampledImages` | `65536` | the sampled-texture array | | `maxPerStageDescriptorUpdateAfterBindStorageImages` | `4096` | the read-write texture array | | `maxDescriptorSetUpdateAfterBindStorageImages` | `4096` | the read-write texture array | -| `maxPerStageDescriptorUpdateAfterBindSamplers` | `4000` | the sampler array | -| `maxDescriptorSetUpdateAfterBindSamplers` | `4000` | the sampler array | -| `maxSamplerAllocationCount` | `4000` | a live sampler in every slot | +| `maxPerStageDescriptorUpdateAfterBindSamplers` | `12000` | the three sampler arrays | +| `maxDescriptorSetUpdateAfterBindSamplers` | `12000` | the three sampler arrays | +| `maxSamplerAllocationCount` | `4000` | Vulkan's minimum: live samplers | | `maxPerStageUpdateAfterBindResources` | `69632` | both texture arrays in one stage; a fragment stage needs its `maxColorAttachments` more | -| `maxUpdateAfterBindDescriptorsInAllPools` | `73632` | all three arrays | +| `maxUpdateAfterBindDescriptorsInAllPools` | `81632` | all five arrays | | `maxPushConstantsSize` | `256` | per-command values: a dispatch region and 28 buffer addresses; anything larger goes in a block whose address is pushed | | `maxComputeWorkGroupInvocations` | `1024` | Metal's most threads per threadgroup | | `maxComputeWorkGroupSize[0]` | `1024` | a threadgroup's width | diff --git a/crates/metal2vulkan-rt/src/arrays.rs b/crates/metal2vulkan-rt/src/arrays.rs new file mode 100644 index 000000000..73cbb46d4 --- /dev/null +++ b/crates/metal2vulkan-rt/src/arrays.rs @@ -0,0 +1,479 @@ +//! Set 1: the descriptor arrays every pipeline takes its textures and samplers from, each element +//! at the index a `gpuResourceID` holds (`docs/RESOURCE-ID.md`), and the index grants the consumer +//! chooses those indices from. +//! +//! One descriptor set of the translator's identity domains' five arrays, made at device creation +//! and never rewritten for layouts: binding 0 the sampled textures (65,536), binding 1 the +//! storage-capable textures (4,096), and bindings 2, 3 and 4 the samplers of each use, plain, +//! depth comparison and integer texture (4,000 each). Every binding is partially bound and +//! updated after bind, also while work that uses the set is pending, so writing one element needs +//! no lock: each element has one owner, which writes it alone. +//! +//! Every element no live object owns holds a defined value, so a nil, stale or forged index reads +//! zeros or samples plainly on every device, where an element never written would be undefined +//! behaviour. A texture element is a null descriptor (`nullDescriptor`), which reads zeros, +//! answers 0 to its size queries and drops its writes, as Metal's nil texture does. A sampler +//! element is its array's default sampler, nearest and clamped to the edge; the comparison +//! array's compares with `NEVER`, so a comparison through it answers 0, as Metal's default +//! comparison (`MTLCompareFunctionNever`) does. Vulkan has no null sampler. The device writes +//! every element once at creation ([`Arrays::new`]). +//! +//! The consumer names each range of indices it takes ([`Device::grant_indices`]), so resource IDs +//! are chosen on the guest's side and reproduce in replay. Three classes, disjoint: storage-capable +//! textures take 1 to 4,095, one index valid in both texture arrays; other textures 4,096 to +//! 65,535; samplers 1 to 3,999. Index 0 is nil and never granted. + +use crate::counters::{Counters, Gauge}; +use crate::device::lock; +use crate::error::{Error, Limit, Refusal}; +use crate::floor::{SAMPLED_IMAGES, SAMPLERS, SAMPLER_ARRAYS, STORAGE_IMAGES}; +use crate::Device; +use ash::vk; +use std::ops::Range; +use std::sync::Mutex; + +/// The binding of the sampled-texture array. +pub(crate) const SAMPLED_BINDING: u32 = 0; +/// The binding of the storage-capable texture array. +pub(crate) const STORAGE_BINDING: u32 = 1; +/// The binding of the first sampler array; the plain, comparison and integer-texture arrays +/// follow in that order. +pub(crate) const FIRST_SAMPLER_BINDING: u32 = 2; + +/// No Metal counterpart: the class of a texture or sampler index, which sets the range its grants +/// are taken from (`docs/RESOURCE-ID.md`). +#[non_exhaustive] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum IndexClass { + /// A texture without shader-write usage: 4,096 to 65,535 of the sampled-texture array. + Texture, + /// A texture with shader-write or unknown usage: 1 to 4,095, one index valid in both the + /// sampled-texture and the storage-texture array. + StorageTexture, + /// A sampler: 1 to 3,999 of each sampler array. A Metal sampler state takes one, and so does + /// each constexpr sampler a pipeline state numbers. + Sampler, +} + +impl IndexClass { + /// The indices the class's grants are taken from. + pub fn range(self) -> Range { + match self { + IndexClass::Texture => STORAGE_IMAGES..SAMPLED_IMAGES, + IndexClass::StorageTexture => 1..STORAGE_IMAGES, + IndexClass::Sampler => 1..SAMPLERS, + } + } + + fn slot(self) -> usize { + match self { + IndexClass::Texture => 0, + IndexClass::StorageTexture => 1, + IndexClass::Sampler => 2, + } + } +} + +/// No Metal counterpart: indices granted to the consumer, `first..first + count` of `class` +/// ([`Device::grant_indices`]). Plain data: it holds nothing of the device. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct IndexGrant { + /// The class the indices are of. + pub class: IndexClass, + /// The first index. + pub first: u32, + /// How many indices. + pub count: u32, +} + +impl IndexGrant { + fn indices(self) -> Range { + self.first..self.first + self.count + } +} + +/// The indices granted, one bit per index of each class's array. +pub(crate) struct Grants { + granted: [Vec; 3], +} + +impl Grants { + pub(crate) fn new() -> Grants { + let words = |len: u32| vec![0; len.div_ceil(64) as usize]; + Grants { + granted: [ + words(SAMPLED_IMAGES), + words(STORAGE_IMAGES), + words(SAMPLERS), + ], + } + } + + fn bit(&self, class: IndexClass, index: u32) -> bool { + self.granted[class.slot()][(index / 64) as usize] & (1 << (index % 64)) != 0 + } + + fn set(&mut self, class: IndexClass, index: u32, on: bool) { + let word = &mut self.granted[class.slot()][(index / 64) as usize]; + match on { + true => *word |= 1 << (index % 64), + false => *word &= !(1 << (index % 64)), + } + } + + /// Grants `first..first + count` of `class` where the range is inside the class's and none of + /// it is granted. + pub(crate) fn grant( + &mut self, + class: IndexClass, + first: u32, + count: u32, + ) -> Result { + let range = class.range(); + let inside = count > 0 + && first >= range.start + && first.checked_add(count).is_some_and(|end| end <= range.end); + if !inside { + return Err(Error::Limit(Limit::IndexRange { + class, + first, + count, + })); + } + let grant = IndexGrant { + class, + first, + count, + }; + if let Some(index) = grant.indices().find(|&index| self.bit(class, index)) { + return Err(Error::Refused(Refusal::IndicesGranted { class, index })); + } + for index in grant.indices() { + self.set(class, index, true); + } + Ok(grant) + } + + /// Returns `grant`, where every index of it is granted. + pub(crate) fn release(&mut self, grant: IndexGrant) -> Result<(), Error> { + let IndexGrant { class, .. } = grant; + let range = class.range(); + let inside = grant.first >= range.start + && grant + .first + .checked_add(grant.count) + .is_some_and(|end| end <= range.end); + let missing = match inside { + true => grant.indices().find(|&index| !self.bit(class, index)), + false => Some(grant.first), + }; + if let Some(index) = missing { + return Err(Error::Refused(Refusal::IndicesNotGranted { class, index })); + } + for index in grant.indices() { + self.set(class, index, false); + } + Ok(()) + } +} + +/// Set 1, its layouts, its default samplers, and the grants of its indices. +pub(crate) struct Arrays { + /// The empty layout of set 0, which no pipeline reads. + empty: vk::DescriptorSetLayout, + /// Set 1's layout. + layout: vk::DescriptorSetLayout, + /// The pool of the one set, which destroying it frees. + pool: vk::DescriptorPool, + /// The default sampler of the plain and integer-texture arrays. + pub(crate) plain: vk::Sampler, + /// The default sampler of the comparison array. + pub(crate) compare: vk::Sampler, + pub(crate) grants: Mutex, +} + +impl Arrays { + /// Makes set 1 and writes every element its default. + /// + /// # Safety + /// + /// `device` is live and was made with the floor's features, `nullDescriptor` and the + /// update-after-bind features among them. + pub(crate) unsafe fn new(device: &ash::Device, counters: &Counters) -> Result { + let mut made = Made::default(); + // SAFETY: the caller's contract; what was made is destroyed where a later step fails. + let arrays = unsafe { made.make(device, counters) }; + if arrays.is_err() { + // SAFETY: nothing else holds what was made. + unsafe { made.destroy(device, counters) }; + } + arrays + } + + /// The set layouts of every pipeline: the empty set 0, then set 1. + pub(crate) fn set_layouts(&self) -> [vk::DescriptorSetLayout; 2] { + [self.empty, self.layout] + } + + /// Destroys set 1. + /// + /// # Safety + /// + /// The device is idle, and no pipeline layout made with [`Arrays::set_layouts`] is used again. + pub(crate) unsafe fn destroy(&self, device: &ash::Device, counters: &Counters) { + let made = Made { + empty: Some(self.empty), + layout: Some(self.layout), + pool: Some(self.pool), + plain: Some(self.plain), + compare: Some(self.compare), + }; + // SAFETY: the caller's contract. + unsafe { made.destroy(device, counters) }; + } +} + +/// What [`Arrays::new`] has made so far. +#[derive(Default)] +struct Made { + empty: Option, + layout: Option, + pool: Option, + plain: Option, + compare: Option, +} + +impl Made { + /// # Safety + /// + /// As [`Arrays::new`]. + unsafe fn make(&mut self, device: &ash::Device, counters: &Counters) -> Result { + let empty = vk::DescriptorSetLayoutCreateInfo::default(); + // SAFETY: the device is live. + let empty = unsafe { device.create_descriptor_set_layout(&empty, None) } + .map_err(Error::vulkan("vkCreateDescriptorSetLayout"))?; + self.empty = Some(empty); + let array = |binding, ty, count| { + vk::DescriptorSetLayoutBinding::default() + .binding(binding) + .descriptor_type(ty) + .descriptor_count(count) + .stage_flags(vk::ShaderStageFlags::ALL) + }; + let sampler = |use_: u32| { + array( + FIRST_SAMPLER_BINDING + use_, + vk::DescriptorType::SAMPLER, + SAMPLERS, + ) + }; + let bindings = [ + array( + SAMPLED_BINDING, + vk::DescriptorType::SAMPLED_IMAGE, + SAMPLED_IMAGES, + ), + array( + STORAGE_BINDING, + vk::DescriptorType::STORAGE_IMAGE, + STORAGE_IMAGES, + ), + sampler(0), + sampler(1), + sampler(2), + ]; + let flags = [vk::DescriptorBindingFlags::PARTIALLY_BOUND + | vk::DescriptorBindingFlags::UPDATE_AFTER_BIND + | vk::DescriptorBindingFlags::UPDATE_UNUSED_WHILE_PENDING; 5]; + let mut binding_flags = + vk::DescriptorSetLayoutBindingFlagsCreateInfo::default().binding_flags(&flags); + let info = vk::DescriptorSetLayoutCreateInfo::default() + .flags(vk::DescriptorSetLayoutCreateFlags::UPDATE_AFTER_BIND_POOL) + .bindings(&bindings) + .push_next(&mut binding_flags); + // SAFETY: the device is live, with the update-after-bind features of each binding's type + // (the floor's). + let layout = unsafe { device.create_descriptor_set_layout(&info, None) } + .map_err(Error::vulkan("vkCreateDescriptorSetLayout"))?; + self.layout = Some(layout); + let sizes = [ + vk::DescriptorPoolSize { + ty: vk::DescriptorType::SAMPLED_IMAGE, + descriptor_count: SAMPLED_IMAGES, + }, + vk::DescriptorPoolSize { + ty: vk::DescriptorType::STORAGE_IMAGE, + descriptor_count: STORAGE_IMAGES, + }, + vk::DescriptorPoolSize { + ty: vk::DescriptorType::SAMPLER, + descriptor_count: SAMPLER_ARRAYS * SAMPLERS, + }, + ]; + let info = vk::DescriptorPoolCreateInfo::default() + .flags(vk::DescriptorPoolCreateFlags::UPDATE_AFTER_BIND) + .max_sets(1) + .pool_sizes(&sizes); + // SAFETY: the device is live. + let pool = unsafe { device.create_descriptor_pool(&info, None) } + .map_err(Error::vulkan("vkCreateDescriptorPool"))?; + self.pool = Some(pool); + let layouts = [layout]; + let info = vk::DescriptorSetAllocateInfo::default() + .descriptor_pool(pool) + .set_layouts(&layouts); + // SAFETY: the pool is the device's, sized for one set of this layout. + let set = unsafe { device.allocate_descriptor_sets(&info) } + .map_err(Error::vulkan("vkAllocateDescriptorSets"))?[0]; + let default = |compare: bool| { + let info = vk::SamplerCreateInfo::default() + .mag_filter(vk::Filter::NEAREST) + .min_filter(vk::Filter::NEAREST) + .mipmap_mode(vk::SamplerMipmapMode::NEAREST) + .address_mode_u(vk::SamplerAddressMode::CLAMP_TO_EDGE) + .address_mode_v(vk::SamplerAddressMode::CLAMP_TO_EDGE) + .address_mode_w(vk::SamplerAddressMode::CLAMP_TO_EDGE) + .compare_enable(compare) + .compare_op(vk::CompareOp::NEVER); + // SAFETY: the device is live. + let sampler = unsafe { device.create_sampler(&info, None) } + .map_err(Error::vulkan("vkCreateSampler"))?; + counters.rise(Gauge::DeviceSamplers); + Ok::<_, Error>(sampler) + }; + let plain = default(false)?; + self.plain = Some(plain); + let compare = default(true)?; + self.compare = Some(compare); + // SAFETY: the set is the device's and no command buffer uses it yet. + unsafe { fill(device, set, plain, compare) }; + Ok(Arrays { + empty, + layout, + pool, + plain, + compare, + grants: Mutex::new(Grants::new()), + }) + } + + /// # Safety + /// + /// The device is idle, and nothing made from these objects is used again. + unsafe fn destroy(&self, device: &ash::Device, counters: &Counters) { + // SAFETY: the caller's contract; destroying the pool frees its set. + unsafe { + for sampler in [self.plain, self.compare].into_iter().flatten() { + device.destroy_sampler(sampler, None); + counters.fall(Gauge::DeviceSamplers); + } + if let Some(pool) = self.pool { + device.destroy_descriptor_pool(pool, None); + } + for layout in [self.layout, self.empty].into_iter().flatten() { + device.destroy_descriptor_set_layout(layout, None); + } + } + } +} + +/// Writes every element of `set` its default: a null descriptor in each texture array, `plain` +/// in the plain and integer-texture sampler arrays and `compare` in the comparison array. +/// +/// # Safety +/// +/// `set` is set 1 of `device`, `nullDescriptor` is enabled, and no other thread writes an element +/// of it meanwhile. +unsafe fn fill( + device: &ash::Device, + set: vk::DescriptorSet, + plain: vk::Sampler, + compare: vk::Sampler, +) { + let sampled = vec![ + vk::DescriptorImageInfo::default() + .image_layout(vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL); + SAMPLED_IMAGES as usize + ]; + let storage = vec![ + vk::DescriptorImageInfo::default().image_layout(vk::ImageLayout::GENERAL); + STORAGE_IMAGES as usize + ]; + let samplers = + |sampler| vec![vk::DescriptorImageInfo::default().sampler(sampler); SAMPLERS as usize]; + let (plains, compares) = (samplers(plain), samplers(compare)); + fn write( + set: vk::DescriptorSet, + binding: u32, + ty: vk::DescriptorType, + infos: &[vk::DescriptorImageInfo], + ) -> vk::WriteDescriptorSet<'_> { + vk::WriteDescriptorSet::default() + .dst_set(set) + .dst_binding(binding) + .descriptor_type(ty) + .image_info(infos) + } + let writes = [ + write( + set, + SAMPLED_BINDING, + vk::DescriptorType::SAMPLED_IMAGE, + &sampled, + ), + write( + set, + STORAGE_BINDING, + vk::DescriptorType::STORAGE_IMAGE, + &storage, + ), + write( + set, + FIRST_SAMPLER_BINDING, + vk::DescriptorType::SAMPLER, + &plains, + ), + write( + set, + FIRST_SAMPLER_BINDING + 1, + vk::DescriptorType::SAMPLER, + &compares, + ), + write( + set, + FIRST_SAMPLER_BINDING + 2, + vk::DescriptorType::SAMPLER, + &plains, + ), + ]; + // SAFETY: the caller's contract; a null image view is a null descriptor under + // `nullDescriptor`, and each sampler is the device's. + unsafe { device.update_descriptor_sets(&writes, &[]) }; +} + +impl Device { + /// No Metal counterpart: grants the consumer `first..first + count` of `class`, the range it + /// names, so the resource IDs it chooses from it reproduce in replay. A texture or a sampler + /// state is made at an index of a live grant of its class, and so is each constexpr sampler a + /// pipeline state numbers. + /// + /// Err: [`Limit::IndexRange`] where the range is empty or leaves the class's + /// ([`IndexClass::range`]); [`Refusal::IndicesGranted`] where one of its indices is granted + /// already. + pub fn grant_indices( + &self, + class: IndexClass, + first: u32, + count: u32, + ) -> Result { + lock(&self.core().arrays.grants).grant(class, first, count) + } + + /// No Metal counterpart: returns a grant [`Device::grant_indices`] made, so its indices may be + /// granted again. + /// + /// Err: [`Refusal::IndicesNotGranted`] where one of its indices is not granted. + pub fn release_indices(&self, grant: IndexGrant) -> Result<(), Error> { + lock(&self.core().arrays.grants).release(grant) + } +} diff --git a/crates/metal2vulkan-rt/src/counters.rs b/crates/metal2vulkan-rt/src/counters.rs index 9cae507ce..adb554ed6 100644 --- a/crates/metal2vulkan-rt/src/counters.rs +++ b/crates/metal2vulkan-rt/src/counters.rs @@ -38,6 +38,8 @@ pub(crate) enum Gauge { CommandBuffers, /// [`Gauges::events`]. Events, + /// [`Gauges::device_samplers`]. + DeviceSamplers, } /// No Metal counterpart: a device's counters ([`Device::counters`](crate::Device::counters)). @@ -72,6 +74,7 @@ struct Atomics { descriptor_slots: AtomicU64, blocks: AtomicU64, events: AtomicU64, + device_samplers: AtomicU64, } impl Counters { @@ -125,6 +128,7 @@ impl Counters { Gauge::Blocks => &a.blocks, Gauge::CommandBuffers => &a.command_buffers, Gauge::Events => &a.events, + Gauge::DeviceSamplers => &a.device_samplers, } } @@ -159,6 +163,7 @@ impl Counters { descriptor_slots: a.descriptor_slots.load(Relaxed), blocks: a.blocks.load(Relaxed), events: a.events.load(Relaxed), + device_samplers: a.device_samplers.load(Relaxed), } } } @@ -225,4 +230,7 @@ pub struct Gauges { pub blocks: u64, /// Events and shared events (timeline semaphores). pub events: u64, + /// `VkSampler`s the runtime holds: the default samplers of the sampler arrays. They count + /// against the device's `maxSamplerAllocationCount`. + pub device_samplers: u64, } diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index 418ccce24..a82509015 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -1,6 +1,7 @@ //! The device: one `VkDevice` for every command queue, every guest process and the compositor; //! its queues, its memory blocks, its threads, quiesce and teardown. +use crate::arrays::Arrays; use crate::cache::Caches; use crate::complete::{self, Done}; use crate::counters::{Counters, Gauge}; @@ -150,8 +151,11 @@ pub(crate) struct Core { /// Every queue's timestamp pool not yet destroyed: one whose queue outlives the device is /// destroyed with it. pub(crate) query_pools: Mutex>, - /// The one pipeline layout of every pipeline: the push window over every stage. + /// The one pipeline layout of every pipeline: the empty set 0, set 1, and the push window + /// over every stage. pub(crate) layout: vk::PipelineLayout, + /// Set 1: the texture and sampler arrays, and the grants of their indices. + pub(crate) arrays: Arrays, /// The device's compute limits. pub(crate) limits: ComputeLimits, /// The parameter ring. @@ -261,13 +265,15 @@ impl Device { mut workgroup_layout, mut maximal_reconvergence, mut subgroup_uniform_control_flow, + mut robustness2, } = enabled_features; let mut features = vk::PhysicalDeviceFeatures2::default() .features(core) .push_next(&mut vulkan11) .push_next(&mut vulkan12) .push_next(&mut vulkan13) - .push_next(&mut workgroup_layout); + .push_next(&mut workgroup_layout) + .push_next(&mut robustness2); // An optional extension's structure goes in only where the extension is enabled. let enabled = |name: &std::ffi::CStr| capabilities.extensions.contains(&name); if enabled(ash::khr::shader_maximal_reconvergence::NAME) { @@ -327,7 +333,7 @@ impl Device { // SAFETY: the device was made from `raw` with `capabilities.features`, and the family is // its queues' family. let made = unsafe { objects(&device, &capabilities, family, &counters) }; - let (memory_types, filler, done, layout) = match made { + let (memory_types, filler, done, arrays, layout) = match made { Ok(made) => made, Err(error) => { // SAFETY: nothing made from the device is left but the caches, which made no @@ -389,6 +395,7 @@ impl Device { reaper: Reaper::new(), query_pools: Mutex::new(Vec::new()), layout, + arrays, limits, ring: Ring::new(), ids: Ids::new(), @@ -802,7 +809,7 @@ unsafe fn objects( capabilities: &floor::Capabilities, family: u32, counters: &Counters, -) -> Result<(floor::MemoryTypes, Filler, Done, vk::PipelineLayout), Error> { +) -> Result<(floor::MemoryTypes, Filler, Done, Arrays, vk::PipelineLayout), Error> { // SAFETY: the caller's contract. let memory_types = unsafe { floor::memory_types(device, capabilities) }.map_err(Error::BelowFloor)?; @@ -811,18 +818,34 @@ unsafe fn objects( let mut filler = unsafe { Filler::new(device, family, memory_types.shared, counters) }?; // SAFETY: the device is live. let made = unsafe { Done::new(device) }.and_then(|mut done| { + // SAFETY: the device is live, with the floor's features. + let arrays = match unsafe { Arrays::new(device, counters) } { + Ok(arrays) => arrays, + Err(error) => { + // SAFETY: the completion objects are unused. + unsafe { done.destroy(device) }; + return Err(error); + } + }; let push = [vk::PushConstantRange { stage_flags: vk::ShaderStageFlags::ALL, offset: 0, size: PUSH_BYTES, }]; - let info = vk::PipelineLayoutCreateInfo::default().push_constant_ranges(&push); - // SAFETY: the device is live, and the floor holds `PUSH_BYTES` of push constants. + let sets = arrays.set_layouts(); + let info = vk::PipelineLayoutCreateInfo::default() + .set_layouts(&sets) + .push_constant_ranges(&push); + // SAFETY: the device is live, and the floor holds `PUSH_BYTES` of push constants and set + // 1's update-after-bind descriptors in one stage. match unsafe { device.create_pipeline_layout(&info, None) } { - Ok(layout) => Ok((done, layout)), + Ok(layout) => Ok((done, arrays, layout)), Err(result) => { - // SAFETY: the completion objects are unused. - unsafe { done.destroy(device) }; + // SAFETY: the completion objects and set 1 are unused. + unsafe { + arrays.destroy(device, counters); + done.destroy(device); + } Err(Error::Vulkan { call: "vkCreatePipelineLayout", result, @@ -831,7 +854,7 @@ unsafe fn objects( } }); match made { - Ok((done, layout)) => Ok((memory_types, filler, done, layout)), + Ok((done, arrays, layout)) => Ok((memory_types, filler, done, arrays, layout)), Err(error) => { // SAFETY: the fill's objects are unused. if unsafe { filler.destroy(device) } { @@ -950,6 +973,7 @@ impl Drop for Core { let zero_source = unsafe { self.caches.destroy(&self.device); self.device.destroy_pipeline_layout(self.layout, None); + self.arrays.destroy(&self.device, &self.counters); self.done.destroy(&self.device); let zero_source = self.filler.destroy(&self.device); self.device.destroy_device(None); diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index a07204714..b4b445a81 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -1,5 +1,6 @@ //! The error every fallible call returns: one typed variant per case, never text to parse. +use crate::arrays::IndexClass; use crate::floor::BelowFloor; use crate::memory::BlockId; use ash::vk; @@ -139,6 +140,26 @@ pub enum Refusal { /// The buffer's length. length: u64, }, + /// A grant of an index already granted ([`Device::grant_indices`](crate::Device::grant_indices)). + /// Metal has no counterpart: Metal chooses its resource IDs itself. + /// + /// Basis: ours (each index has one grant, so each resource ID names one object). + IndicesGranted { + /// The class of the index. + class: IndexClass, + /// The first index of the range that is granted already. + index: u32, + }, + /// A release of an index that is not granted + /// ([`Device::release_indices`](crate::Device::release_indices)). Metal has no counterpart. + /// + /// Basis: ours (a grant is returned once). + IndicesNotGranted { + /// The class of the index. + class: IndexClass, + /// The first index of the range that is not granted. + index: u32, + }, } /// A Metal feature the runtime does not build yet, with what it was asked. Each is refused until a @@ -248,6 +269,20 @@ pub enum Limit { /// The most one call takes. max: u64, }, + /// A grant of no indices, or one past its class's range + /// ([`Device::grant_indices`](crate::Device::grant_indices), [`IndexClass::range`]). Metal + /// has no counterpart. + /// + /// Basis: ours (the descriptor arrays are 65,536 sampled textures, 4,096 storage textures and + /// 4,000 samplers of each use, and index 0 is nil). + IndexRange { + /// The class asked for. + class: IndexClass, + /// The first index asked for. + first: u32, + /// How many indices. + count: u32, + }, } impl Error { @@ -307,6 +342,12 @@ impl fmt::Display for Refusal { f, "indirect arguments at offset {offset} of a {length}-byte buffer are misaligned or past its end" ), + Refusal::IndicesGranted { class, index } => { + write!(f, "{class:?} index {index} is granted already") + } + Refusal::IndicesNotGranted { class, index } => { + write!(f, "{class:?} index {index} is not granted") + } } } } @@ -356,6 +397,14 @@ impl fmt::Display for Limit { Limit::BytesLength { len, max } => { write!(f, "{len} bytes are past the most one call takes, {max}") } + Limit::IndexRange { + class, + first, + count, + } => write!( + f, + "{count} {class:?} indices from {first} are none or leave the class's range" + ), } } } diff --git a/crates/metal2vulkan-rt/src/floor.rs b/crates/metal2vulkan-rt/src/floor.rs index 8a883a47f..0be69c500 100644 --- a/crates/metal2vulkan-rt/src/floor.rs +++ b/crates/metal2vulkan-rt/src/floor.rs @@ -19,11 +19,12 @@ pub const VERSION: u32 = vk::API_VERSION_1_3; /// runtime's own device. pub const INSTANCE_EXTENSIONS: &[&CStr] = &[ash::khr::surface::NAME]; -/// The device extensions the runtime requires and device creation enables: presenting, and -/// threadgroup memory laid out as Metal lays it. +/// The device extensions the runtime requires and device creation enables: presenting, +/// threadgroup memory laid out as Metal lays it, and null descriptors. pub const DEVICE_EXTENSIONS: &[&CStr] = &[ ash::khr::swapchain::NAME, ash::khr::workgroup_memory_explicit_layout::NAME, + ash::ext::robustness2::NAME, ]; /// The device extensions device creation enables where the device lists them, each for the @@ -41,6 +42,8 @@ fn shader_extension(name: &CStr) -> Option { Some(VkExtension::KhrShaderMaximalReconvergence) } else if name == ash::khr::shader_subgroup_uniform_control_flow::NAME { Some(VkExtension::KhrShaderSubgroupUniformControlFlow) + } else if name == ash::ext::robustness2::NAME { + Some(VkExtension::ExtRobustness2) } else { None } @@ -52,10 +55,13 @@ pub(crate) const SAMPLED_IMAGES: u32 = 65_536; /// Slots in the read-write texture array. pub(crate) const STORAGE_IMAGES: u32 = 4096; -/// Slots in the sampler array. 4000 is Vulkan's minimum `maxSamplerAllocationCount`, so every +/// Slots in each sampler array. 4000 is Vulkan's minimum `maxSamplerAllocationCount`, so every /// device can hold a sampler in every slot. pub(crate) const SAMPLERS: u32 = 4000; +/// Sampler arrays: one per use of a sampler (plain, depth comparison, integer texture). +pub(crate) const SAMPLER_ARRAYS: u32 = 3; + /// Bytes of push constants: a dispatch region and 28 buffer addresses (the translator's push /// window on `Device::from_queries`' profile), which every captured device reports, so no query /// decides it. @@ -150,6 +156,9 @@ pub struct Features { /// it. pub subgroup_uniform_control_flow: vk::PhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR<'static>, + /// `VkPhysicalDeviceRobustness2FeaturesEXT`, of `VK_EXT_robustness2`: only `nullDescriptor` + /// is enabled, never the robust buffer and image access beside it. + pub robustness2: vk::PhysicalDeviceRobustness2FeaturesEXT<'static>, } /// One feature: the Vulkan structure that reports it, its member as ash spells it, the member, and @@ -183,6 +192,9 @@ macro_rules! feature { (@structure subgroup_uniform_control_flow) => { "VkPhysicalDeviceShaderSubgroupUniformControlFlowFeaturesKHR" }; + (@structure robustness2) => { + "VkPhysicalDeviceRobustness2FeaturesEXT" + }; (@translator) => { None }; @@ -215,6 +227,10 @@ pub(crate) const REQUIRED: &[Feature] = &[ feature!(vulkan12.shader_sampled_image_array_non_uniform_indexing => ShaderSampledImageArrayNonUniformIndexing), feature!(vulkan12.shader_storage_image_array_non_uniform_indexing => ShaderStorageImageArrayNonUniformIndexing), feature!(core.shader_storage_image_write_without_format => ShaderStorageImageWriteWithoutFormat), + // Every array element no texture owns is a null descriptor: a nil, freed or unowned texture + // index reads zeros, answers 0 to its size queries and drops its writes, as Metal's nil + // texture does, with no code in the shader. + feature!(robustness2.null_descriptor => NullDescriptor), // The translator's shaders: 8-, 16- and 64-bit integers, 8- and 16-bit values in buffers, // scalar and std430 layout of buffer, uniform and push-constant blocks, threadgroup memory // laid out as Metal lays it, and the Vulkan memory model with device scope for atomics and @@ -507,6 +523,7 @@ unsafe fn query(instance: &ash::Instance, physical: vk::PhysicalDevice) -> Queri let maximal_reconvergence_listed = listed(ash::khr::shader_maximal_reconvergence::NAME); let uniform_control_flow_listed = listed(ash::khr::shader_subgroup_uniform_control_flow::NAME); + let robustness2_listed = listed(ash::ext::robustness2::NAME); let Features { core, @@ -516,6 +533,7 @@ unsafe fn query(instance: &ash::Instance, physical: vk::PhysicalDevice) -> Queri workgroup_layout, maximal_reconvergence, subgroup_uniform_control_flow, + robustness2, } = &mut queried.features; let mut features = vk::PhysicalDeviceFeatures2::default() .push_next(&mut *vulkan11) @@ -530,6 +548,9 @@ unsafe fn query(instance: &ash::Instance, physical: vk::PhysicalDevice) -> Queri if uniform_control_flow_listed { features = features.push_next(&mut *subgroup_uniform_control_flow); } + if robustness2_listed { + features = features.push_next(&mut *robustness2); + } instance.get_physical_device_features2(physical, &mut features); *core = features.features; vulkan11.p_next = std::ptr::null_mut(); @@ -538,6 +559,7 @@ unsafe fn query(instance: &ash::Instance, physical: vk::PhysicalDevice) -> Queri workgroup_layout.p_next = std::ptr::null_mut(); maximal_reconvergence.p_next = std::ptr::null_mut(); subgroup_uniform_control_flow.p_next = std::ptr::null_mut(); + robustness2.p_next = std::ptr::null_mut(); queried.families = instance.get_physical_device_queue_family_properties(physical); queried.memory = instance.get_physical_device_memory_properties(physical); @@ -748,12 +770,12 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 15] { ( "maxPerStageDescriptorUpdateAfterBindSamplers", descriptors.max_per_stage_descriptor_update_after_bind_samplers, - SAMPLERS, + SAMPLER_ARRAYS * SAMPLERS, ), ( "maxDescriptorSetUpdateAfterBindSamplers", descriptors.max_descriptor_set_update_after_bind_samplers, - SAMPLERS, + SAMPLER_ARRAYS * SAMPLERS, ), ( "maxSamplerAllocationCount", @@ -769,7 +791,7 @@ pub(crate) fn limits(device: &Queried) -> [(&'static str, u32, u32); 15] { ( "maxUpdateAfterBindDescriptorsInAllPools", descriptors.max_update_after_bind_descriptors_in_all_pools, - SAMPLED_IMAGES + STORAGE_IMAGES + SAMPLERS, + SAMPLED_IMAGES + STORAGE_IMAGES + SAMPLER_ARRAYS * SAMPLERS, ), ( "maxPushConstantsSize", diff --git a/crates/metal2vulkan-rt/src/lib.rs b/crates/metal2vulkan-rt/src/lib.rs index a8ffc18b2..efe8bd878 100644 --- a/crates/metal2vulkan-rt/src/lib.rs +++ b/crates/metal2vulkan-rt/src/lib.rs @@ -8,6 +8,7 @@ #![warn(missing_docs)] +mod arrays; mod buffer; mod cache; mod command; @@ -34,6 +35,7 @@ mod submit; mod tests; mod times; +pub use arrays::{IndexClass, IndexGrant}; pub use buffer::Buffer; pub use command::{CommandBuffer, CommandBufferError, CommandBufferStatus}; pub use counters::{Counters, Gauges, Metrics}; diff --git a/crates/metal2vulkan-rt/src/tests/arrays.rs b/crates/metal2vulkan-rt/src/tests/arrays.rs new file mode 100644 index 000000000..d538090d3 --- /dev/null +++ b/crates/metal2vulkan-rt/src/tests/arrays.rs @@ -0,0 +1,157 @@ +//! Set 1's index grants, and on devices its fill. +//! +//! - A grant takes a range inside its class's (storage-capable textures 1 to 4,095, other textures +//! 4,096 to 65,535, samplers 1 to 3,999); index 0, an empty range and one past the class's are +//! `Limit::IndexRange`. An index granted already is `Refusal::IndicesGranted`, of any range that +//! holds it; a release of an index not granted is `Refusal::IndicesNotGranted`. A released range +//! is granted again. +//! - Under a device cfg, on every device of the cfg's kind, the device writes every element of +//! set 1 its default at creation, and holds two `VkSampler`s for it; grants work through the +//! device; making and destroying a second set 1 is timed and reported, and its two samplers +//! are gone after it. + +use crate::arrays::Grants; +use crate::error::{Error, Limit, Refusal}; +use crate::IndexClass; + +/// The refusal of `result`. +fn refusal(result: Result) -> Refusal { + match result { + Err(Error::Refused(refusal)) => refusal, + other => panic!("not a refusal: {other:?}"), + } +} + +/// The limit of `result`. +fn limit(result: Result) -> Limit { + match result { + Err(Error::Limit(limit)) => limit, + other => panic!("not a limit: {other:?}"), + } +} + +/// Each class's range, and a grant at either end of it. +#[test] +fn a_grant_takes_a_range_inside_its_class() { + for (class, first, end) in [ + (IndexClass::StorageTexture, 1, 4096), + (IndexClass::Texture, 4096, 65_536), + (IndexClass::Sampler, 1, 4000), + ] { + assert_eq!(class.range(), first..end, "{class:?}"); + let mut grants = Grants::new(); + let whole = grants + .grant(class, first, end - first) + .unwrap_or_else(|error| panic!("{class:?}: {error}")); + assert_eq!( + (whole.class, whole.first, whole.count), + (class, first, end - first) + ); + grants.release(whole).expect("the release"); + for (first, count) in [(0, 1), (first - 1, 2), (end - 1, 2), (end, 1), (first, 0)] { + assert_eq!( + limit(grants.grant(class, first, count)), + Limit::IndexRange { + class, + first, + count + }, + "{class:?} {first} {count}" + ); + } + assert_eq!( + limit(grants.grant(class, u32::MAX, 2)), + Limit::IndexRange { + class, + first: u32::MAX, + count: 2 + } + ); + } +} + +/// An index has one grant at a time; a released range is granted again; the classes are apart. +#[test] +fn an_index_has_one_grant_at_a_time() { + let mut grants = Grants::new(); + let class = IndexClass::Sampler; + let held = grants.grant(class, 10, 5).expect("the grant"); + for (first, count, index) in [(10, 5, 10), (14, 3, 14), (8, 3, 10)] { + assert_eq!( + refusal(grants.grant(class, first, count)), + Refusal::IndicesGranted { class, index }, + "{first} {count}" + ); + } + // The same numbers of another class are free. + grants + .grant(IndexClass::StorageTexture, 10, 5) + .expect("another class's grant"); + let next = grants.grant(class, 15, 1).expect("the next index"); + grants.release(held).expect("the release"); + assert_eq!( + refusal(grants.release(held)), + Refusal::IndicesNotGranted { class, index: 10 } + ); + // A range partly granted is not released. + let mut partly = next; + partly.first = 14; + partly.count = 2; + assert_eq!( + refusal(grants.release(partly)), + Refusal::IndicesNotGranted { class, index: 14 } + ); + grants.grant(class, 10, 5).expect("the range again"); +} + +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod on_device { + use super::refusal; + use crate::arrays::Arrays; + use crate::tests::devices_of_the_cfgs_kind; + use crate::{Device, DeviceOptions, IndexClass, Instance, Refusal}; + use std::time::Instant; + + /// Set 1 is made with the device: its two default samplers are live while it is, grants + /// work through it, and making a second set 1 with every element written is timed. + #[test] + fn set_1_is_filled_at_creation() { + let instance = Instance::new(&[]).expect("an instance at the floor"); + let devices = devices_of_the_cfgs_kind(&instance); + assert!( + !devices.is_empty(), + "the loader lists no device of this cfg's kind" + ); + for (name, physical) in devices { + let device = Device::new(&physical, DeviceOptions::default()) + .unwrap_or_else(|error| panic!("{name}: {error}")); + let counters = device.counters(); + assert_eq!(counters.gauges().device_samplers, 2, "{name}"); + let grant = device + .grant_indices(IndexClass::Texture, 4096, 64) + .unwrap_or_else(|error| panic!("{name}: {error}")); + assert_eq!( + refusal(device.grant_indices(IndexClass::Texture, 4100, 1)), + Refusal::IndicesGranted { + class: IndexClass::Texture, + index: 4100 + }, + "{name}" + ); + device.release_indices(grant).expect("the release"); + let core = device.core(); + let start = Instant::now(); + // SAFETY: the device is live and made at the floor. + let second = unsafe { Arrays::new(&core.device, &counters) } + .unwrap_or_else(|error| panic!("{name}: a second set 1: {error}")); + let micros = start.elapsed().as_micros(); + assert_eq!(counters.gauges().device_samplers, 4, "{name}"); + // SAFETY: nothing used the second set 1 or a layout made from it. + unsafe { second.destroy(&core.device, &counters) }; + assert_eq!(counters.gauges().device_samplers, 2, "{name}"); + println!("M2V-MATRIX set1_make/{name} {micros} us"); + drop(device); + assert_eq!(counters.gauges().device_samplers, 0, "{name}"); + } + } +} diff --git a/crates/metal2vulkan-rt/src/tests/device.rs b/crates/metal2vulkan-rt/src/tests/device.rs index 40ef9568b..3c24f7bab 100644 --- a/crates/metal2vulkan-rt/src/tests/device.rs +++ b/crates/metal2vulkan-rt/src/tests/device.rs @@ -143,6 +143,8 @@ fn every_device_of_the_cfgs_kind_opens_presents_and_tears_down_to_zero() { .join() .expect("the presenting thread"); assert_eq!(submitted, expected, "{name}: the presenting queue"); + // Set 1's two default samplers, and nothing else. + assert_eq!(counters.gauges().device_samplers, 2, "{name}"); drop(device); let gauges = counters.gauges(); @@ -155,6 +157,7 @@ fn every_device_of_the_cfgs_kind_opens_presents_and_tears_down_to_zero() { ("descriptor_slots", gauges.descriptor_slots), ("blocks", gauges.blocks), ("events", gauges.events), + ("device_samplers", gauges.device_samplers), ] { println!("M2V-MATRIX gauge device_teardown/{kind}@drop {value}"); } @@ -292,8 +295,8 @@ fn every_device_of_the_cfgs_kind_enables_the_consumers_extensions_it_offers() { } /// The translator's profile on every device of the cfg's kind holds only what device creation -/// enabled: the floor's `robustImageAccess`, and none of the robustness features the runtime -/// leaves off, whatever the device reports. +/// enabled: the floor's `robustImageAccess` and `nullDescriptor`, and none of the robustness +/// features the runtime leaves off, whatever the device reports. #[cfg(any(m2v_gpu, m2v_cpu_icd))] #[test] fn every_device_of_the_cfgs_kind_gives_the_translator_only_what_it_enables() { @@ -310,18 +313,16 @@ fn every_device_of_the_cfgs_kind_gives_the_translator_only_what_it_enables() { let device = Device::new(physical, DeviceOptions::default()) .unwrap_or_else(|error| panic!("{name}: {error}")); let enabled = &device.core().translator.profile().enabled().features; - assert!( - enabled.contains(&VkFeature::RobustImageAccess), - "{name}: robustImageAccess" - ); + for on in [VkFeature::RobustImageAccess, VkFeature::NullDescriptor] { + assert!(enabled.contains(&on), "{name}: {on:?}"); + } for off in [ VkFeature::RobustImageAccess2, VkFeature::RobustBufferAccess, VkFeature::RobustBufferAccess2, - VkFeature::NullDescriptor, ] { assert!(!enabled.contains(&off), "{name}: {off:?}"); } - println!("profile: {name}: robustImageAccess alone of the robustness features"); + println!("profile: {name}: robustImageAccess and nullDescriptor alone of the robustness features"); } } diff --git a/crates/metal2vulkan-rt/src/tests/floor.rs b/crates/metal2vulkan-rt/src/tests/floor.rs index e2653fba0..f4dc4e8a2 100644 --- a/crates/metal2vulkan-rt/src/tests/floor.rs +++ b/crates/metal2vulkan-rt/src/tests/floor.rs @@ -74,6 +74,7 @@ fn at_the_floor() -> Queried { features.vulkan12.timeline_semaphore = vk::TRUE; features.vulkan13.synchronization2 = vk::TRUE; features.vulkan13.dynamic_rendering = vk::TRUE; + features.robustness2.null_descriptor = vk::TRUE; Queried { version: vk::make_api_version(0, 1, 3, 0), @@ -89,10 +90,10 @@ fn at_the_floor() -> Queried { .max_descriptor_set_update_after_bind_sampled_images(65_536) .max_per_stage_descriptor_update_after_bind_storage_images(4096) .max_descriptor_set_update_after_bind_storage_images(4096) - .max_per_stage_descriptor_update_after_bind_samplers(4000) - .max_descriptor_set_update_after_bind_samplers(4000) + .max_per_stage_descriptor_update_after_bind_samplers(3 * 4000) + .max_descriptor_set_update_after_bind_samplers(3 * 4000) .max_per_stage_update_after_bind_resources(65_536 + 4096 + 8) - .max_update_after_bind_descriptors_in_all_pools(65_536 + 4096 + 4000), + .max_update_after_bind_descriptors_in_all_pools(65_536 + 4096 + 3 * 4000), features, extensions: DEVICE_EXTENSIONS .iter() @@ -134,7 +135,8 @@ fn holds(features: &Features, feature: &crate::floor::Feature) -> bool { /// The translator's description is restricted to what device creation enables: a feature or an /// extension the device reports beyond the floor is outside the enable set, so the translator's -/// profile never relies on it, and the floor's `robustImageAccess` is in it. +/// profile never relies on it, and the floor's `robustImageAccess` and `nullDescriptor` are in it. +/// `VK_EXT_robustness2`'s robust buffer and image access stay off where the device reports them. #[test] fn the_translator_sees_only_what_device_creation_enables() { use crate::floor::shader_enables; @@ -143,12 +145,20 @@ fn the_translator_sees_only_what_device_creation_enables() { device.features.core.geometry_shader = vk::TRUE; device.features.vulkan12.sampler_mirror_clamp_to_edge = vk::TRUE; device.features.vulkan13.robust_image_access = vk::TRUE; - device - .extensions - .push(ash::ext::robustness2::NAME.to_owned()); + device.features.robustness2.robust_image_access2 = vk::TRUE; + device.features.robustness2.robust_buffer_access2 = vk::TRUE; let capabilities = decide(&device).unwrap_or_else(|below| panic!("{below}")); + assert_eq!( + capabilities.features.robustness2.robust_image_access2, + vk::FALSE + ); + assert_eq!( + capabilities.features.robustness2.robust_buffer_access2, + vk::FALSE + ); let enables = shader_enables(&capabilities); assert!(enables.features.contains(&VkFeature::RobustImageAccess)); + assert!(enables.features.contains(&VkFeature::NullDescriptor)); for reported in [ VkFeature::GeometryShader, VkFeature::SamplerMirrorClampToEdge, @@ -158,7 +168,8 @@ fn the_translator_sees_only_what_device_creation_enables() { ] { assert!(!enables.features.contains(&reported), "{reported:?}"); } - assert!(!enables.extensions.contains(&VkExtension::ExtRobustness2)); + // `nullDescriptor` comes with the extension, which device creation enables. + assert!(enables.extensions.contains(&VkExtension::ExtRobustness2)); } #[test] @@ -210,8 +221,9 @@ fn each_missing_feature_is_named() { const V13: &str = "VkPhysicalDeviceVulkan13Features"; const CORE: &str = "VkPhysicalDeviceFeatures"; const LAYOUT: &str = "VkPhysicalDeviceWorkgroupMemoryExplicitLayoutFeaturesKHR"; + const ROBUSTNESS2: &str = "VkPhysicalDeviceRobustness2FeaturesEXT"; type Clear = fn(&mut Features); - let cases: [(Clear, Missing); 30] = [ + let cases: [(Clear, Missing); 31] = [ ( |f| f.vulkan12.buffer_device_address = vk::FALSE, feature(V12, "bufferDeviceAddress"), @@ -347,6 +359,10 @@ fn each_missing_feature_is_named() { |f| f.vulkan13.dynamic_rendering = vk::FALSE, feature(V13, "dynamicRendering"), ), + ( + |f| f.robustness2.null_descriptor = vk::FALSE, + feature(ROBUSTNESS2, "nullDescriptor"), + ), ]; assert_eq!( cases.len(), @@ -399,15 +415,15 @@ fn each_low_limit_is_named() { ( |d| { d.vulkan12 - .max_per_stage_descriptor_update_after_bind_samplers = 3999 + .max_per_stage_descriptor_update_after_bind_samplers = 11_999 }, "maxPerStageDescriptorUpdateAfterBindSamplers", - 4000, + 12_000, ), ( - |d| d.vulkan12.max_descriptor_set_update_after_bind_samplers = 3999, + |d| d.vulkan12.max_descriptor_set_update_after_bind_samplers = 11_999, "maxDescriptorSetUpdateAfterBindSamplers", - 4000, + 12_000, ), ( |d| d.limits.max_sampler_allocation_count = 3999, @@ -420,9 +436,9 @@ fn each_low_limit_is_named() { 65_536 + 4096 + 8, ), ( - |d| d.vulkan12.max_update_after_bind_descriptors_in_all_pools = 65_536 + 4096 + 3999, + |d| d.vulkan12.max_update_after_bind_descriptors_in_all_pools = 65_536 + 4096 + 11_999, "maxUpdateAfterBindDescriptorsInAllPools", - 65_536 + 4096 + 4000, + 65_536 + 4096 + 12_000, ), ( |d| d.limits.max_push_constants_size = 255, @@ -691,6 +707,7 @@ fn every_missing_item_is_named_at_once() { [ Missing::Extension(ash::khr::swapchain::NAME), Missing::Extension(ash::khr::workgroup_memory_explicit_layout::NAME), + Missing::Extension(ash::ext::robustness2::NAME), feature("VkPhysicalDeviceFeatures", "shaderInt64"), feature("VkPhysicalDeviceVulkan13Features", "dynamicRendering"), Missing::Limit { @@ -707,7 +724,8 @@ fn every_missing_item_is_named_at_once() { assert_eq!( below.to_string(), "the device is below the runtime's floor: it lacks VK_KHR_swapchain; \ - VK_KHR_workgroup_memory_explicit_layout; VkPhysicalDeviceFeatures.shaderInt64; VkPhysicalDeviceVulkan13Features.dynamicRendering; \ + VK_KHR_workgroup_memory_explicit_layout; VK_EXT_robustness2; \ + VkPhysicalDeviceFeatures.shaderInt64; VkPhysicalDeviceVulkan13Features.dynamicRendering; \ maxPushConstantsSize 64, below 256; a queue family with graphics and compute; a memory \ type with VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | \ VK_MEMORY_PROPERTY_HOST_COHERENT_BIT for buffers" @@ -951,13 +969,15 @@ fn every_device_the_loader_lists_is_above_the_floor() { mut workgroup_layout, mut maximal_reconvergence, mut subgroup_uniform_control_flow, + mut robustness2, } = capabilities.features; let mut features = vk::PhysicalDeviceFeatures2::default() .features(core) .push_next(&mut vulkan11) .push_next(&mut vulkan12) .push_next(&mut vulkan13) - .push_next(&mut workgroup_layout); + .push_next(&mut workgroup_layout) + .push_next(&mut robustness2); let enabled = |name: &std::ffi::CStr| capabilities.extensions.contains(&name); if enabled(ash::khr::shader_maximal_reconvergence::NAME) { features = features.push_next(&mut maximal_reconvergence); diff --git a/crates/metal2vulkan-rt/src/tests/mod.rs b/crates/metal2vulkan-rt/src/tests/mod.rs index d7979992d..731f49a9c 100644 --- a/crates/metal2vulkan-rt/src/tests/mod.rs +++ b/crates/metal2vulkan-rt/src/tests/mod.rs @@ -1,3 +1,4 @@ +mod arrays; mod cache; mod command; mod compute; diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 1f48504ad..501b7aa5d 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,8 +37,8 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 6 | 6 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 11 | 11 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Limit` | 5 | 5 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 13 | 13 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Limit` | 6 | 6 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 4 | 4 | 0 | 0 | 0 | 0 | 0 | ## Totals by basis @@ -55,8 +55,8 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 6 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 2 | 5 | 0 | 0 | 4 | 0 | 0 | 0 | -| The new runtime's `Limit` | 0 | 0 | 0 | 3 | 2 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 2 | 5 | 0 | 0 | 6 | 0 | 0 | 0 | +| The new runtime's `Limit` | 0 | 0 | 0 | 3 | 3 | 0 | 0 | 0 | | The new runtime's `Gap` | 0 | 0 | 0 | 0 | 4 | 0 | 0 | 0 | ## 1. Translator and front-end refusals (`Unsupported`: a `Feature` and its `Needs`) @@ -623,6 +623,8 @@ Columns: | `NoBufferAtIndex` | `setBufferOffset` at an index where no buffer is bound | every device (a public call's own check of its arguments) | `ours`: there is no buffer whose offset to change | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` | `-` | | `ThreadgroupSize` | A threadgroup of no threads, or of more than the pipeline state's `maxTotalThreadsPerThreadgroup` | every device (a public call's own check of its arguments) | `metal-documented`: a threadgroup's threads total at most the state's `maxTotalThreadsPerThreadgroup` | 2: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` | `-` | | `IndirectOffset` | An indirect dispatch's argument offset that is not a multiple of 4, or that leaves fewer than 12 bytes (three 32-bit counts) in the buffer | every device (a public call's own check of its arguments) | `ours`: `vkCmdDispatchIndirect` reads three 32-bit counts at a 4-byte aligned offset inside the buffer | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` | `-` | +| `IndicesGranted` | A grant of an index already granted (`Device::grant_indices`) | every device (a public call's own check of its arguments) | `ours`: each index has one grant, so each resource ID names one object | 1: `crates/metal2vulkan-rt/src/arrays.rs (grant)` | `-` | +| `IndicesNotGranted` | A release of an index that is not granted (`Device::release_indices`) | every device (a public call's own check of its arguments) | `ours`: a grant is returned once | 1: `crates/metal2vulkan-rt/src/arrays.rs (release)` | `-` | ## 12. The new runtime's `Limit` (`Error::Limit(Limit)`) @@ -633,6 +635,7 @@ Columns: | `ThreadgroupShape` | A threadgroup longer on an axis than the device's `maxComputeWorkGroupSize` (the floor holds 1,024 by 1,024 by 64) | at the device's limit | `device`: the device's `maxComputeWorkGroupSize` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | | `ThreadgroupMemory` | A dispatch whose threadgroup memory, the kernel's own and the lengths set (each rounded up to 16 bytes), is past the device's... | at the device's limit | `device`: the device's `maxComputeSharedMemorySize` | 1: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` | `-` | | `BytesLength` | `setBytes` data longer than one parameter ring chunk | every device (a public call's own check of its arguments) | `ours`: a ring chunk is 64 KiB | 1: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)` | `-` | +| `IndexRange` | A grant of no indices, or one past its class's range (`Device::grant_indices`, [`IndexClass::range`]) | every device (a public call's own check of its arguments) | `ours`: the descriptor arrays are 65,536 sampled textures, 4,096 storage textures and 4,000 samplers of each use, and index 0 is nil | 1: `crates/metal2vulkan-rt/src/arrays.rs (grant)` | `-` | ## 13. The new runtime's `Gap` (`Error::Unsupported(Gap)`) @@ -1140,11 +1143,14 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::NoBufferAtIndex`: `crates/metal2vulkan-rt/src/encoder.rs (set_buffer_offset)` - `rt:Refusal::ThreadgroupSize`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch, 2 sites)` - `rt:Refusal::IndirectOffset`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)` +- `rt:Refusal::IndicesGranted`: `crates/metal2vulkan-rt/src/arrays.rs (grant)` +- `rt:Refusal::IndicesNotGranted`: `crates/metal2vulkan-rt/src/arrays.rs (release)` - `rt:Limit::BlockLen`: `crates/metal2vulkan-rt/src/memory.rs (dedicated_len)` - `rt:Limit::BlockIds`: `crates/metal2vulkan-rt/src/memory.rs (number)` - `rt:Limit::ThreadgroupShape`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` - `rt:Limit::ThreadgroupMemory`: `crates/metal2vulkan-rt/src/encoder.rs (dispatch)` - `rt:Limit::BytesLength`: `crates/metal2vulkan-rt/src/encoder.rs (set_bytes)` +- `rt:Limit::IndexRange`: `crates/metal2vulkan-rt/src/arrays.rs (grant)` - `rt:Gap::IndirectCommandBuffers`: `crates/metal2vulkan-rt/src/pipeline.rs (new_compute_pipeline_state)` - `rt:Gap::KernelInput`: `crates/metal2vulkan-rt/src/pipeline.rs (gap)` - `rt:Gap::PartialSimdgroups`: `crates/metal2vulkan-rt/src/pipeline.rs (emulated_kernel)`