From 9c7013f60b74f4e790efd5f64ea0b373f4fc8962 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 15 Nov 2026 14:37:33 -0800 Subject: [PATCH] RUNTIME 2387: host RAM copies: a dispatch writes its own imports alone into a partially bound import array What: the pages copy's owned kernel makes its first storage-buffer binding, the array of PagesCopyModule::imports(device) imports, VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT where the array holds more than one and the device enables descriptorBindingPartiallyBound (the runtime enables it wherever the device has it: device/enables.rs, Vulkan 1.2 features). Each dispatch of a copy then writes (pushes, or writes into its set) only its own imports, then the buffer's window and the table: OwnedKernel::first_written accepts a set that writes 1 to the array's length of the array's elements where the binding is partially bound, every element elsewhere, and buffer_place places the rest after them. Without the feature the elements past the dispatch's imports hold its first import again, as before. The kernel's making text carries the flag. Why: since RUNTIME 2322 every pages-copy dispatch wrote the whole array: on a device of 32 push descriptors (ANV, RADV, NVIDIA, lavapipe: 30 imports) a dispatch over one import pushed 32 storage-buffer descriptors where 3 serve, through push_set's heap path (past 16 writes) and the driver's vkCmdPushDescriptorSet, at every copy dispatch (358 to 813 a consumer's boot). No table entry names an element past the dispatch's imports, so no invocation accesses one. Vulkan: VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT "specifies that descriptors in this binding that are not dynamically used need not contain valid descriptors at the time the descriptors are consumed"; a push descriptor set layout takes it (VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-flags-03003 forbids such a layout only UPDATE_AFTER_BIND, UPDATE_UNUSED_WHILE_PENDING and VARIABLE_DESCRIPTOR_COUNT), and descriptorBindingPartiallyBound must be enabled for it. Test: host_ram_copy_device's a_dispatch_over_one_import_writes_its_own_descriptors_alone: rows of 4-byte texels in one chunk, one dispatch, the gathered bytes right, and the storage-buffer descriptors the owned kernel's set or push wrote (a test-only thread-local count, owned_kernel::buffers_written) 3 where the array is partially bound, the array's length and 2 elsewhere (32 before this change on lavapipe). Verified: m3-max-33702 (msi) at the lane tip 238fde9d64: clippy (runtime + validation, all targets, all features) 0, rustdoc 0; lavapipe host_ram_copy_device 32/32 (m3-max-33686, the same tree before its rebase), "an array of 30 imports, partially bound true: 3 storage-buffer descriptors written"; PHOENIX (RADV, carried m2v_gpu archive of 238fde9d64) host_ram_copy_device 32/32, 3 written (m3-max-33733); negative control (the whole array written again) fails the new test with 32 (m3-max-33700). clippy m2v_gpu / m2v_cpu_icd in 33722. --- .../metal2vulkan-runtime/src/host_ram/copy.rs | 19 ++- .../metal2vulkan-runtime/src/owned_kernel.rs | 116 +++++++++++++++--- .../src/tests/host_ram_copy_device.rs | 50 ++++++++ crates/metal2vulkan/src/cache/mod.rs | 2 +- 4 files changed, 161 insertions(+), 26 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/host_ram/copy.rs b/crates/metal2vulkan-runtime/src/host_ram/copy.rs index d4680edda..b6d889a78 100644 --- a/crates/metal2vulkan-runtime/src/host_ram/copy.rs +++ b/crates/metal2vulkan-runtime/src/host_ram/copy.rs @@ -141,8 +141,11 @@ //! list's), an array of up to the device's `PagesCopyModule::imports` of them (30 where it //! pushes descriptors and indexes arrays of storage buffers, 1 where it indexes none), the //! buffer's bytes and the table: a dispatch for each that many imports the runs touch, never one -//! region per run, and no other word of the runs' pages read or written. An array's elements no -//! import of the dispatch takes hold its first import again, so every descriptor of it is valid. +//! region per run, and no other word of the runs' pages read or written. A dispatch writes its +//! own imports alone into the array where the device enables `descriptorBindingPartiallyBound` +//! (the array partially bound: an element no invocation reads need not be valid, so a dispatch +//! over one import of an array of 30 writes 3 descriptors, not 32); elsewhere the elements past +//! them hold its first import again, so every descriptor of the array is valid. //! A copy whose bytes pass the device's storage range, or whose runs of one array pass its //! workgroup count, takes more (each window of the buffer's bytes, each part of the runs). //! Counted: `WorkCounts::host_ram_copies`, `host_ram_copy_bytes` and @@ -1969,13 +1972,19 @@ impl BlitCommandEncoder { }; let sets: Vec = (dispatches.iter()) .map(|dispatch| { - // The dispatch's imports, its array's elements; those past them hold its first - // again, a valid descriptor its entries name none of. + // The dispatch's imports, its array's elements, its entries naming no element past + // them: where the array is partially bound (`OwnedKernel::partial`), all the + // array's descriptors it writes, as no invocation reads another; else those past + // them hold its first again, a valid descriptor its entries name none of. let group = imports.get(dispatch.group * array..).unwrap_or_default(); let lead = group.first().ok_or_else(|| { crate::error::internal("a host RAM copy's dispatch over no import") })?; - let mut buffers: Vec<(vk::Buffer, u64, u64)> = (0..array) + let written = match kernel.partial { + true => group.len().min(array), + false => array, + }; + let mut buffers: Vec<(vk::Buffer, u64, u64)> = (0..written) .map(|element| { let chunk = group.get(element).unwrap_or(lead); (chunk.raw, 0, chunk.bytes()) diff --git a/crates/metal2vulkan-runtime/src/owned_kernel.rs b/crates/metal2vulkan-runtime/src/owned_kernel.rs index 28fdfd799..9af43e6ff 100644 --- a/crates/metal2vulkan-runtime/src/owned_kernel.rs +++ b/crates/metal2vulkan-runtime/src/owned_kernel.rs @@ -49,6 +49,7 @@ use metal2vulkan::bind::{ ChromaDecode, MipmapFilterKernel, RewritePhase, RewriteProgram, ShadowMergeRead, ShadowMergeStores, ShadowTexelView, TessellationScanKernel, YCbCrCodes, YCbCrConversion, }; +use metal2vulkan::device::VkFeature; use metal2vulkan::metal::format::ExtendedRange; use std::collections::HashMap; use std::sync::{Mutex, OnceLock}; @@ -106,7 +107,8 @@ pub(super) enum OwnedModule { IcbReset, /// `bind::pages_copy_module` of one direction: runs of words, up to a 4 KiB page each, copied /// between imports of a guest RAM (an array of the device's `PagesCopyModule::imports` of - /// them, its first binding) and a buffer by a table of them, a gather or a scatter + /// them, its first binding, partially bound where the device lets it be: + /// [`OwnedKernel::partial`]) and a buffer by a table of them, a gather or a scatter /// (`host_ram/copy.rs`). PagesCopy(metal2vulkan::bind::PagesCopy), /// `bind::extended_canonical_module`: Metal's canonical encoding of `BGRA10_XR` texels @@ -585,6 +587,12 @@ pub(super) struct OwnedKernel { pub(super) buffers: u32, /// The descriptors of the first of them: an array's ([`OwnedModule::first_buffers`]), else 1. pub(super) first_buffers: u32, + /// Whether that array is partially bound (`VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT`): where + /// it holds more than one and the device enables `descriptorBindingPartiallyBound`. A set + /// then writes as few of its elements as its dispatch's shader reads, at least one + /// ([`OwnedKernel::first_written`]): an element no invocation accesses need not hold a valid + /// descriptor. Else a set writes every element. + pub(super) partial: bool, /// Whether set 0's layout is a push descriptor set's: its dispatches push their descriptors /// (`vkCmdPushDescriptorSetKHR`) in place of a set from a pool. pub(super) pushed: bool, @@ -1002,9 +1010,12 @@ impl Device { return Ok(kernel); } let (spirv, buffers, push_bytes) = which.build(self)?; + let first_buffers = which.first_buffers(self); + let partial = first_buffers > 1 + && (self.enabled().features).contains(&VkFeature::DescriptorBindingPartiallyBound); let bindings = ( (which.images(), which.storage_images()), - (buffers, which.first_buffers(self)), + (buffers, first_buffers, partial), ); let baked = match which { OwnedModule::YCbCrSample(sampler, ..) | OwnedModule::ChromaSample(sampler) => { @@ -1031,14 +1042,15 @@ impl Device { /// The objects of a kernel of `spirv` (entry point `main`), its pipeline named `name`'s answer /// (`DeviceShared::name_pipeline`), with `images` sampled images, then `storage_images` storage /// images and then `buffers` storage-buffer bindings in set 0, the first an array of -/// `first_buffers` (one where 1), a push descriptor set's where `pushed`, and `push_bytes` of +/// `first_buffers` (one where 1), partially bound where `partial` ([`OwnedKernel::partial`]), a +/// push descriptor set's where `pushed`, and `push_bytes` of /// `COMPUTE` push constants. With `baked`, a sampler of a Y′CbCr conversion and the descriptors a /// combined image sampler of it takes, its first binding is that combined image sampler, the /// sampler immutable. fn make( device: &Device, (spirv, name): (&[u32], impl FnOnce() -> String), - ((images, storage_images), (buffers, first_buffers)): ((u32, u32), (u32, u32)), + ((images, storage_images), (buffers, first_buffers, partial)): ((u32, u32), (u32, u32, bool)), (push_bytes, pushed): (u32, bool), baked: Option<(vk::Sampler, u32)>, ) -> Result { @@ -1056,6 +1068,7 @@ fn make( storage_images, buffers, first_buffers, + partial, pushed, combined, }; @@ -1082,7 +1095,22 @@ fn make( } }) .collect(); + // The first storage-buffer binding's array partially bound, the other bindings not; a + // push descriptor set layout takes the flag (of the binding flags, + // VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-flags-03003 refuses it only + // update-after-bind, update-unused-while-pending and a variable count). + let flags: Vec = (0..images + storage_images + buffers) + .map(|binding| match binding == images + storage_images { + true => vk::DescriptorBindingFlags::PARTIALLY_BOUND, + false => vk::DescriptorBindingFlags::empty(), + }) + .collect(); + let mut binding_flags = + vk::DescriptorSetLayoutBindingFlagsCreateInfo::default().binding_flags(&flags); let mut info = vk::DescriptorSetLayoutCreateInfo::default().bindings(&bindings); + if partial { + info = info.push_next(&mut binding_flags); + } if pushed { info = info.flags(vk::DescriptorSetLayoutCreateFlags::PUSH_DESCRIPTOR_KHR); } @@ -1111,7 +1139,7 @@ fn make( Making::new("owned kernel").words(spirv).text(&( images, storage_images, - (buffers, first_buffers), + (buffers, first_buffers, partial), push_bytes, pushed, )), @@ -1166,26 +1194,66 @@ impl OwnedKernel { } } + /// The elements of its first storage-buffer binding a set of `given` storage-buffer + /// descriptors writes, in binding order: every one ([`buffer_descriptors`] given), or, where + /// that binding is partially bound ([`OwnedKernel::partial`]), as few as one, the rest of its + /// array left unwritten. `None` for any other count. + /// + /// [`buffer_descriptors`]: OwnedKernel::buffer_descriptors + fn first_written(&self, given: usize) -> Option { + let given = u32::try_from(given).ok()?; + let Some(others) = self.buffers.checked_sub(1) else { + return (given == 0).then_some(0); + }; + let first = given.checked_sub(others)?; + let fewer = self.partial && (1..self.first_buffers).contains(&first); + (first == self.first_buffers || fewer).then_some(first) + } + /// The binding and array element of its set 0's `n`-th storage-buffer descriptor, in binding - /// order: the first binding's elements, then one a binding. - fn buffer_place(&self, n: u32) -> (u32, u32) { - let first = self.images + self.storage_images; - match n.checked_sub(self.first_buffers) { - None => (first, n), - Some(after) => (first + 1 + after, 0), + /// order, of a set that writes `first` elements of the first binding + /// ([`OwnedKernel::first_written`]): those elements, then one a binding. + fn buffer_place(&self, n: u32, first: u32) -> (u32, u32) { + let binding = self.images + self.storage_images; + match n.checked_sub(first) { + None => (binding, n), + Some(after) => (binding + 1 + after, 0), } } } /// What one set of an [`OwnedKernel`] binds: its sampled images' views, then its storage images' /// views, each in the `GENERAL` layout, then its storage-buffer descriptors' `(buffer, offset, -/// range)`, the first binding's array elements first ([`OwnedKernel::buffer_place`]). +/// range)`, the first binding's array elements first ([`OwnedKernel::buffer_place`]): all of +/// them, or as few as its dispatch reads where the array is partially bound +/// ([`OwnedKernel::first_written`]). pub(super) struct OwnedSet { pub(super) images: Vec, pub(super) storage_images: Vec, pub(super) buffers: Vec<(vk::Buffer, u64, u64)>, } +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +thread_local! { + /// The storage-buffer descriptors this thread wrote into owned kernels' sets or their pushes + /// ([`OwnedSets::write_each`], [`OwnedBinds::new`]), in the device tests that read it + /// (`tests::host_ram_copy_device`). + static BUFFERS_WRITTEN: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Count `written` storage-buffer descriptors of an owned kernel's set or push. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +fn note_buffers_written(written: usize) { + BUFFERS_WRITTEN.with(|count| count.set(count.get() + written as u64)); +} + +/// How many storage-buffer descriptors this thread wrote into owned kernels' sets or pushes so +/// far. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) fn buffers_written() -> u64 { + BUFFERS_WRITTEN.with(std::cell::Cell::get) +} + /// The descriptor sets of one command's dispatches of its kernels, from pools of the device's /// spares (the module docs). pub(super) struct OwnedSets { @@ -1301,7 +1369,7 @@ impl OwnedSets { || sets.iter().zip(kernels).any(|(set, kernel)| { set.images.len() != kernel.images as usize || set.storage_images.len() != kernel.storage_images as usize - || set.buffers.len() != kernel.buffer_descriptors() as usize + || kernel.first_written(set.buffers.len()).is_none() }) { return Err(internal("owned sets that do not match their kernel")); @@ -1362,8 +1430,12 @@ impl OwnedSets { .image_info(std::slice::from_ref(info)), ); } + let first = (kernel.first_written(buffers.len())) + .ok_or_else(|| internal("owned sets that do not match their kernel"))?; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + note_buffers_written(buffers.len()); for (n, info) in (0..).zip(buffers) { - let (binding, element) = kernel.buffer_place(n); + let (binding, element) = kernel.buffer_place(n, first); writes.push( vk::WriteDescriptorSet::default() .dst_set(*set) @@ -1494,12 +1566,16 @@ impl OwnedBinds { }; let mut pushed = Vec::with_capacity(sets.len()); for set in sets { - if set.images.len() != kernel.images as usize - || set.storage_images.len() != kernel.storage_images as usize - || set.buffers.len() != kernel.buffer_descriptors() as usize - { + let first = kernel.first_written(set.buffers.len()); + let (Some(first), true) = ( + first, + set.images.len() == kernel.images as usize + && set.storage_images.len() == kernel.storage_images as usize, + ) else { return Err(internal("owned binds that do not match their kernel")); - } + }; + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + note_buffers_written(set.buffers.len()); let images = set .images .iter() @@ -1519,7 +1595,7 @@ impl OwnedBinds { let buffers = (0..) .zip(&set.buffers) .map(|(n, &(buffer, offset, range))| { - let (binding, element) = kernel.buffer_place(n); + let (binding, element) = kernel.buffer_place(n, first); let info = vk::DescriptorBufferInfo { buffer, offset, diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs index 7efb06345..89032399e 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_copy_device.rs @@ -38,6 +38,10 @@ //! (a dispatch per array of imports) and no region: every other byte of their pages (each a //! pattern) stays. A scatter of such runs that //! name bytes twice takes regions, and leaves the later's. +//! - **A dispatch over one import writes its own descriptors**: rows of 4-byte texels in one +//! chunk, gathered by one dispatch, write that import, the buffer's window and the table into +//! the pages copy's set (3 storage-buffer descriptors) where its array is partially bound (the +//! device enables `descriptorBindingPartiallyBound`), the whole array and those two elsewhere. //! - **A laid-out surface in one call**: rows at a pitch over scattered pages (two side by side, //! one before the first chunk's end, one in the second), each run at its byte of a buffer that //! keeps the layout (`copy_runs_from_host_ram`, `copy_runs_to_host_ram`): rows of 4-byte texels @@ -744,6 +748,52 @@ fn runs_of_words_inside_pages_take_dispatches_alone_and_leave_the_rest_of_their_ ); } +#[test] +fn a_dispatch_over_one_import_writes_its_own_descriptors_alone() { + let Some(device) = device() else { + return; + }; + let (ram, start) = new_ram(None); + let _used = device.use_host_ram(&ram).unwrap(); + // Rows of 4-byte texels in the first chunk alone: one dispatch, over its one import. + let runs: Vec> = (0..3) + .map(|y| { + let row = start + 20 * PAGE + 16 + 2048 * y; + row..row + 2044 + }) + .collect(); + write_pattern(start + 20 * PAGE..start + 22 * PAGE, 5); + let total: u64 = runs.iter().map(|run| run.end - run.start).sum(); + let out = shared(&device, total, |_| 0xee); + let before = (device.work_counts(), crate::owned_kernel::buffers_written()); + blit(&device, |encoder| { + encoder.copy_from_host_ram(&ram, &runs, &out, 0).unwrap(); + }); + let written = crate::owned_kernel::buffers_written() - before.1; + assert!(contents(&out) == gathered(&runs), "the gathered bytes"); + let after = device.work_counts(); + assert_eq!( + after.host_ram_copy_dispatches - before.0.host_ram_copy_dispatches, + 1 + ); + let array = metal2vulkan::bind::PagesCopyModule::imports(device.compile_device()); + let partial = array > 1 + && (device.enabled().features) + .contains(&metal2vulkan::device::VkFeature::DescriptorBindingPartiallyBound); + eprintln!( + "HOST-RAM-COPY: an array of {array} imports, partially bound {partial}: {written} \ + storage-buffer descriptors written" + ); + let want = match partial { + true => 1 + 2, + false => u64::from(array) + 2, + }; + assert_eq!( + written, want, + "the import, the buffer's window and the table, the rest of a partially bound array unwritten" + ); +} + /// The pages of a laid-out surface: its 4 KiB pages lie apart in the RAM, two of them side by /// side, one before the first chunk's end and one in the second chunk. const SURFACE_PAGES: [u64; 8] = [30, 12, 13, SECOND - 1, SECOND + 2, 7, 50, 51]; diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d3751ffd9..f06a9802e 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2386; +pub const RUNTIME_VERSION: u32 = 2387; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles