From 123a9919fce9cb0792c2de9573b8d3cf9bcec8fd Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 22 Oct 2026 19:28:30 +0300 Subject: [PATCH] List argument samplers at each batch's submission, and retire resource-id-takeover The steps this packet landed as, in order: - Refuse the private option bit where Metal ends the process, and take it where Metal ignores it - Drop the GPU's writes to no-copy memory of the private option bit on macOS - Let a host step ask the driver for a heap set's layout support - Run a command that leaves a live sampler state out, announced, instead of failing it - Record what a read-only view of no-copy pages costs Content: the tree of `development` at abc094a6c3, unchanged. --- crates/metal2vulkan-runtime/src/buffer.rs | 25 +- .../src/buffer_descriptor.rs | 116 ++++++--- .../src/buffer_texture.rs | 2 +- .../src/command_buffer/mod.rs | 145 +++++++---- .../src/command_buffer/submit.rs | 10 + crates/metal2vulkan-runtime/src/compute.rs | 2 +- .../metal2vulkan-runtime/src/degradation.rs | 134 +++++++--- crates/metal2vulkan-runtime/src/device/mod.rs | 6 +- .../metal2vulkan-runtime/src/device/prime.rs | 3 + crates/metal2vulkan-runtime/src/error.rs | 18 -- crates/metal2vulkan-runtime/src/exactness.rs | 1 - crates/metal2vulkan-runtime/src/heap.rs | 14 +- crates/metal2vulkan-runtime/src/heap_sets.rs | 88 ++----- crates/metal2vulkan-runtime/src/lib.rs | 1 + crates/metal2vulkan-runtime/src/memory.rs | 57 ++++- .../src/read_only_view.rs | 137 ++++++++++ crates/metal2vulkan-runtime/src/render.rs | 2 +- .../metal2vulkan-runtime/src/resource_ids.rs | 2 +- crates/metal2vulkan-runtime/src/sampler.rs | 14 +- .../src/sampler_listing.rs | 139 +++++++---- .../src/tests/command_buffer.rs | 1 - .../src/tests/exactness.rs | 20 +- crates/metal2vulkan-runtime/src/texture.rs | 8 +- .../src/texture/shared.rs | 2 +- .../src/texture/wrapped.rs | 2 +- crates/metal2vulkan-runtime/src/values.rs | 22 +- .../metal2vulkan-runtime/src/work_counts.rs | 30 +-- .../src/wrapped_buffer.rs | 2 +- .../src/runtime_lane/degrade_notices.rs | 234 ++++++++++++++---- .../src/runtime_lane/host_memory.rs | 3 +- .../src/runtime_lane/render_executions.rs | 31 ++- .../src/runtime_lane/resource_ids.rs | 146 +++++++---- crates/metal2vulkan/src/bind/heap/tests.rs | 4 +- .../src/tests/engine_heap_binder.rs | 3 +- docs/API.md | 36 ++- docs/REFUSALS.md | 58 ++--- 36 files changed, 1037 insertions(+), 481 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/read_only_view.rs diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index e9b1247be..c14709bc3 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -160,6 +160,10 @@ pub(super) struct HostCell { /// The device whose work counts each look at its pages adds to /// (`WorkCounts::no_copy_lies_read`). device: Device, + /// The GPU's writes to the buffer are dropped, as Metal's private option bit 24 drops them: + /// its pages are imported through a read-only view of them (`read_only_view.rs`), which a + /// rebind's are too. + drops_writes: bool, } /// The textures over a buffer's host pages ([`HostCell`]): their images, which a detach makes @@ -348,6 +352,11 @@ impl Drop for HostCell { } impl HostCell { + /// Whether the GPU's writes to the buffer are dropped (`read_only_view.rs`). + pub(super) fn drops_writes(&self) -> bool { + self.drops_writes + } + /// The pages the buffer lies in now; `None` while it is detached. pub(super) fn current(&self) -> Option> { self.device.shared().counts.no_copy_lie_read(); @@ -832,6 +841,9 @@ pub(super) struct Shape { pub(super) type_index: u32, /// The pages were imported as dma-bufs (`dma_buf.rs`), not by their pointer. pub(super) over_dma_buf: bool, + /// The pages were imported through a read-only view of them, which drops the GPU's writes + /// (`read_only_view.rs`). + pub(super) drops_writes: bool, } impl Shape { @@ -845,6 +857,7 @@ impl Shape { mapped: placement.mapped, type_index: placement.type_index(), over_dma_buf: placement.over_dma_buf(), + drops_writes: placement.over_read_only_view(), } } @@ -857,12 +870,14 @@ impl Shape { self.reach, self.type_index, self.over_dma_buf, + self.drops_writes, ) == ( other.offset, other.base, other.reach, other.type_index, other.over_dma_buf, + other.drops_writes, ) && at(self) == at(other) } } @@ -1019,6 +1034,12 @@ impl HostImport { } } + /// Whether its pages were imported through a read-only view of them, which drops the GPU's + /// writes (`read_only_view.rs`). + pub(super) fn drops_writes(&self) -> bool { + self.shape.drops_writes + } + /// Its residency, where the device may release it while idle. #[cfg(unix)] pub(super) fn residency(&self) -> Option<&Residency> { @@ -1790,7 +1811,7 @@ impl Device { /// (`Invalid`). pub fn new_buffer(&self, length: u64, options: ResourceOptions) -> Result { self.keep_room(); - let options = self.take_options("new_buffer", options); + let options = self.own_memory_options("new_buffer", options)?; let (buffer, class) = self.buffer_of_length("new_buffer", length, options, AddressPlacement::Any)?; self.degrade_system_memory(&buffer, class, || { @@ -2322,6 +2343,7 @@ impl Device { /// A no-copy buffer's lie, of `key`: pages of its own in `import`, released to `release` /// once nothing holds them, which a rebind replaces (`rebind.rs`). fn host_lie(&self, key: ResourceKey, import: Arc, release: Option) -> Lie { + let drops_writes = import.drops_writes(); let host = HostPages::new(import); if let Some(release) = release { host.release_to(release); @@ -2332,6 +2354,7 @@ impl Device { textures: Mutex::new(TexturesOver::default()), exposed: AtomicU8::new(0), device: self.clone(), + drops_writes, }); self.shared().rebinds.register(key, &cell); Lie::Host(cell) diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index bf06b7194..758a285ab 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -26,6 +26,7 @@ use super::host_memory::{ #[cfg(unix)] use super::host_residency::Again; use super::memory::{ImportFailure, MemoryClass, Placement}; +use super::read_only_view::ReadOnlyView; use super::rebind::RebindProblem; use super::texture::stand_in::TextureImages; use super::texture::Remade; @@ -215,7 +216,10 @@ impl Device { } (None, None) => Place::At(placement), }; - let resource_options = self.take_options(CALL, resource_options); + let (resource_options, drops_writes) = match contents { + BufferContents::NoCopy { .. } => self.no_copy_options(CALL, resource_options), + _ => (self.own_memory_options(CALL, resource_options)?, false), + }; let buffer = match contents { BufferContents::Zero => self.zero_buffer(CALL, length, resource_options, place), BufferContents::Copy(bytes) => { @@ -239,6 +243,7 @@ impl Device { HostRelease::new(deallocator, keep_alive), place, false, + drops_writes, ) }, }?; @@ -258,7 +263,7 @@ impl Device { ) -> Result { const CALL: &str = "new_buffer_with_bytes"; self.keep_room(); - let options = self.take_options(CALL, options); + let options = self.own_memory_options(CALL, options)?; let buffer = self.buffer_with_bytes(CALL, bytes, options, AddressPlacement::Any)?; Ok(self.visible(buffer)) } @@ -277,7 +282,10 @@ impl Device { /// GiB measured on an M4 and an M3 Max), where Metal makes the buffer at once and pays at the /// first command using it (24 to 88 ms per GiB). Where the device refuses the pointer and /// `memory` carries a dma-buf source ([`HostMemory::with_dma_buf`]), the dma-bufs it makes of - /// the pages are imported instead. + /// the pages are imported instead. With Metal's private option bit 24 + /// ([`ResourceOptions::PRIVATE_BIT`]), the GPU's writes to the pages are dropped, as Metal's + /// are: on macOS the pages are imported through a read-only view of them, by their pointer + /// alone; elsewhere the GPU's writes reach them, announced (`private-resource-option`). /// /// Refused: a length of 0 or past `max_buffer_length` (`Nil`, as plain Metal answers nil); /// `Private` or `Memoryless` storage, as Metal stops them, and an undefined @@ -302,7 +310,7 @@ impl Device { deallocator: Option, ) -> Result { const CALL: &str = "new_buffer_with_bytes_no_copy"; - let options = self.take_options(CALL, options); + let (options, drops_writes) = self.no_copy_options(CALL, options); // SAFETY: the caller's contract. let buffer = unsafe { self.buffer_over_host_memory( @@ -313,6 +321,7 @@ impl Device { HostRelease::new(deallocator, None), AddressPlacement::Any.into(), false, + drops_writes, ) }?; Ok(self.visible(buffer)) @@ -409,7 +418,10 @@ impl Device { /// buffer when `of_heap` (`heap.rs`, `Device::new_heap_with_bytes_no_copy`), whose memory /// must start at a multiple of the import's unit, the larger of the host page and the /// device's `minImportedHostPointerAlignment`, so that the heap's offsets are its memory's - /// (`Invalid`, `HeapProblem::HostMemoryAlignment`, elsewhere). + /// (`Invalid`, `HeapProblem::HostMemoryAlignment`, elsewhere). Where `drops_writes` (Metal's + /// private option bit 24, [`Device::no_copy_options`]), the pages are imported through a + /// read-only view of them, which drops the GPU's writes (`read_only_view.rs`): an import of + /// its own, which no other buffer lies in or joins, and which the device keeps imported. /// /// # Safety /// @@ -423,6 +435,7 @@ impl Device { release: HostRelease, placement: Place, of_heap: bool, + drops_writes: bool, ) -> Result { let modes = Modes::of(options)?; let class = match modes.storage { @@ -444,7 +457,7 @@ impl Device { .as_ref() .map_err(|unsupported| Error::Unsupported(unsupported.clone()))?; let (pointer, source, writable) = memory.into_parts(); - let host = host_window(call, importer, pointer, length, source)?; + let host = host_window(call, importer, pointer, length, source, drops_writes)?; let window = host.window; if of_heap && window.offset != 0 { let alignment = importer.page.max(importer.alignment); @@ -453,10 +466,10 @@ impl Device { } // A buffer over the bytes a live no-copy buffer was made over, of its memory class, lies // in its import (`host_aliases.rs`), its dma-buf source dropped uncalled; a heap's own - // buffer imports its own. + // buffer imports its own, as does one whose GPU writes are dropped. let made_over = (pointer.as_ptr() as u64, length); let release = release.of(pointer, length); - let shares = (!of_heap) + let shares = (!of_heap && !drops_writes) .then(|| shared.aliases.import(made_over, class)) .flatten(); if shares.is_none() && !of_heap && shared.aliases.inside_live(made_over, class) { @@ -483,12 +496,12 @@ impl Device { // A no-copy buffer's own import of dma-bufs keeps them, so the device may release it // while idle and import them again (`host_residency.rs`), as it may its own import of // the pointer where the driver's pointer imports follow their address; a heap's import - // stays. + // stays, as does an import of a read-only view. let (buffer, memory, again) = match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }? { Ok((buffer, memory)) => { #[cfg(unix)] - let again = (!of_heap) + let again = (!of_heap && !drops_writes) .then(|| Again::pointer(self, pointer, (length, window, class))) .flatten(); #[cfg(not(unix))] @@ -532,10 +545,10 @@ impl Device { again, }); // A buffer over the bytes another no-copy buffer covers joins it (`host_aliases.rs`), and - // a later one lies in its import. + // a later one lies in its import; one whose GPU writes are dropped joins none. // A buffer just made lies in its pages (`HostCell::current`). let current = buffer.host_cell().and_then(|cell| cell.current()); - if let (false, Some(current)) = (of_heap, current) { + if let (false, false, Some(current)) = (of_heap, drops_writes, current) { shared .aliases .join(buffer.identity().key, made_over, class, current.import()); @@ -592,7 +605,9 @@ impl Device { .as_ref() .map_err(|unsupported| Error::Unsupported(unsupported.clone()))?; let (pointer, source, writable) = memory.into_parts(); - let host = host_window(call, importer, pointer, length, source)?; + // A buffer whose GPU writes are dropped keeps them dropped over its new pages. + let drops_writes = cell.drops_writes(); + let host = host_window(call, importer, pointer, length, source, drops_writes)?; let window = host.window; if heap.is_some() && window.offset != 0 { let alignment = importer.page.max(importer.alignment); @@ -617,10 +632,9 @@ impl Device { // dropped uncalled: they pin no page, that import's making asked about the same window, // and the pages stay writable while imported (`HostMemory::new`). A heap's own buffer // imports its own, whose images bound to its bytes are made again over the new import's - // memory or its dma-bufs. + // memory or its dma-bufs, as does a buffer whose GPU writes are dropped. let made_over = (pointer.as_ptr() as u64, length); - let shares = heap - .is_none() + let shares = (heap.is_none() && !drops_writes) .then(|| shared.aliases.import(made_over, class)) .flatten(); let (pages, remade) = match shares { @@ -856,11 +870,13 @@ impl Device { by_pointer, source, unwritable: _, + drops_writes, } = host; let refusal = match by_pointer { // SAFETY: the caller's. - true => match unsafe { self.import_pointer(importer, pointer, length, &window, class) } - { + true => match unsafe { + self.import_pointer(importer, pointer, length, &window, class, drops_writes) + } { Ok(imported) => return Ok(Ok(imported)), Err(error) if refused(&error) => error, Err(error) => return Err(error), @@ -872,8 +888,9 @@ impl Device { /// The `VkBuffer` of a no-copy buffer of `length` bytes at `pointer`, made for host /// allocations and bound in the import of the window's pages at their pointer - /// (`VK_EXT_external_memory_host`), `buffer.base` bytes below the window's offset, as memory - /// of `class`: the buffer and the placement. Released again on failure. + /// (`VK_EXT_external_memory_host`), or of a read-only view of them where `drops_writes` + /// (`read_only_view.rs`), `buffer.base` bytes below the window's offset, as memory of + /// `class`: the buffer and the placement. Released again on failure. /// /// # Safety /// @@ -886,10 +903,12 @@ impl Device { length: u64, window: &ImportWindow, class: MemoryClass, + drops_writes: bool, ) -> Result<(HostBuffer, Placement), Error> { let buffer = self.host_buffer(window, length)?; // The window starts `window.offset` bytes before the pointer, in the pages it touches. let start = pointer.as_ptr().wrapping_sub(window.offset as usize); + let class = (class, drops_writes); // SAFETY: the caller's, and the buffer is a new one of this device. match unsafe { self.import_backing(importer, &buffer, start, window, class) } { Ok(placement) => Ok((buffer, placement)), @@ -924,9 +943,11 @@ impl Device { let window = &again.window; // SAFETY: the caller's pages stay mapped at the pointer while the buffer lives // (`HostMemory::new`), and the buffer outlives the placement: the import holds it, and a - // command buffer that reads it holds the buffer too. - let (buffer, placement) = - unsafe { self.import_pointer(importer, pointer, again.length, window, again.class) }?; + // command buffer that reads it holds the buffer too. An import of a read-only view is + // never made again (`Device::buffer_over_host_memory`). + let (buffer, placement) = unsafe { + self.import_pointer(importer, pointer, again.length, window, again.class, false) + }?; Ok(self.pages_of( buffer.raw, placement, @@ -1033,8 +1054,10 @@ impl Device { } /// Import the window's pages at `start` and bind `buffer` in them, `buffer.base` bytes below - /// the window's offset, as memory of `class`: the placement. Released again on failure but - /// the buffer. + /// the window's offset, as memory of `class`: the placement. Where `drops_writes`, a + /// read-only view of the pages is imported in their place (`read_only_view.rs`); a view the + /// system cannot map is refused as host memory run out. Released again on failure but the + /// buffer. /// /// # Safety /// @@ -1047,15 +1070,27 @@ impl Device { buffer: &HostBuffer, start: *mut u8, window: &ImportWindow, - class: MemoryClass, + (class, drops_writes): (MemoryClass, bool), ) -> Result { let raw_device = self.shared().vk(); let requirements = &buffer.requirements; let at = binds_in(window, buffer.base, buffer.size, requirements) .map_err(|_| not_importable())?; let start = NonNull::new(start).ok_or_else(not_importable)?; - // SAFETY: `start` is host memory aligned to the import alignment (the window's). - let types = unsafe { importer.memory_types(raw_device, start) }.map_err(import_refused)?; + let view = match drops_writes { + // SAFETY: the window is whole host pages of the caller's mapped memory (the caller's + // contract; `import_window` rounds it out to the host page). + true => Some( + unsafe { ReadOnlyView::of(start, window.size) } + .ok_or(Error::OutOfMemory(MemoryKind::Host))?, + ), + false => None, + }; + let imported = view.as_ref().map_or(start, ReadOnlyView::pointer); + // SAFETY: the imported pages are host memory aligned to the import alignment (the + // window's). + let types = + unsafe { importer.memory_types(raw_device, imported) }.map_err(import_refused)?; let allowed = types & requirements.memory_type_bits; // An allocation past the device's, refused before the driver sees it. let largest = self @@ -1066,22 +1101,23 @@ impl Device { return Err(Error::OutOfMemory(MemoryKind::Device)); } // SAFETY: the caller's contract keeps the window mapped until the placement is freed, - // and the buffer is unbound. - unsafe { self.import_now(buffer.raw, start, window.size, allowed, class, at) } + // and the buffer is unbound; the view views the window whole. + unsafe { self.import_now(buffer.raw, (start, view), window.size, allowed, class, at) } } /// Import `size` bytes of host pages at `start` as memory of `class` among the types - /// `allowed`, and bind `raw` in them `at` bytes in: the placement. Released again on failure. + /// `allowed`, through `view` where given (`read_only_view.rs`), and bind `raw` in them `at` + /// bytes in: the placement. Released again on failure. /// /// # Safety /// /// The `size` bytes at `start` are host memory of this process that stays mapped until the - /// placement is freed; `raw` is an unbound buffer of this device made for host allocations, - /// whose requirements the pages meet from `at`. + /// placement is freed, and `view`, where given, views them whole; `raw` is an unbound buffer + /// of this device made for host allocations, whose requirements the pages meet from `at`. unsafe fn import_now( &self, raw: vk::Buffer, - start: NonNull, + pages: (NonNull, Option), size: u64, allowed: u32, class: MemoryClass, @@ -1091,7 +1127,7 @@ impl Device { let raw_device = shared.vk(); // SAFETY: the caller's contract keeps the pages mapped until the placement is freed. let placement = - unsafe { lock(&shared.memory).import_host(raw_device, start, size, allowed, class) } + unsafe { lock(&shared.memory).import_host(raw_device, pages, size, allowed, class) } .map_err(|failure| match failure { ImportFailure::NoMemoryType => not_importable(), ImportFailure::Vulkan(error) => import_refused(error), @@ -1116,6 +1152,9 @@ impl Device { /// The host pages a no-copy buffer (or a heap's own buffer) of some length imports /// ([`host_window`]). struct HostWindow { + /// The GPU's writes to them are dropped: they are imported through a read-only view of them + /// (`read_only_view.rs`), by their pointer alone. + drops_writes: bool, /// The pages: the range rounded out to the host page. window: ImportWindow, /// Whether the device's import alignment covers them, so that their pointer is imported @@ -1157,7 +1196,8 @@ fn writability_settled( /// The host pages a no-copy object of `length` bytes at `pointer` imports on the device of /// `importer`, for `call`: the pages the range touches ([`import_window`]), imported by their /// pointer where the device's import alignment covers them, else only as a dma-buf where the -/// caller gave a source the device can use. A source the device cannot use is dropped uncalled. +/// caller gave a source the device can use. A source the device cannot use is dropped uncalled, +/// as is any where `drops_writes` (imported through a read-only view, `read_only_view.rs`). /// Refused: memory past the address space's end (`Nil`, as Metal makes no buffer over it); a /// range the import alignment cannot cover, with no usable source (`Unsupported`, `HostMemory`). fn host_window( @@ -1166,8 +1206,9 @@ fn host_window( pointer: NonNull, length: u64, source: Option, + drops_writes: bool, ) -> Result { - let source = source.filter(|_| importer.imports_dma_bufs()); + let source = source.filter(|_| importer.imports_dma_bufs() && !drops_writes); let at = pointer.as_ptr() as u64; let window = import_window(at, length, importer.page, 1) .map_err(|_| nil(call, Problem::BufferLength { length }))?; @@ -1176,6 +1217,7 @@ fn host_window( return Err(not_importable()); } Ok(HostWindow { + drops_writes, window, by_pointer, source, diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index da6dc16b7..85f9a37c7 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -474,7 +474,7 @@ impl Buffer { let surface_facts = ycbcr_surface; let ycbcr_surface = ycbcr_surface.filter(|_| ycbcr(asked_format) && surface); let device = self.device(); - let asked = device.take_texture_options(call, descriptor); + let asked = device.texture_options(call, descriptor)?; device.check_texture_placement(call, asked.placement, asked.usage, asked.texture_type)?; let options = asked.resource_options; let storage = options.storage_mode()?; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 49884bae8..8cd4fdc44 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -70,7 +70,7 @@ use super::function_table::TableSnapshot; use super::gpu_pools::{IndexPool, PoolKind, PoolLease}; use super::gpu_time::{self, KernelTimes, Life, Placement, Stamped, Times}; use super::heap::Heap; -use super::heap_sets::HeapUse; +use super::heap_sets::{self, HeapUse}; use super::live_buffers::LiveTable; use super::pipeline::budget::Urgency; use super::pipeline::kept::StepNumbers; @@ -562,12 +562,13 @@ pub(super) struct State { pub(super) heaps: HeapUse, /// Its commands' function-table snapshots, written again as it commits. table_snapshots: Vec, - /// Its commands' sampler tables, listed again as it commits (`sampler_listing.rs`). + /// Its commands' sampler tables, listed again as it commits and as the batch holding each + /// command's encoder is submitted, until then (`sampler_listing.rs`). sampler_listings: Vec, /// As it committed, some command's plan could not list the sampler states live then /// (`sampler_listing.rs`), or a command a host step recorded after the commit left a live - /// state out of its argument samplers (`State::unlisted_argument_sampler`): it completes with - /// `CommandBufferError::UnlistedArgumentSampler` unless another error fails it first. + /// state out of its argument samplers (`State::unlisted_argument_sampler`): counted once + /// (`WorkCounts::unlisted_argument_sampler_buffers`). unlisted_argument_samplers: bool, /// The first ended encoder Metal fails the command buffer from, with the error (a render /// pass without attachments past 16384 a side, `CommandBufferError::RenderTargetSize`, or @@ -1102,28 +1103,80 @@ impl State { } } - /// Keep a command's sampler tables to list the argument samplers again as the command buffer - /// commits (`sampler_listing.rs`). A command a host step records after the commit lists the - /// states as they stand then, and one that leaves a live state out fails the command buffer - /// (`State::unlisted_argument_sampler`). - pub(super) fn list_samplers(&mut self, listing: SamplerListing) { + /// Keep a command's sampler tables, of the open encoder's command, to list the argument + /// samplers again as the command buffer commits and as the batch holding the encoder is + /// submitted (`sampler_listing.rs`). A command a host step records after the commit lists the + /// states as they stand then (`State::unlisted_argument_sampler`). + pub(super) fn list_samplers(&mut self, mut listing: SamplerListing) { if self.status == CommandBufferStatus::NotEnqueued { + listing.at_encoder(self.open_encoder_place()); self.sampler_listings.push(listing); } } - /// A command left a live sampler state out of its argument samplers, its variant's set-1 - /// sampler arrays holding fewer elements than the live states (`heap_sets::fit_samplers`). - /// Before the commit nothing follows here: the commit lists the command's samplers again and - /// fails the command buffer where the state still lives (`sampler_listing.rs`). A command a - /// host step records after the commit is listed by no commit, and its function would read the - /// neutral sampler where Metal's reaches the state by its ID, so the command buffer fails as it - /// completes (`CommandBufferError::UnlistedArgumentSampler`), counted once - /// (`WorkCounts::unlisted_argument_sampler_failures`). + /// The sampler tables kept from the `from`th on are of commands of the ended encoder at place + /// `encoder`: a segment recorded at the commit, from its encoder's logged work. + fn place_listings(&mut self, from: usize, encoder: usize) { + for listing in self.sampler_listings.iter_mut().skip(from) { + listing.at_encoder(encoder); + } + } + + /// As the batch holding parts `range` of the ended encoders is submitted, before its + /// `vkQueueSubmit`: its commands' argument samplers listed again where a state was made or + /// went since they were (`sampler_listing.rs`), on a device whose heap sets take writes while + /// command buffers that bind them are pending; a command whose plan cannot list them all runs + /// with those it can, and the first such command's `unlisted-argument-sampler` notice comes + /// back, for the caller to announce once with no lock of the command buffer's held. + pub(super) fn list_samplers_at_submission( + &mut self, + device: &Device, + range: Range, + ) -> Result, Error> { + if self.sampler_listings.is_empty() { + return Ok(None); + } + let Some(last) = range.end.checked_sub(1).map(|at| self.recorded[at].encoder) else { + return Ok(None); + }; + let due: Vec = self + .sampler_listings + .extract_if(.., |listing| listing.encoder() <= last) + .collect(); + if !heap_sets::unused_while_pending(device) { + return Ok(None); + } + let changed = device.sampler_slots_changed(); + let mut live = None; + let mut notice = None; + for mut listing in due.into_iter().filter(|listing| listing.stale(changed)) { + let live = live.get_or_insert_with(|| device.argument_samplers_at()); + let at = (live.0, &live.1[..]); + let relisted = listing.relist(device, at, &mut self.heaps)?; + if !relisted.samplers.is_empty() { + self.retained.push(Box::new(relisted.samplers)); + } + if let Some(unlisted) = relisted.unlisted { + notice.get_or_insert(unlisted); + } + } + if notice.is_some() { + self.unlisted_argument_sampler(device); + } + Ok(notice) + } + + /// A command left a live sampler state out of its argument samplers (`sampler_listing.rs`): + /// its variant's set-1 sampler arrays hold fewer elements than the live states + /// (`heap_sets::fit_samplers`), or its plan's tables fewer entries. Before the commit nothing + /// follows here: the commit lists the command's samplers again (`sampler_listing.rs`). After + /// it, as it commits, as a batch is submitted or as a host step records a command no commit + /// lists, its function reads the neutral sampler where Metal's reaches the state by its ID: the + /// command buffer is counted once (`WorkCounts::unlisted_argument_sampler_buffers`). pub(super) fn unlisted_argument_sampler(&mut self, device: &Device) { if self.status != CommandBufferStatus::NotEnqueued && !self.unlisted_argument_samplers { self.unlisted_argument_samplers = true; - device.shared().counts.unlisted_argument_sampler_failure(); + device.shared().counts.unlisted_argument_sampler_buffer(); } } @@ -2298,7 +2351,7 @@ impl CommandBuffer { ) -> Result<(), Error> { let device = &self.0.device; let committed = Instant::now(); - let (segments, failure, reached, hangs): (Vec<(Deferred, bool)>, _, _, _) = { + let (segments, places, failure, reached, hangs): (Vec<(Deferred, bool)>, Vec, _, _, _) = { let mut state = self.state(); let refusal = match run { CommitRun::AtCall => state.refusal(), @@ -2362,17 +2415,17 @@ impl CommandBuffer { if let Some(residency) = &mut state.residency { residency.sync_heaps(); } - let segments = state + let (segments, places) = state .recorded .iter() .filter(|recorded| runs(recorded.encoder)) - .flat_map(|encoder| &encoder.segments) - .map(|segment| (segment.work.clone(), segment.needs_step())) - .collect(); + .flat_map(|recorded| (recorded.segments.iter()).map(|at| (at, recorded.encoder))) + .map(|(segment, encoder)| ((segment.work.clone(), segment.needs_step()), encoder)) + .unzip(); // What of it the live buffers list once used, held weakly: the device's registries' // locks, which take no other, inside this one. let reached = state.reached(device.shared(), runs); - (segments, failure, reached, hangs) + (segments, places, failure, reached, hangs) }; // What the commands of its encoders that run use is resident from its commit on, as // Metal's is: a no-copy buffer or a heap among it is reached unnamed from here, by its @@ -2389,7 +2442,14 @@ impl CommandBuffer { // and announce degradations. let prepared: Result, Error> = segments .iter() - .map(|(work, host)| work.prepare(self, *host)) + .zip(&places) + .map(|((work, host), &encoder)| { + // The sampler tables its commands keep are its encoder's (`sampler_listing.rs`). + let before = self.state().sampler_listings.len(); + let prepared = work.prepare(self, *host); + self.state().place_listings(before, encoder); + prepared + }) .collect(); let prepared = match prepared { Ok(prepared) => prepared, @@ -2443,23 +2503,26 @@ impl CommandBuffer { } state.table_snapshots.clear(); // Its commands' argument samplers, the states live now, before its heap sets stop - // taking its writes (`sampler_listing.rs`). + // taking its writes; each batch's submission lists them again where a state was made + // or went since (`sampler_listing.rs`). if !state.sampler_listings.is_empty() { - let live = device.argument_samplers(); + let (changed, live) = device.argument_samplers_at(); let held = &mut *state; - for listing in &held.sampler_listings { - match listing.relist(device, &live, &mut held.heaps)? { - Some(samplers) if !samplers.is_empty() => { - held.retained.push(Box::new(samplers)); - } - Some(_) => {} - // Its plan cannot list them: the command buffer fails as it completes. - None => held.unlisted_argument_samplers = true, + let mut left_out = false; + for listing in &mut held.sampler_listings { + let relisted = listing.relist(device, (changed, &live), &mut held.heaps)?; + if !relisted.samplers.is_empty() { + held.retained.push(Box::new(relisted.samplers)); + } + // Its plan cannot list them all: it runs with those it lists. + if let Some(unlisted) = relisted.unlisted { + device.degrade(Degradation::UnlistedArgumentSampler, || unlisted); + left_out = true; } } - held.sampler_listings.clear(); - if held.unlisted_argument_samplers { - device.shared().counts.unlisted_argument_sampler_failure(); + if left_out && !held.unlisted_argument_samplers { + held.unlisted_argument_samplers = true; + device.shared().counts.unlisted_argument_sampler_buffer(); } } // Until it completes, an image retired from the device's heap waits for it, where @@ -3990,12 +4053,6 @@ impl CommandBufferShared { state.status = CommandBufferStatus::Error; state.error = Some(CommandBufferError::CubicArgumentSampler); } - // A command's plan could not list the sampler states live as it committed: - // its function may have missed one Metal's would reach. - if state.unlisted_argument_samplers && state.error.is_none() { - state.status = CommandBufferStatus::Error; - state.error = Some(CommandBufferError::UnlistedArgumentSampler); - } unmeasured_reach = report.captured_reach_unmeasured; state.report = Some(report); let counts = &self.device.shared().counts; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 530e405d7..d1186f43f 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -179,6 +179,7 @@ use super::hang; use super::kept_barriers::{KeptBarriers, SlotStamps}; use super::{lock, recording_error, submission_error, CommandBufferShared, State}; use crate::deferred::Deferred; +use crate::degradation::Degradation; use crate::encoder::RecordedSegment; use crate::error::CommandBufferError; use crate::error::{internal, Error}; @@ -393,6 +394,12 @@ impl CommandBufferShared { // check's code. let rebound = state.failing_at(device, index); let range = state.batch_range(index); + // Its commands' argument samplers, the states live now where some were made or went since + // they were listed (`sampler_listing.rs`); one its plan cannot list is announced below, + // with the lock let go of. + let unlisted = state + .list_samplers_at_submission(device, range.clone()) + .map_err(|error| recording_error(device, error))?; // A batch that begins with resource state encoders binds their updates first, after its // waits, which its work then waits for through the bind. let updates: Vec = state.recorded[range.clone()] @@ -1041,6 +1048,9 @@ impl CommandBufferShared { if rebound { device.degrade_encoded_use_rebound(rebound_use); } + if let Some(unlisted) = unlisted { + device.degrade_once(Degradation::UnlistedArgumentSampler, || unlisted); + } device.reach_stale_detached(reaches); let submission = Submission { queue, diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index 778154815..d5bb5b1bb 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -2291,7 +2291,7 @@ fn record( unlisted, &format!("kernel `{kernel}`'s dispatches"), ); - // A host step's dispatch, which no commit lists again, fails its command buffer. + // A host step's dispatch, which no commit lists again, runs with the states it listed. let mut held = core.command_buffer().state(); held.unlisted_argument_sampler(&device); } diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 9524f29ab..d90be9aad 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -793,28 +793,25 @@ degradations! { ImplementationDefinedReconvergence = "implementation-defined-reconvergence", Precision, "simdgroup operations after divergent control flow can see other lanes active than \ Metal's"; - /// A function can read a resource ID whose holder the runtime cannot give it as Metal's - /// command buffer reads it (`resource_ids.rs`, `sampler.rs`): a sampler state was made - /// while a committed command buffer not yet completed lists the argument samplers as it - /// committed. A texture's ID reaches its holder as the command buffer runs - /// (`heap_sets.rs`); a state live as a command buffer commits that its command's plan - /// cannot list fails it (`UnlistedArgumentSampler`). - ResourceIdTakeover = "resource-id-takeover", Precision, - "a function reading the ID can see an earlier holder of it, or the neutral \ - resource, where Metal's sees the resource holding it as the command buffer runs"; /// A sampler state whose element no set-1 sampler array can hold, as more states live /// than it holds (each takes the lowest element no live state holds, `resource_ids.rs`): /// the device's, as the state is made, or a pipeline's, as a command lists the argument - /// samplers or its command buffer lists them again as it commits (`sampler.rs`, - /// `compute.rs`, `sampler_listing.rs`). Or, as a command buffer commits, more states live - /// than a command's plan's sampler tables hold, or one of a shape its checks refuse - /// (`sampler_listing.rs`). A command buffer whose command lists the argument samplers then - /// fails (`CommandBufferError::UnlistedArgumentSampler`), whether or not its functions - /// reach the state; each is counted (`WorkCounts::unlisted_argument_sampler_failures`). + /// samplers or its command buffer lists them again as it commits or as the command's batch + /// is submitted (`sampler.rs`, `compute.rs`, `sampler_listing.rs`). Or, as a command + /// buffer commits or the batch is submitted, more states live than a command's plan's + /// sampler tables hold, or one of a shape its checks refuse (`sampler_listing.rs`): at the + /// submission, announced on the device's scheduler thread, outside any program call. The + /// command runs with the states it lists: those that fit its sampler arrays, where its + /// tables hold them, else those it listed before. Each command buffer that left a state + /// out is counted once, whether or not its functions reach the state + /// (`WorkCounts::unlisted_argument_sampler_buffers`). Where it happens: a command misses a + /// state where more states live than its sampler arrays hold (at most the device's + /// update-after-bind sampler limit), or than its plan's tables hold, twice the capacity + /// class of the states live as it was encoded, so where the live states more than doubled + /// between its encoding and its batch's submission. UnlistedArgumentSampler = "unlisted-argument-sampler", Precision, - "a command buffer whose commands list the argument samplers while the state lives \ - fails (UnlistedArgumentSampler), where Metal's function reads the state through \ - its ID"; + "a function reading the state through its ID in an argument buffer reads the \ + neutral sampler, where Metal's reads the state"; /// A `Depth32Float` texture the program only reads or samples, on a device whose driver /// is not measured to keep every `float` in a depth image (`device/driver_facts.rs`: a /// denormal, and without `VK_EXT_depth_range_unrestricted` a value outside `[0, 1]`), is @@ -985,13 +982,23 @@ degradations! { "the record reads its word as zero, where Metal reads what lies at that address in its \ own address space: zero where nothing is there, another buffer's bytes where Metal \ placed one"; - /// A resource made with `MTLResourceOptions` bit 24, a private option Metal takes - /// ([`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT)), is - /// made as without it, and reports its options without it, as Metal's does. + /// A heap of the runtime's memory or an indirect command buffer made with + /// `MTLResourceOptions` bit 24 + /// ([`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT)), or off macOS a + /// no-copy buffer or heap over the caller's bytes, which Metal makes and keeps the GPU's + /// writes from the memory of (the M3 Max under macOS 27.0.1: a kernel's stores and a + /// blit's fill reach neither the CPU nor a later command buffer, which read the memory's + /// bytes; a later command of the same command buffer may read them, as the GPU's caches + /// hold them; a blit into a texture over or in that memory faults the command buffer), is + /// made as without it, and reports its options without it, as Metal's does. On macOS a + /// no-copy buffer or heap with the bit drops the GPU's writes as Metal's does, its pages + /// imported through a read-only view of them (`read_only_view.rs`), announcing nothing. + /// A buffer of the runtime's memory or a texture descriptor with the bit is refused, as + /// Metal ends the process there; a buffer placed in a heap without the bit is made as + /// without it, as Metal's is, announcing nothing. PrivateResourceOption = "private-resource-option", Precision, - "the private option has no effect here: on Metal a no-copy buffer made with it kept \ - the GPU's writes from the CPU (Metal probe nc_bit24 on an M4), where the runtime's \ - reach it"; + "the GPU's writes reach the resource's memory, the CPU and later command buffers, \ + where Metal's never reach them"; /// A depth or stencil texture with `allowGPUOptimizedContents` off sized or made in a heap /// (never a device's own texture, whose layout nothing shows), on a device whose driver /// keeps depth and stencil images GPU-optimized whatever their create info @@ -2317,6 +2324,16 @@ impl Degradation { "none: a texture over a no-copy buffer's host pages is a shadow, which takes no first \ move over them", ), + ( + // A sampler state made while a committed command buffer that listed the argument + // samplers had not completed announced it. Each batch's submission lists the states + // live then, so a state made before the wait that orders its ID's write is the one + // its function reads, as Metal's. + "metal2vulkan-degrade-resource-id-takeover", + "none: a command reads the sampler states live as its batch is submitted, so a state \ + made before the event wait that orders its ID's write is the one its function reads, \ + as on Metal", + ), ]; /// The kind of `code`, if any. @@ -2761,6 +2778,20 @@ pub(crate) fn announcement_breach(each: bool) -> Option { } } +/// `Invalid` (`Problem::UndefinedValue`) where `options` set [`ResourceOptions::PRIVATE_BIT`]. +fn refuse_private_bit(call: &'static str, options: ResourceOptions) -> Result<(), Error> { + match options.without_private_bit().1 { + true => Err(crate::error::invalid( + call, + crate::error::Problem::UndefinedValue { + ty: "MTLResourceOptions", + raw: options.raw(), + }, + )), + false => Ok(()), + } +} + /// Whether a misplaced announcement ends the process: in builds with debug assertions, which /// every lane and gate runs. pub(crate) const MISPLACED_ENDS: bool = cfg!(debug_assertions); @@ -3091,9 +3122,27 @@ impl Device { } } - /// `options` as the runtime makes `call`'s resource of them: without - /// [`ResourceOptions::PRIVATE_BIT`], which has no effect here, announced once - /// ([`Degradation::PrivateResourceOption`]). + /// `options` of `call`'s no-copy buffer or heap over the caller's bytes without + /// [`ResourceOptions::PRIVATE_BIT`], and whether its memory drops the GPU's writes, as Metal's + /// does where the options set the bit: on macOS, where the runtime imports the pages through + /// a read-only view of them (`read_only_view.rs`). Elsewhere the GPU's writes reach the + /// pages, announced once ([`Degradation::PrivateResourceOption`]). + pub(super) fn no_copy_options( + &self, + call: &'static str, + options: ResourceOptions, + ) -> (ResourceOptions, bool) { + if !crate::read_only_view::VIEWS_DROP_WRITES { + return (self.take_options(call, options), false); + } + options.without_private_bit() + } + + /// `options` as the runtime makes `call`'s resource of them where Metal makes it with + /// [`ResourceOptions::PRIVATE_BIT`] and keeps the GPU's writes from its memory (a heap of + /// the runtime's memory; a no-copy buffer or heap off macOS, [`Device::no_copy_options`]; an + /// indirect command buffer, whose GPU-written records under it are not measured): without the + /// bit, announced once ([`Degradation::PrivateResourceOption`]). pub(super) fn take_options( &self, call: &'static str, @@ -3113,16 +3162,33 @@ impl Device { taken } - /// `descriptor` with its options as [`take_options`](Self::take_options) takes them. - pub(super) fn take_texture_options( + /// `options` of `call`'s resource whose memory the runtime gives it (a buffer of a length or + /// of bytes, a Vulkan buffer of the caller's): refused where they set + /// [`ResourceOptions::PRIVATE_BIT`] (`Invalid`, `Problem::UndefinedValue`), as Metal ends the + /// process there (the M3 Max under macOS 27.0.1: `newBufferWithLength:options:` and + /// `newBufferWithBytes:length:options:`, `Shared` or `Private`, assert in the buffer's + /// suballocator, "Different MTLResourceOptions used for the same heap index"). + pub(super) fn own_memory_options( + &self, + call: &'static str, + options: ResourceOptions, + ) -> Result { + refuse_private_bit(call, options)?; + Ok(options) + } + + /// `descriptor`, refused where its options set [`ResourceOptions::PRIVATE_BIT`] (`Invalid`, + /// `Problem::UndefinedValue`), as Metal's texture descriptor validation ends the process there + /// for every texture (the M3 Max under macOS 27.0.1: "MTLResourceOptions (0x1000000) contains + /// unknown bits", a device's texture, `Shared` or `Private`, a heap's, a buffer's and a + /// shareable one alike). + pub(super) fn texture_options( &self, call: &'static str, descriptor: &TextureDescriptor, - ) -> TextureDescriptor { - TextureDescriptor { - resource_options: self.take_options(call, descriptor.resource_options), - ..*descriptor - } + ) -> Result { + refuse_private_bit(call, descriptor.resource_options)?; + Ok(*descriptor) } /// Announce what `stages` (a variant's) record, `at` its making or a bind diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 544a77a4c..52f1636d5 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -91,7 +91,7 @@ use metal2vulkan::error::RuntimeDriverDefect; use metal2vulkan::vk::DriverId; use relay::Flights; use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak}; use std::time::Instant; use submit::{Internal, OwnTimeline}; @@ -242,9 +242,6 @@ pub(super) struct DeviceShared { /// The immutable sampler sets of the variants' layouts, by their samplers /// (`pipeline/objects.rs`, `pipeline/content_keyed.rs`). pub(crate) sampler_sets: Mutex, - /// The command buffers, not yet completed, whose dispatches list the argument samplers - /// (`heap_sets.rs`): a sampler state made under a new ID then is a degradation. - pub(super) sampler_tables: Arc, /// The heap sets and the texture table every command buffer shares (`heap_sets.rs`). Its /// lock is taken before `resource_ids`', never under it. pub(super) heaps: Mutex, @@ -1641,7 +1638,6 @@ impl Device { samplers: Mutex::default(), sampler_count: SamplerCount::new(limits.max_sampler_allocation_count), sampler_sets: Mutex::default(), - sampler_tables: Arc::default(), heaps: Mutex::default(), heap_nan_residue: NanResidue::default(), function_tables: Mutex::default(), diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs index 690e984ae..e0ee53125 100644 --- a/crates/metal2vulkan-runtime/src/device/prime.rs +++ b/crates/metal2vulkan-runtime/src/device/prime.rs @@ -1097,6 +1097,9 @@ impl Primer<'_> { .map_err(vulkan)?; self.made(Call::CreateDescriptorSetLayout); self.hold(set_layout); + let mut support = vk::DescriptorSetLayoutSupport::default(); + device.get_descriptor_set_layout_support(&info, &mut support); + self.made(Call::GetDescriptorSetLayoutSupport); let set_layouts = [set_layout]; let push = [vk::PushConstantRange { stage_flags: vk::ShaderStageFlags::COMPUTE, diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index fc3f429bb..4d278ced2 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1616,22 +1616,6 @@ pub enum CommandBufferError { /// the command buffer fails (`NotImplemented(SamplerBicubicFilter)`'s reach, decided where the /// function ran). A command buffer whose functions never reach such a sampler runs as Metal's. CubicArgumentSampler, - /// As the command buffer committed, a command's plan could not list the sampler states live - /// then, which Metal's function reaches by their resource IDs as it runs: a state past the - /// command's set-1 sampler arrays (more states live than they hold), more states than its - /// sampler tables hold (twice the class of the states live as it was encoded), or a state of a - /// shape the plan's checks refuse (such as a cubic state beside a fragment stage). The command - /// ran with the states it could list, so a function reading a state left out would have read - /// the neutral sampler, and the command buffer fails. So does one a command of which a host - /// step recorded after the commit (an indirect command buffer whose records the GPU writes) - /// left a live state out, more states living then than the command's set-1 sampler arrays hold: - /// no commit lists such a command again. - /// - /// The refusal is over-approximate: it fails the command buffer whether or not any function - /// reached the state left out, so it can fail a command buffer that Metal completes. Each is - /// counted (`WorkCounts::unlisted_argument_sampler_failures`), and the device announces the - /// first (`Degradation::UnlistedArgumentSampler`). - UnlistedArgumentSampler, /// An emulated mesh draw's records did not fit the rest of the command buffer's mesh records /// pool, or its vertices passed a `u32`: such draws drew nothing. Metal draws them; the /// runtime's pool is the device's budget, so nothing is drawn short silently. The first such @@ -2007,7 +1991,6 @@ impl CommandBufferError { | CommandBufferError::Refused | CommandBufferError::RenderTargetSize | CommandBufferError::CubicArgumentSampler - | CommandBufferError::UnlistedArgumentSampler | CommandBufferError::HostStepObject(_) | CommandBufferError::EncodedUseRebound | CommandBufferError::PredicatedLoopPastCopies @@ -2050,7 +2033,6 @@ impl CommandBufferError { | CommandBufferError::SparseMappingArguments(_) | CommandBufferError::SparseMappingSplit | CommandBufferError::CubicArgumentSampler - | CommandBufferError::UnlistedArgumentSampler | CommandBufferError::MeshRecordsOverflow(_) | CommandBufferError::TessellationRecordsOverflow(_) | CommandBufferError::Refused diff --git a/crates/metal2vulkan-runtime/src/exactness.rs b/crates/metal2vulkan-runtime/src/exactness.rs index d32bdf81b..5445ae07f 100644 --- a/crates/metal2vulkan-runtime/src/exactness.rs +++ b/crates/metal2vulkan-runtime/src/exactness.rs @@ -81,7 +81,6 @@ impl Degradation { // Points Metal sizes none of: what it draws is undefined, mostly nothing, and the // runtime draws nothing. | D::UnsizedPoints => Exactness::OneOfMetals, - D::UnlistedArgumentSampler => Exactness::FailsInstead(E::UnlistedArgumentSampler), D::EncodedUseRebound => Exactness::FailsInstead(E::EncodedUseRebound), _ => Exactness::NearEquivalent, }, diff --git a/crates/metal2vulkan-runtime/src/heap.rs b/crates/metal2vulkan-runtime/src/heap.rs index 185ccc5b1..9050f2899 100644 --- a/crates/metal2vulkan-runtime/src/heap.rs +++ b/crates/metal2vulkan-runtime/src/heap.rs @@ -526,7 +526,9 @@ impl Device { /// image over a dma-buf of its own pages), else an image of its own whose texels the encoders copy from /// the heap's bytes and back, laid out by level and layer from the texture's offset, which the /// device announces once (`shadowed-texture`; `texture/heap.rs`). Its purgeable state answers - /// as a no-copy buffer's: non-volatile, and emptying it keeps the caller's bytes. + /// as a no-copy buffer's: non-volatile, and emptying it keeps the caller's bytes. With Metal's + /// private option bit 24 the GPU's writes to the memory are dropped as a no-copy buffer's are + /// ([`Device::new_buffer_with_bytes_no_copy`]). /// /// Refused: a size of 0 (`Nil`, as [`Device::new_heap`] answers it); storage other than /// `Shared`, a sparse heap, an undefined option (`Invalid`); memory whose first byte is not a multiple of the import's unit @@ -587,7 +589,7 @@ impl Device { token: Option, ) -> Result { const CALL: &str = "new_heap_with_bytes_no_copy"; - let options = self.take_options(CALL, descriptor.resource_options); + let (options, drops_writes) = self.no_copy_options(CALL, descriptor.resource_options); let modes = Modes::of(options)?; if modes.storage != StorageMode::Shared || descriptor.heap_type == HeapType::Sparse { return Err(invalid(CALL, Problem::StorageMode)); @@ -606,6 +608,7 @@ impl Device { release, descriptor.placement.into(), true, + drops_writes, ) }?; if let Some(token) = token { @@ -940,7 +943,9 @@ impl Heap { /// (`OutOfMemory(Heap)`). pub fn new_buffer(&self, length: u64, options: ResourceOptions) -> Result { const CALL: &str = "new_buffer"; - let options = self.device().take_options(CALL, options); + // Metal makes a placed buffer with the private bit as without it (the heap's own options + // decide where its writes go). + let options = options.without_private_bit().0; let options = self.placed_options(CALL, options)?; let bytes = self.check_type(CALL, HeapType::Automatic)?; if length == 0 { @@ -976,7 +981,8 @@ impl Heap { offset: u64, ) -> Result { const CALL: &str = "new_buffer_at_offset"; - let options = self.device().take_options(CALL, options); + // As `new_buffer`: the private bit is the heap's to take. + let options = options.without_private_bit().0; let options = self.placed_options(CALL, options)?; let bytes = self.check_type(CALL, HeapType::Placement)?; self.check_length(CALL, length)?; diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index 4b82b25d4..e647343b9 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -65,8 +65,8 @@ //! placement's or a rebind's writes go only to versions not committed). //! - **Samplers.** A sampler state is at its element of the sampler arrays (`resource_ids.rs`), //! which its command's sampler table maps its ID to: the device's live states as the command was -//! encoded. Until it completes, a command buffer whose commands list them is counted in the -//! device's `sampler_tables` (`sampler.rs` announces a state made meanwhile). +//! encoded, listed again as its command buffer commits and as the command's batch is submitted +//! (`sampler_listing.rs`). //! - **Release.** A heap set goes with the last variant of its layout and the last command buffer //! that bound it; the table with the device. @@ -602,9 +602,9 @@ impl DeviceHeaps { } } -/// Whether `device`'s heap arrays can be written while a command buffer binding them is pending -/// (the module docs). -fn unused_while_pending(device: &Device) -> bool { +/// Whether the device's heap sets take writes while command buffers that bind them are pending: +/// one version of each set, `UPDATE_UNUSED_WHILE_PENDING` (the module docs). +pub(super) fn unused_while_pending(device: &Device) -> bool { metal2vulkan::pipeline::heap_unused_while_pending(device.compile_device().profile()) } @@ -1263,16 +1263,11 @@ pub(super) fn retire(device: &Device, kept: Keeper) { drop(freed); } -/// A command buffer's heap: the versions its commands bound and its sampler listing (the module -/// docs), until it completes. +/// A command buffer's heap: the versions its commands bound (the module docs), until it +/// completes. #[derive(Default)] pub(super) struct HeapUse { versions: Vec>, - listed: Option, - /// Some command lists the argument samplers. - lists_samplers: bool, - /// The command buffer committed. - committed: bool, /// Its first submission takes a ticket: its commands, or its host steps', may read the heap. wants_ticket: bool, /// Its ticket was taken. @@ -1289,18 +1284,11 @@ impl HeapUse { /// argument samplers again (`sampler_listing.rs`), where its commands or its host steps may /// read the heap: its ticket for what a rebind or a detach replaces, which it holds until it /// completes; its first submission takes its ticket for gone textures ([`submit`]). Nothing - /// writes its own versions from now on but a gone texture's neutrals (the module docs). A - /// command buffer that lists the argument samplers is counted in the device's - /// `sampler_tables` until it completes: a state made meanwhile is not among them - /// (`sampler.rs`). + /// writes its own versions from now on but a gone texture's neutrals (the module docs). /// /// [`submit`]: HeapUse::submit pub(super) fn commit(&mut self, device: &Device) -> Ticket { - self.committed = true; self.wants_ticket = true; - if self.lists_samplers && self.listed.is_none() { - self.listed = Some(Listed::new(&device.shared().sampler_tables)); - } let mut heaps = lock(&device.shared().heaps); for version in &self.versions { version.committed.store(true, Ordering::Release); @@ -1339,13 +1327,10 @@ impl HeapUse { }) } - /// The command buffer completed: its listing goes, and the versions its commands bound come - /// out, for the caller to let go of once its completed handlers ran (each version's last - /// hold releases its descriptor pool). + /// The command buffer completed: the versions its commands bound come out, for the caller to + /// let go of once its completed handlers ran (each version's last hold releases its + /// descriptor pool). pub(super) fn clear(&mut self) -> Vec> { - self.listed = None; - self.lists_samplers = false; - self.committed = false; self.wants_ticket = false; self.ticketed = false; std::mem::take(&mut self.versions) @@ -1466,15 +1451,6 @@ pub(super) fn bind( return Err(internal("a heap write to another set")); } let set = objects.heap_set()?; - // A command buffer whose commands list the argument samplers lists them again as it commits - // (`sampler_listing.rs`), and is counted from then on; a command a host step records after - // the commit lists the states as they stand then, counted at once. - if writes.iter().any(|w| w.ty == vk::DescriptorType::SAMPLER) { - heap.lists_samplers = true; - if heap.committed && heap.listed.is_none() { - heap.listed = Some(Listed::new(&device.shared().sampler_tables)); - } - } let mut notes = Notes::default(); let version = { let mut heaps = lock(&device.shared().heaps); @@ -1623,35 +1599,23 @@ pub(super) fn fit_samplers( /// Announce that `commands` (the commands of a function, named) leave the sampler state at /// resource ID `id` out of their argument samplers, their variant's set-1 sampler arrays holding -/// `capacity` elements ([`fit_samplers`]): their command buffer fails as it completes, where the -/// state still lives as it commits (`sampler_listing.rs`), or where a host step recorded them after -/// the commit. -pub(super) fn degrade_unlisted(device: &Device, (id, capacity): (u64, u64), commands: &str) { +/// `capacity` elements ([`fit_samplers`]): a function of theirs reading it reads the neutral +/// sampler, where the state still lives as their command buffer commits (`sampler_listing.rs`), +/// or where a host step recorded them after the commit. +pub(super) fn degrade_unlisted(device: &Device, unlisted: (u64, u64), commands: &str) { device.degrade(Degradation::UnlistedArgumentSampler, || { - ( - format!("sampler state at resource ID {id}"), - format!( - "{commands}' set-1 sampler arrays hold {capacity} elements, fewer than the live \ - sampler states, so they leave the state out of their argument samplers and \ - their command buffer fails (CommandBufferError::UnlistedArgumentSampler)" - ), - ) + unlisted_notice(unlisted, commands) }); } -/// A command buffer whose commands list the argument samplers, counted in its device's -/// `sampler_tables` until it goes. -struct Listed(Arc); - -impl Listed { - fn new(count: &Arc) -> Listed { - count.fetch_add(1, Ordering::AcqRel); - Listed(Arc::clone(count)) - } -} - -impl Drop for Listed { - fn drop(&mut self) { - self.0.fetch_sub(1, Ordering::AcqRel); - } +/// The object and the reason of [`degrade_unlisted`]'s notice. +pub(super) fn unlisted_notice((id, capacity): (u64, u64), commands: &str) -> (String, String) { + ( + format!("sampler state at resource ID {id}"), + format!( + "{commands}' set-1 sampler arrays hold {capacity} elements, fewer than the live \ + sampler states, so they leave the state out of their argument samplers, and a \ + function of theirs reading it reads the neutral sampler" + ), + ) } diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 5123f5481..18fda8ca5 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -162,6 +162,7 @@ mod queue; mod range; mod rate_map; mod rate_mapped_pass; +mod read_only_view; mod reader_sizes; mod rebind; mod recorder; diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 23139f857..98486d1d3 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -18,7 +18,8 @@ //! has its own entry, [`Memory::import_host`]: one dedicated block per import, never //! pooled, freed through the same [`Memory::free`]. So has a buffer's fresh pages //! ([`import_own_pages`], `fresh_pages.rs`): a dedicated block that unmaps them once its -//! memory is freed. A dma-buf's import +//! memory is freed, as an import through a read-only view of the caller's pages unmaps the view +//! (`read_only_view.rs`). A dma-buf's import //! (`Memory::import_dma_buf`) is in no block: the placement in it keeps it, and frees it as it //! goes (`dma_buf.rs`'s `DmaBufPages`). //! @@ -52,6 +53,7 @@ use super::freed_memory::{Parked, Parking}; use super::fresh_pages::OwnPages; use super::memory_log::{self, MemoryLog}; use super::range::RangeAllocator; +use super::read_only_view::ReadOnlyView; use super::sharing::Sharing; use super::work_counts::Counters; use crate::release; @@ -552,10 +554,18 @@ pub(super) struct Block { /// The pages its memory was imported from, where the runtime mapped them for it /// ([`import_own_pages`]): unmapped once the memory is freed. pages: Option, + /// The read-only view of the caller's pages its memory was imported from, which drops the + /// GPU's writes ([`Memory::import_host`], `read_only_view.rs`): unmapped once the memory is + /// freed. + view: Option, /// Its memory type. type_index: u32, } +/// What the runtime mapped that a block's memory was imported from (`Block::pages`, +/// `Block::view`), unmapped once the memory is freed. +type MappedPages = (Option, Option); + /// A buffer over the first `Block::size` bytes of a block, with every usage of an addressed /// buffer (`buffer::usage`), whose device address gives each buffer placed in the block its own /// (the module docs). @@ -580,8 +590,8 @@ impl Block { drop(pages); } - /// Destroy the block's buffer of addresses: its memory, to free, and the pages it was - /// imported from where the runtime mapped them, to unmap once it is freed. + /// Destroy the block's buffer of addresses: its memory, to free, and the pages or the view + /// it was imported from where the runtime mapped them, to unmap once it is freed. /// /// # Safety /// @@ -589,18 +599,23 @@ impl Block { unsafe fn release_addresses( self, device: &ash::Device, - ) -> (vk::DeviceMemory, Option) { + ) -> (vk::DeviceMemory, Option) { let Block { memory, addresses, pages, + view, .. } = self; if let Some(addresses) = addresses { // SAFETY: the caller's contract. unsafe { release::object(device, addresses.raw) }; } - (memory, pages) + let mapped_pages = match (pages, view) { + (None, None) => None, + mapped_pages => Some(mapped_pages), + }; + (memory, mapped_pages) } } @@ -668,6 +683,8 @@ pub(super) struct Placement { pub(super) address: Option, /// It lies in pages the runtime mapped and imported ([`import_own_pages`]). own_pages: bool, + /// It lies in an import of a read-only view of the caller's pages (`read_only_view.rs`). + read_only_view: bool, /// The imports of the caller's dma-bufs the placement lies in, with the source that made them /// (`dma_buf.rs`), which no block of the runtime's holds: kept until the placement goes, and /// freed, the source dropped, when their last holder goes. @@ -696,6 +713,7 @@ impl Placement { mapped: mapped.map(Mapped), address: None, own_pages: false, + read_only_view: false, #[cfg(unix)] dma_buf: None, } @@ -725,6 +743,7 @@ impl Placement { mapped: Some(Mapped(mapped)), address: None, own_pages: false, + read_only_view: false, dma_buf: Some(pages), } } @@ -758,6 +777,12 @@ impl Placement { self.own_pages } + /// Whether the placement lies in an import of a read-only view of the caller's pages, which + /// drops the GPU's writes to them (`read_only_view.rs`). + pub(super) fn over_read_only_view(&self) -> bool { + self.read_only_view + } + /// The imports of the caller's dma-bufs the placement lies in, with their source /// (`dma_buf.rs`); `None` for any other placement. #[cfg(unix)] @@ -791,6 +816,7 @@ impl Placement { mapped: self.mapped, address: self.address, own_pages: self.own_pages, + read_only_view: self.read_only_view, #[cfg(unix)] dma_buf: self.dma_buf.clone(), } @@ -1133,6 +1159,7 @@ impl Memory { .filter(|_| addressed) .map(|addresses| addresses.address + offset), own_pages: payload.pages.is_some(), + read_only_view: payload.view.is_some(), #[cfg(unix)] dma_buf: None, } @@ -1291,26 +1318,29 @@ impl Memory { /// Import the caller's host memory, `size` bytes at `pointer` (both multiples of the device's /// import alignment), as a dedicated block of the best memory type of `class` among /// `allowed` (the types both the pointer and the resource take): its placement at offset 0, - /// whose `mapped` is `pointer`. The block is never pooled and is freed with the placement, - /// as a dedicated block is (`host_memory.rs`). Refused when no type of `class` is among - /// `allowed`, else with the failure of the last type tried. + /// whose `mapped` is `pointer`. Where `view` is given, a read-only view of those pages + /// (`read_only_view.rs`), the view is imported in their place, and unmapped once the memory + /// is freed. The block is never pooled and is freed with the placement, as a dedicated block + /// is (`host_memory.rs`). Refused when no type of `class` is among `allowed`, else with the + /// failure of the last type tried, the view unmapped. /// /// # Safety /// /// The `size` bytes at `pointer` are host memory of this process that stays mapped until the - /// placement is freed. + /// placement is freed; `view`, where given, views them whole. pub(super) unsafe fn import_host( &mut self, device: &ash::Device, - pointer: NonNull, + (pointer, view): (NonNull, Option), size: u64, allowed: u32, class: MemoryClass, ) -> Result { let types = candidates(&self.types, allowed, class, self.unified); - // SAFETY: the caller's contract. + let imported = view.as_ref().map_or(pointer, ReadOnlyView::pointer); + // SAFETY: the caller's contract; the view stays mapped while the block holds it. let (memory, type_index) = - unsafe { import_pointer(device, pointer, size, &types, self.device_address) }?; + unsafe { import_pointer(device, imported, size, &types, self.device_address) }?; let block = Block { memory, size, @@ -1318,6 +1348,7 @@ impl Memory { addresses: None, imported: true, pages: None, + view, type_index, }; let host = pointer.as_ptr() as usize; @@ -1555,6 +1586,7 @@ impl BlockMaker { addresses, imported: false, pages: None, + view: None, type_index, }) } @@ -1634,6 +1666,7 @@ pub(super) fn import_own_pages( addresses: None, imported: false, pages: Some(pages), + view: None, type_index, }; let mut memory = lock(memory); diff --git a/crates/metal2vulkan-runtime/src/read_only_view.rs b/crates/metal2vulkan-runtime/src/read_only_view.rs new file mode 100644 index 000000000..f417e6fff --- /dev/null +++ b/crates/metal2vulkan-runtime/src/read_only_view.rs @@ -0,0 +1,137 @@ +//! Read-only views of a caller's pages: on macOS, no-copy memory made with Metal's private option +//! bit 24 ([`ResourceOptions::PRIVATE_BIT`](crate::ResourceOptions::PRIVATE_BIT)) is imported +//! through one, so that the GPU's writes to it are dropped, as Metal drops them. +//! +//! - **What Metal does.** Measured on an M3 Max under macOS 27.0.1: a no-copy buffer, or a heap +//! over the caller's bytes, made with bit 24 takes the GPU's writes nowhere. A kernel's stores +//! and a blit's fill reach neither the CPU nor a later command buffer, which reads the CPU's +//! bytes; later commands of the same command buffer may read some back from the GPU's caches. +//! The pages' protection is unchanged, and the resource's options leave the bit out. +//! - **How.** A no-copy buffer made without the bit over a read-only view of the same pages +//! (`mach_vm_remap` sharing them, then `mprotect` read-only) behaved the same on every count +//! measured. On macOS the device's import of a host pointer is such a buffer (MoltenVK hands +//! the range to Metal), so the runtime imports the view in place of the caller's pointer +//! (`Device::buffer_over_host_memory`), while the CPU reads and writes the caller's own +//! (`Buffer::contents`). The view shares the pages, so the GPU reads what the CPU +//! writes at the pointer. +//! - **Cost.** Mapping and protecting a view of touched pages took at most 7 us, and unmapping +//! it at most 17 us, for 16 KiB to 1 GiB (best of 20, the M3 Max under macOS 27.0.1), beside +//! the import's 11 to 20 ms per GiB. +//! - **Freed.** The view is unmapped once the memory imported from it is freed (`memory.rs`'s +//! `Block`), as the import requires it mapped for its whole life. +//! - **Elsewhere** the import is of the caller's pages: Linux drivers pin imported pages for +//! writing and refuse or fault on read-only ones (`host_memory.rs`), so there the GPU's writes +//! reach the pages, and the difference is announced +//! ([`Degradation::PrivateResourceOption`](crate::Degradation::PrivateResourceOption)). + +use std::ptr::NonNull; + +/// Whether this system imports no-copy memory of bit 24 through a read-only view of its pages +/// (the module docs). +pub(super) const VIEWS_DROP_WRITES: bool = cfg!(target_os = "macos"); + +/// A read-only view of `length` bytes of the caller's pages, mapped by the runtime and unmapped +/// as this goes: after the memory imported from it is freed (`memory.rs`'s `Block`). +#[derive(Debug)] +pub(crate) struct ReadOnlyView { + pointer: NonNull, + length: u64, +} + +// SAFETY: the view is the runtime's alone, and nothing writes through it; unmapping it is this +// value's alone. +unsafe impl Send for ReadOnlyView {} +// SAFETY: as above; a shared view answers its pointer alone. +unsafe impl Sync for ReadOnlyView {} + +impl ReadOnlyView { + /// A read-only view of the `length` bytes of pages at `pointer`, sharing them: `None` where + /// the system maps none. + /// + /// # Safety + /// + /// `pointer` and `length` are multiples of the host page, and the bytes are mapped memory of + /// this process. + #[cfg(target_os = "macos")] + pub(super) unsafe fn of(pointer: NonNull, length: u64) -> Option { + unsafe extern "C" { + /// ``: the port of this process's task. + static mach_task_self_: libc::mach_port_t; + fn mach_vm_remap( + target_task: libc::vm_map_t, + target_address: *mut libc::mach_vm_address_t, + size: libc::mach_vm_size_t, + mask: libc::mach_vm_address_t, + flags: libc::c_int, + src_task: libc::vm_map_t, + src_address: libc::mach_vm_address_t, + copy: libc::boolean_t, + cur_protection: *mut libc::vm_prot_t, + max_protection: *mut libc::vm_prot_t, + inheritance: libc::vm_inherit_t, + ) -> libc::kern_return_t; + } + // ``: the kernel picks the address. + const VM_FLAGS_ANYWHERE: libc::c_int = 0x0001; + // ``: a child process shares the view, as measured (the module docs). + const VM_INHERIT_SHARE: libc::vm_inherit_t = 0; + let bytes = usize::try_from(length).ok()?; + let mut view: libc::mach_vm_address_t = 0; + let (mut current, mut maximum) = (0, 0); + // SAFETY: a new mapping, at an address the kernel picks, of the caller's mapped pages + // (the caller's contract), shared rather than copied, so it reads what they hold. + let remapped = unsafe { + let task = mach_task_self_; + mach_vm_remap( + task, + &mut view, + length, + 0, + VM_FLAGS_ANYWHERE, + task, + pointer.as_ptr() as libc::mach_vm_address_t, + 0, + &mut current, + &mut maximum, + VM_INHERIT_SHARE, + ) + }; + if remapped != libc::KERN_SUCCESS { + return None; + } + let view = ReadOnlyView { + pointer: NonNull::new(view as *mut u8)?, + length, + }; + // SAFETY: the mapping is the view's own, just made. + let protected = + unsafe { libc::mprotect(view.pointer.as_ptr().cast(), bytes, libc::PROT_READ) }; + (protected == 0).then_some(view) + } + + /// No view is mapped on this system ([`VIEWS_DROP_WRITES`]). + /// + /// # Safety + /// + /// None: it maps nothing. + #[cfg(not(target_os = "macos"))] + pub(super) unsafe fn of(_pointer: NonNull, _length: u64) -> Option { + None + } + + /// Where the view starts. + pub(super) fn pointer(&self) -> NonNull { + self.pointer + } +} + +impl Drop for ReadOnlyView { + fn drop(&mut self) { + #[cfg(unix)] + // SAFETY: the mapping is this value's, and nothing reads it any more: the memory + // imported from it was freed first (`memory.rs`'s `Block`). + unsafe { + libc::munmap(self.pointer.as_ptr().cast(), self.length as usize); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index e1c8ca711..b225d5965 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -9231,7 +9231,7 @@ impl RenderLowering { .retain_samplers(&mut self.core, &mut samplers); if let Some(unlisted) = unlisted { heap_sets::degrade_unlisted(&device, unlisted, "a render pipeline state's draws"); - // A host step's draw, which no commit lists again, fails its command buffer. + // A host step's draw, which no commit lists again, runs with the states it listed. let mut held = self.core.command_buffer().state(); held.unlisted_argument_sampler(&device); } diff --git a/crates/metal2vulkan-runtime/src/resource_ids.rs b/crates/metal2vulkan-runtime/src/resource_ids.rs index 59effb27b..834eddba4 100644 --- a/crates/metal2vulkan-runtime/src/resource_ids.rs +++ b/crates/metal2vulkan-runtime/src/resource_ids.rs @@ -136,7 +136,7 @@ //! (`ElementHold`), which the sampler table maps its ID to, so a state at any ID is listed; only //! where more states live than an array holds is one left out, //! [`Degradation::UnlistedArgumentSampler`](super::Degradation::UnlistedArgumentSampler), and a -//! command buffer whose commands list the argument samplers then fails. +//! function reading it through an argument buffer then reads the neutral sampler. //! - **Slots.** Each ID has one slot, held by the resource last made with it, placed or plain: //! that is what a function reading the ID reaches, and every resource with the ID still //! answers it as its own. Once the holder is gone the slot reads the neutral resource, even diff --git a/crates/metal2vulkan-runtime/src/sampler.rs b/crates/metal2vulkan-runtime/src/sampler.rs index 59469677c..7c548163c 100644 --- a/crates/metal2vulkan-runtime/src/sampler.rs +++ b/crates/metal2vulkan-runtime/src/sampler.rs @@ -483,22 +483,12 @@ impl Device { format!( "more sampler states live than a set-1 sampler array of the device \ holds ({limit:?} is {available}), so none holds its element {element}, \ - and a command buffer whose commands list the argument samplers while it \ - lives fails (CommandBufferError::UnlistedArgumentSampler)" + and a function reading it through an argument buffer while it lives \ + reads the neutral sampler" ), ) }); } - if shared.sampler_tables.load(Ordering::Acquire) > 0 { - self.degrade(Degradation::ResourceIdTakeover, || { - ( - format!("sampler state made at resource ID {id}"), - "a committed command buffer that has not completed lists the argument \ - samplers as it committed, which this state is not among" - .to_owned(), - ) - }); - } Ok(state) } diff --git a/crates/metal2vulkan-runtime/src/sampler_listing.rs b/crates/metal2vulkan-runtime/src/sampler_listing.rs index 1ab1ad2ea..f2ad1f090 100644 --- a/crates/metal2vulkan-runtime/src/sampler_listing.rs +++ b/crates/metal2vulkan-runtime/src/sampler_listing.rs @@ -1,40 +1,51 @@ -//! A command's argument samplers, listed again as its command buffer commits. +//! A command's argument samplers, listed again as its command buffer commits and as the batch +//! holding the command is submitted. //! //! Metal's function reaches a sampler state by its resource ID as the command runs, as it does a //! texture (`resource_ids.rs`). A command reaches the states its sampler table lists //! (`BindState::argument_samplers`): the device's live states as it was encoded. So a state made //! after that, or one that took a listed state's ID, would be missed. Each command that writes a -//! sampler table keeps it here, and the command buffer lists the states live as it commits, before -//! it is submitted: +//! sampler table keeps it here, with its encoder's place, and the command buffer lists the states +//! live as it commits, and again as the batch holding the encoder is submitted where a state was +//! made or went since (the count of the sampler IDs' slots' changes moved, +//! `Device::sampler_slots_changed`): //! //! - **Where they fit the plan** (as many as the planned entries hold beside the null entry, twice //! the class's, each of a shape the plan was made for or one its checks admit, //! `BindingPlan::relisted_sampler_tables`), their table is written over the command's region of //! the arena, and their elements into the heap set the command binds -//! (`binding::argument_sampler_writes`, `heap_sets::bind`): the set's version a pending command -//! buffer does not use, or the command buffer's own, still written until it commits -//! (`heap_sets.rs`). +//! (`binding::argument_sampler_writes`, `heap_sets::bind`): the set's one version, whose new +//! elements no pending command buffer reads, or the command buffer's own, still written until it +//! commits (`heap_sets.rs`). Before the batch's `vkQueueSubmit`, so the host's writes are visible +//! to it (the host write ordering guarantee). //! - **Where they do not** (a state past the command's set-1 sampler arrays, //! `heap_sets::fit_samplers`; more states than its tables hold; or a shape its checks refuse, //! such as a cubic state beside a fragment stage), the command cannot reach every state as -//! Metal's function would, so its command buffer fails as it completes -//! (`CommandBufferError::UnlistedArgumentSampler`), announced once as `unlisted-argument-sampler` -//! and counted (`WorkCounts::unlisted_argument_sampler_failures`). The refusal is -//! over-approximate: it holds whether or not the function reaches the state left out. +//! Metal's function would: it runs with the states that fit the arrays where its tables hold +//! them, else with those it listed before, and a function reading a state left out reads the +//! neutral sampler. Announced as `unlisted-argument-sampler` and counted once per command buffer +//! (`WorkCounts::unlisted_argument_sampler_buffers`), whether or not a function reaches the +//! state left out. //! -//! A state made after the commit, while the command buffer has not completed, is not listed: the -//! device announces it as it is made (`sampler.rs`), Metal's answer then hanging on whether its -//! command ran before the state was made. +//! **Why the submission.** A batch is submitted only once every event it waits for is reached +//! (`scheduler.rs`), and an event wait starts a batch of its own (`batches.rs`). So a state made +//! after the commit and before a wait it is ordered by (the program writes its ID into an argument +//! buffer, then signals the event the command buffer waits for, or commits the command buffer that +//! signals it) is made before that batch is submitted, and its command reads it, as Metal's does +//! (the M3 Max under macOS 27.0.1). A state made after the batch's submission can reach the +//! batch's function only through memory the program wrote after the submission with nothing +//! ordering that write before the function's read, a data race on Metal too, whose answer hangs on +//! when the GPU read the memory. On a device without `descriptorBindingUpdateUnusedWhilePending`, +//! whose command buffers bind their own versions of the heap set, written until they commit +//! (`Degradation::HeapSetCopied`), the commit's listing stands: a state made after the commit is +//! the neutral sampler there, as a texture made after it is. //! //! A command a host step records after the commit is listed again by no commit: it lists the states //! live as it is recorded, and where more live than its set-1 sampler arrays hold, so that it -//! leaves one out (`heap_sets::fit_samplers`), its command buffer fails as it completes -//! (`CommandBufferError::UnlistedArgumentSampler`, `State::unlisted_argument_sampler`), announced -//! and counted as above, where it completed with the function reading the neutral sampler for the -//! state left out. +//! leaves one out (`heap_sets::fit_samplers`), it runs with the others, announced and counted as +//! above (`State::unlisted_argument_sampler`). use super::binding; -use super::degradation::Degradation; use super::error::{internal, Error}; use super::heap_sets::{self, HeapUse}; use super::pipeline::VariantObjects; @@ -54,6 +65,11 @@ pub(super) struct SamplerListing { placement: HeapPlacement, /// The argument samplers the command listed. listed: Vec, + /// The count of the sampler IDs' slots' changes `listed` was taken at, once the commit listed + /// them (`Device::sampler_slots_changed`). + listed_at: Option, + /// The place of the command's encoder among its command buffer's ended encoders. + encoder: usize, /// Each sampler table's `(set, binding)` and region. tables: Vec<((u32, u32), Upload)>, /// The commands, named, for the notices. @@ -79,49 +95,75 @@ impl SamplerListing { heap: heap?.clone(), placement, listed: listed.to_vec(), + listed_at: None, + encoder: 0, tables, commands: commands(), }) } - /// List `live` again, the device's live states as the command buffer whose heap use is - /// `heaps` commits (the module docs): the Vulkan samplers the new elements name, which the - /// command buffer holds until it completes, or `None` where the command's plan cannot list - /// them (its command buffer then fails, `CommandBufferError::UnlistedArgumentSampler`). + /// The command's encoder takes place `encoder` among its command buffer's ended encoders. + pub(super) fn at_encoder(&mut self, encoder: usize) { + self.encoder = encoder; + } + + /// The place of the command's encoder among its command buffer's ended encoders. + pub(super) fn encoder(&self) -> usize { + self.encoder + } + + /// Whether the states listed may no longer be the live ones: the commit has not listed them, + /// or a state was made or went since (`changed`, the count of the sampler IDs' slots' changes + /// now). + pub(super) fn stale(&self, changed: u64) -> bool { + self.listed_at != Some(changed) + } + + /// List `live` again, the device's live states at the count `changed` of the sampler IDs' + /// slots' changes, as the command buffer whose heap use is `heaps` commits or as the batch + /// holding the command is submitted (the module docs): the Vulkan samplers the new elements + /// name, which the command buffer holds until it completes, and, where the command's plan + /// cannot list every one, the object and the reason of the `unlisted-argument-sampler` notice, + /// for the caller to announce. The command then lists those that fit its sampler arrays, where + /// its tables hold them, else keeps those it listed. pub(super) fn relist( - &self, + &mut self, device: &Device, - live: &[SamplerState], + (changed, live): (u64, &[SamplerState]), heaps: &mut HeapUse, - ) -> Result>>, Error> { + ) -> Result { + self.listed_at = Some(changed); let mut live = live.to_vec(); - let mut unlisted = None; - heap_sets::fit_samplers(Some(&self.heap), &mut live, &mut unlisted); - // A state past the command's sampler arrays, which no element of them holds. - if let Some(unlisted) = unlisted { - heap_sets::degrade_unlisted(device, unlisted, &self.commands); - return Ok(None); - } + let mut past = None; + // A state past the command's sampler arrays, which no element of them holds, is left out. + heap_sets::fit_samplers(Some(&self.heap), &mut live, &mut past); + let unlisted = past.map(|past| heap_sets::unlisted_notice(past, &self.commands)); let samplers = heap_sets::listed(&live); if samplers == self.listed { - return Ok(Some(Vec::new())); + return Ok(Relisted { + samplers: Vec::new(), + unlisted, + }); } let Some(bytes) = self .plan .relisted_sampler_tables(device.compile_device(), &samplers, self.placement) .map_err(Error::Bind)? else { - let commands = &self.commands; - device.degrade(Degradation::UnlistedArgumentSampler, || { + let unlisted = unlisted.unwrap_or_else(|| { ( - format!("{commands} listing the argument samplers"), - "the sampler states live as their command buffer commits are more than their \ - plan's sampler tables hold, or of a shape its checks refuse, so the command \ - buffer fails (CommandBufferError::UnlistedArgumentSampler)" + format!("{} listing the argument samplers", self.commands), + "the sampler states live as their command buffer commits, or as their batch \ + is submitted, are more than their plan's sampler tables hold, or of a shape \ + its checks refuse, so the commands keep the states they listed before, and \ + a function reading another reads the neutral sampler" .to_owned(), ) }); - return Ok(None); + return Ok(Relisted { + samplers: Vec::new(), + unlisted: Some(unlisted), + }); }; for (key, region) in &self.tables { let table = bytes @@ -130,10 +172,23 @@ impl SamplerListing { .ok_or_else(|| internal("a sampler table its plan does not list"))?; region.write(&table.bytes); } - let (writes, samplers) = binding::argument_sampler_writes(device, &self.plan, &live)?; + let (writes, owned) = binding::argument_sampler_writes(device, &self.plan, &live)?; if !writes.is_empty() { heap_sets::bind(device, &self.objects, heaps, writes, None)?; } - Ok(Some(samplers)) + self.listed = samplers; + Ok(Relisted { + samplers: owned, + unlisted, + }) } } + +/// What [`SamplerListing::relist`] made of the live states. +pub(super) struct Relisted { + /// The Vulkan samplers the new elements name, none where nothing changed. + pub(super) samplers: Vec>, + /// Where a live state is left out, the object and the reason of the + /// `unlisted-argument-sampler` notice. + pub(super) unlisted: Option<(String, String)>, +} diff --git a/crates/metal2vulkan-runtime/src/tests/command_buffer.rs b/crates/metal2vulkan-runtime/src/tests/command_buffer.rs index defdb7d80..85f2d8380 100644 --- a/crates/metal2vulkan-runtime/src/tests/command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/tests/command_buffer.rs @@ -271,7 +271,6 @@ fn a_command_buffer_error_names_whose_failure_it_is() { ), (E::SparseMappingSplit, Runtime, 1), (E::CubicArgumentSampler, Runtime, 1), - (E::UnlistedArgumentSampler, Runtime, 1), (E::MeshRecordsOverflow(overflow), Runtime, 8), (E::Refused, Runtime, 1), ( diff --git a/crates/metal2vulkan-runtime/src/tests/exactness.rs b/crates/metal2vulkan-runtime/src/tests/exactness.rs index 53947366a..e94a17883 100644 --- a/crates/metal2vulkan-runtime/src/tests/exactness.rs +++ b/crates/metal2vulkan-runtime/src/tests/exactness.rs @@ -79,16 +79,16 @@ fn the_kinds_metal_answers_otherwise_are_named() { _ => None, }) .collect(); - assert_eq!(fails.len(), 2, "{fails:?}"); - for pair in [ - ( - D::UnlistedArgumentSampler, - CommandBufferError::UnlistedArgumentSampler, - ), - (D::EncodedUseRebound, CommandBufferError::EncodedUseRebound), - ] { - assert!(fails.contains(&pair), "{pair:?}"); - } + assert_eq!( + fails, + [(D::EncodedUseRebound, CommandBufferError::EncodedUseRebound)] + ); + // A command that leaves a live sampler state out runs, a function reading it reading the + // neutral sampler. + assert_eq!( + D::UnlistedArgumentSampler.exactness(), + Exactness::NearEquivalent + ); for (kind, error) in fails { assert_eq!(error.origin(), FailureOrigin::Runtime, "{kind:?}"); } diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index e15dfd8f1..3f0822542 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -1577,7 +1577,7 @@ impl Device { pub fn new_texture(&self, descriptor: &TextureDescriptor) -> Result { const CALL: &str = "new_texture"; self.keep_room(); - let descriptor = &self.take_texture_options(CALL, descriptor); + let descriptor = &self.texture_options(CALL, descriptor)?; // An `Outside` texture takes no ID, so no ID's limit applies. if descriptor.placement != IdPlacement::Outside { self.check_texture_placement( @@ -3517,9 +3517,7 @@ impl Heap { /// Refused for a placement heap, whose textures take an offset (`Invalid`, as for its /// buffers). pub fn new_texture(&self, descriptor: &TextureDescriptor) -> Result { - let descriptor = &self - .device() - .take_texture_options("new_texture", descriptor); + let descriptor = &self.device().texture_options("new_texture", descriptor)?; match self.heap_type() { HeapType::Sparse => self.device().new_sparse_texture(self, descriptor), HeapType::Automatic => self.device().new_heap_texture(self, descriptor, None), @@ -3554,7 +3552,7 @@ impl Heap { offset: u64, ) -> Result { let device = self.device(); - let descriptor = &device.take_texture_options("new_texture_at_offset", descriptor); + let descriptor = &device.texture_options("new_texture_at_offset", descriptor)?; device.new_heap_texture(self, descriptor, Some(offset)) } } diff --git a/crates/metal2vulkan-runtime/src/texture/shared.rs b/crates/metal2vulkan-runtime/src/texture/shared.rs index 3dcdb84f4..803bfe18e 100644 --- a/crates/metal2vulkan-runtime/src/texture/shared.rs +++ b/crates/metal2vulkan-runtime/src/texture/shared.rs @@ -70,7 +70,7 @@ impl Device { // descriptor says, so a rotated one asserts as one without it does. let descriptor = &TextureDescriptor { framebuffer_only: false, - ..self.take_texture_options(CALL, descriptor) + ..self.texture_options(CALL, descriptor)? }; self.check_texture_placement( CALL, diff --git a/crates/metal2vulkan-runtime/src/texture/wrapped.rs b/crates/metal2vulkan-runtime/src/texture/wrapped.rs index 515a619ee..54bf3d266 100644 --- a/crates/metal2vulkan-runtime/src/texture/wrapped.rs +++ b/crates/metal2vulkan-runtime/src/texture/wrapped.rs @@ -534,7 +534,7 @@ impl Device { layouts: VkImageLayouts, ) -> Result { const CALL: &str = "new_texture_with_vk_image"; - let descriptor = &self.take_texture_options(CALL, descriptor); + let descriptor = &self.texture_options(CALL, descriptor)?; self.check_texture_placement( CALL, descriptor.placement, diff --git a/crates/metal2vulkan-runtime/src/values.rs b/crates/metal2vulkan-runtime/src/values.rs index 11330f476..a4dd98d01 100644 --- a/crates/metal2vulkan-runtime/src/values.rs +++ b/crates/metal2vulkan-runtime/src/values.rs @@ -123,13 +123,21 @@ impl ResourceOptions { const HAZARD_SHIFT: u32 = 8; const DEFINED: u64 = 0xf | (0xf << 4) | (0x3 << 8); - /// Bit 24 (0x100_0000), a private option plain Metal takes (a consumer's read-only detached - /// buffers pass it; Metal's validation stops it as undefined). Metal makes the resource and - /// reports its options without the bit (Metal probe `nc_bit24` on an M4). - /// [`from_raw`](Self::from_raw) takes it. A device makes a resource of options with it as - /// without it, reports its options without it, and announces - /// `metal2vulkan-degrade-private-resource-option` once: on Metal a no-copy buffer made with it - /// kept the GPU's writes from the CPU, where the runtime's reach it. + /// Bit 24 (0x100_0000), a private option (a consumer's read-only detached buffers and heaps + /// pass it). [`from_raw`](Self::from_raw) takes it. What Metal does with it (the M3 Max under + /// macOS 27.0.1), and the runtime: + /// - a no-copy buffer and a heap are made with it, and report their options without it: Metal + /// keeps the GPU's writes from their memory (a kernel's stores and a blit's fill reach + /// neither the CPU nor a later command buffer; a blit into a texture over or in the memory + /// faults the command buffer). The runtime makes them as without it, and announces + /// `metal2vulkan-degrade-private-resource-option` once; so does an indirect command buffer + /// made with it, which Metal makes and whose GPU-written records under it are not measured; + /// - a buffer placed in a heap without it is made as without it, as Metal's is, announcing + /// nothing; + /// - a buffer of a length or of bytes, and a texture descriptor, end Metal's process (the + /// buffer's suballocator and the texture descriptor's validation assert): refused `Invalid` + /// (`Problem::UndefinedValue`), as is a Vulkan buffer of the caller's + /// (`Device::new_buffer_with_vk_buffer`). pub const PRIVATE_BIT: u64 = 1 << 24; /// The options of these three modes. diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index a6916437e..778e8ddb6 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -56,7 +56,7 @@ pub(crate) struct Counters { variant_pipelines_made: AtomicU64, flights_followed: AtomicU64, variants_taken_back: AtomicU64, - unlisted_argument_sampler_failures: AtomicU64, + unlisted_argument_sampler_buffers: AtomicU64, host_step_sampler_sets_made: AtomicU64, creation_pipelines_made: AtomicU64, creation_pipelines_drawn: AtomicU64, @@ -794,11 +794,10 @@ impl Counters { self.variants_taken_back.fetch_add(1, Ordering::Relaxed); } - /// A command buffer committed whose commands' plans could not list the sampler states live - /// then (`sampler_listing.rs`), or whose host step's command left a live state out: it fails - /// `CommandBufferError::UnlistedArgumentSampler`. - pub(crate) fn unlisted_argument_sampler_failure(&self) { - self.unlisted_argument_sampler_failures + /// A command buffer committed whose commands' plans could not list every sampler state live + /// then (`sampler_listing.rs`), or whose host step's command left a live state out. + pub(crate) fn unlisted_argument_sampler_buffer(&self) { + self.unlisted_argument_sampler_buffers .fetch_add(1, Ordering::Relaxed); } @@ -2447,13 +2446,14 @@ pub struct WorkCounts { pub flights_followed: u64, /// Variants made again that took back a released variant's objects and `VkPipeline`s. pub variants_taken_back: u64, - /// Command buffers committed whose commands' plans could not list the sampler states live - /// as they committed (`sampler_listing.rs`): a state past the sampler arrays, more states - /// than the plan's tables hold, or a shape its checks refuse; or one of whose commands a host - /// step recorded after the commit left a live state out, past the sampler arrays. Each fails - /// `CommandBufferError::UnlistedArgumentSampler` unless another error fails it first, and - /// is counted once whether or not its functions reach the state left out. - pub unlisted_argument_sampler_failures: u64, + /// Command buffers committed whose commands' plans could not list every sampler state live + /// as they committed or as their batches were submitted (`sampler_listing.rs`): a state past + /// the sampler arrays, more states than the plan's tables hold, or a shape its checks refuse; + /// or one of whose commands a host step recorded after the commit left a live state out, past + /// the sampler arrays. Each runs, a function reading a state left out reading the neutral + /// sampler (`Degradation::UnlistedArgumentSampler`), and is counted once whether or not its + /// functions reach the state left out. + pub unlisted_argument_sampler_buffers: u64, /// Immutable sampler sets a command buffer's host step made, counting samplers on the /// scheduler's thread, because the device's map held no set of its variant's samplers: the /// open break (a render execution's step drawing a state made after its commit, on the variant @@ -3899,8 +3899,8 @@ impl Device { variant_pipelines_made: counters.variant_pipelines_made.load(Ordering::Relaxed), flights_followed: counters.flights_followed.load(Ordering::Relaxed), variants_taken_back: counters.variants_taken_back.load(Ordering::Relaxed), - unlisted_argument_sampler_failures: counters - .unlisted_argument_sampler_failures + unlisted_argument_sampler_buffers: counters + .unlisted_argument_sampler_buffers .load(Ordering::Relaxed), host_step_sampler_sets_made: counters .host_step_sampler_sets_made diff --git a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs index f6ccf1843..13e3e7de7 100644 --- a/crates/metal2vulkan-runtime/src/wrapped_buffer.rs +++ b/crates/metal2vulkan-runtime/src/wrapped_buffer.rs @@ -230,7 +230,7 @@ impl Device { options: ResourceOptions, ) -> Result { const CALL: &str = "new_buffer_with_vk_buffer"; - let options = self.take_options(CALL, options); + let options = self.own_memory_options(CALL, options)?; let modes = Modes::of(options)?; if !matches!(modes.storage, StorageMode::Shared | StorageMode::Private) { return Err(invalid(CALL, Problem::StorageMode)); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index f94945a82..0d5a25747 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -24,7 +24,7 @@ //! ([`UNPACKED_FILL`]), texture buffers' fills reading bytes past their pattern's copies in //! `texture_buffer_fills` ([`TEXTURE_BUFFER_FILL`]), draws of points no state sizes in //! `topology_classes` ([`UNSIZED_POINTS`]), -//! resource IDs ([`RESOURCE_IDS`], [`UNLISTED`]), +//! resource IDs ([`UNLISTED`]), //! indirect command buffers' commands naming a released state ([`RELEASED_STATES`]) and their host //! steps ([`HOST_STEPS`]), indirect dispatches' host reads ([`INDIRECT_DISPATCHES`]), indexed draws //! past their index buffer ([`INDEX_FETCHES`]), depth twins ([`TWINS`]) and uploads into depth @@ -186,6 +186,7 @@ use super::kept_buffer_bytes::KEPT_BYTES; use super::linear_attachments::{CHOSEN_COPIES, LINEAR_COPIES}; use super::mesh_draws::EMULATED_MESH; use super::mipmaps_exact::{M3_MIPMAPS, TIE_MIPMAPS}; +use super::no_copy_heaps::HEAP; use super::pass_start_reads::{FRAGMENTS_BEFORE_GEOMETRY, IN_PLACE_VERTEX_READS}; use super::patches::EMULATED_TESSELLATION; use super::pvrtc_textures::UNREADABLE; @@ -193,7 +194,7 @@ use super::rate_mapped_passes::ZERO_LAYER_AFTER_RELEASE; use super::rebind_reach::REBOUND_USES; use super::resolves::{color_pass, lane, quiet, MIXED_RESOLVES, ONE}; use super::resource_ids::{ - DELAYED_DEALLOCATORS, OWN_COPIES, PAST_CAPACITY, PAST_LAYOUT_SUPPORT, RESOURCE_IDS, UNLISTED, + DELAYED_DEALLOCATORS, OWN_COPIES, PAST_CAPACITY, PAST_LAYOUT_SUPPORT, UNLISTED, UNNAMED_SHADOWS, UNVIEWABLE, }; use super::rotated_textures::ROTATED_LOADS; @@ -245,10 +246,10 @@ use metal2vulkan::vk::ResolveModeFlags as Mode; use metal2vulkan::Budget; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ - BlitOption, CpuCacheMode, DebugMessage, Degradation, DegradationCategory, Device, + BlitOption, Buffer, CpuCacheMode, DebugMessage, Degradation, DegradationCategory, Device, DeviceOptions, DriverSetting, Error, HazardTrackingMode, HeapDescriptor, HeapType, HostMemory, LayerSetting, LayerSettingValue, LoadAction, MessageSeverity, MetalLevel, - MultisampleStencilResolveFilter, Origin, PipelineOptions, RenderPassDescriptor, + MultisampleStencilResolveFilter, Origin, PipelineOptions, Problem, RenderPassDescriptor, ResourceOptions, RuntimeGap, Size, StorageMode, StoreAction, TextureDescriptor, }; use std::collections::{BTreeMap, BTreeSet}; @@ -471,7 +472,6 @@ fn every_kind_has_a_site_a_lane_test_takes() { &UNPACKED_FILL, &TEXTURE_BUFFER_FILL, &FROM_HOST, - &RESOURCE_IDS, &UNLISTED, &RELEASED_STATES, &HOST_STEPS, @@ -913,45 +913,158 @@ fn an_anisotropic_state_without_mips_is_announced_through_metals_sampler() { /// takes its site, as a build without debug assertions does. const MISPLACED: [Degradation; 1] = [Degradation::MisplacedNotice]; -/// The kind Metal's private option bit takes ([`the_private_option_bit_is_ignored_once`]). +/// The kind Metal's private option bit takes where the GPU's writes reach the memory here +/// ([`the_private_option_bit_is_announced_on_a_heap_of_the_runtime_s_memory`], +/// [`the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory`]). const PRIVATE_OPTION: [Degradation; 1] = [Degradation::PrivateResourceOption]; -/// Metal's private option bit 24 (0x1000000), which plain Metal takes and reports its options -/// without (Metal probe `nc_bit24` on an M4), makes each resource as without it: buffers, a no-copy -/// buffer whose GPU writes reach the CPU here, a texture, a heap and a heap's buffer, each -/// reporting its options without the bit; it is announced once. +/// `options` with Metal's private option bit 24 (0x1000000). +fn with_private_bit(options: ResourceOptions) -> ResourceOptions { + ResourceOptions::from_raw(options.raw() | ResourceOptions::PRIVATE_BIT) + .expect("the runtime takes the private bit") +} + +/// Whether `made` is refused `Invalid` for the undefined option bits `raw`. +fn refused_bits(made: Result, raw: u64) -> bool { + matches!( + made, + Err(Error::Invalid(invalid)) if invalid.problem + == Problem::UndefinedValue { ty: "MTLResourceOptions", raw } + ) +} + +/// Where Metal ends the process at Metal's private option bit 24 (the M3 Max under macOS 27.0.1: +/// a buffer of a length or of bytes, `Shared` or `Private`, asserts in its suballocator, and a +/// texture descriptor in its validation), the runtime refuses the call `Invalid`; a buffer with it +/// placed in a heap without it is made as without it and reports its options without it, as +/// Metal's is. Nothing is announced. #[test] -fn the_private_option_bit_is_ignored_once() { +fn the_private_option_bit_is_refused_where_metal_ends_and_ignored_in_a_plain_heap() { + on_device(|device, messages| { + let shared = with_private_bit(ResourceOptions::shared()); + let private = with_private_bit(ResourceOptions::private()); + assert!(refused_bits(device.new_buffer(256, shared), shared.raw())); + assert!(refused_bits(device.new_buffer(256, private), private.raw())); + assert!(refused_bits( + device.new_buffer_with_bytes(&[7; 16], shared), + shared.raw() + )); + let mut d = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 4, 4, false); + d.resource_options = shared; + assert!(refused_bits(device.new_texture(&d), shared.raw())); + d.resource_options = private; + assert!(refused_bits(device.new_texture(&d), private.raw())); + let plain = ResourceOptions::private(); + let heap = device + .new_heap(&HeapDescriptor::new(HeapType::Automatic, 1 << 16, plain)) + .unwrap(); + assert!(refused_bits(heap.new_texture(&d), private.raw())); + let placed = heap.new_buffer(256, private).unwrap(); + assert_eq!( + placed.resource_options(), + heap.new_buffer(256, plain).unwrap().resource_options() + ); + assert_eq!( + placed.resource_options().raw() & ResourceOptions::PRIVATE_BIT, + 0 + ); + assert_made_once(messages, &[], &BTreeSet::new()); + }); +} + +/// A heap of the runtime's memory made with Metal's private option bit 24, which Metal makes and +/// keeps the GPU's writes from the memory of, is made as without it here, the GPU's writes +/// reaching the memory, the heap and a buffer placed in it reporting their options without the +/// bit; it is announced once. +#[test] +fn the_private_option_bit_is_announced_on_a_heap_of_the_runtime_s_memory() { + on_device(|device, messages| { + let private = with_private_bit(ResourceOptions::private()); + let heap = device + .new_heap(&HeapDescriptor::new(HeapType::Automatic, 1 << 16, private)) + .unwrap(); + assert_eq!( + heap.resource_options().raw() & ResourceOptions::PRIVATE_BIT, + 0 + ); + let placed = heap.new_buffer(256, private).unwrap(); + assert_eq!( + placed.resource_options().raw() & ResourceOptions::PRIVATE_BIT, + 0 + ); + assert_made_once(messages, &PRIVATE_OPTION, &BTreeSet::new()); + }); +} + +/// Whether the GPU's writes to no-copy memory made with Metal's private option bit 24 are +/// dropped here, as Metal drops them: on macOS, where the runtime imports its pages through a +/// read-only view of them (the runtime's `read_only_view.rs`). +const DROPS_WRITES: bool = cfg!(target_os = "macos"); + +/// Of `buffer`, a no-copy buffer over host pages whose bytes are its `contents`: the CPU writes +/// 0x11 to its first 16 bytes, a command buffer fills them with 0x5a, and later command buffers +/// copy them out, before and after the CPU writes 0x33 there. Whether they dropped the fill: the +/// pages and the first copy kept the CPU's 0x11, and the second read its 0x33. Where they took +/// it, the pages and the first copy hold 0x5a, and the second the CPU's 0x33. +fn drops_the_fill(device: &Device, buffer: &Buffer) -> bool { + let contents = buffer.contents().unwrap(); + let write = |byte: u8| { + // SAFETY: the buffer's first 16 bytes are host memory of this process, and no command + // uses them now. + unsafe { std::ptr::write_bytes(contents.as_ptr(), byte, 16) }; + }; + // SAFETY: as above. + let pages = || unsafe { std::slice::from_raw_parts(contents.as_ptr(), 16) }.to_vec(); + let queue = device.new_command_queue().unwrap(); + let run = |encode: &dyn Fn(&mut metal2vulkan_runtime::BlitCommandEncoder)| { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + encode(&mut blit); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.error(), None); + }; + let out = device.new_buffer(16, ResourceOptions::shared()).unwrap(); + let copied = || { + run(&|blit| { + blit.copy_from_buffer_to_buffer(buffer, 0, &out, 0, 16) + .unwrap() + }); + // SAFETY: `out` holds 16 bytes, and no command uses them now. + unsafe { std::slice::from_raw_parts(out.contents().unwrap().as_ptr(), 16) }.to_vec() + }; + write(0x11); + run(&|blit| blit.fill_buffer(buffer, 0..16, 0x5a).unwrap()); + let (kept, first) = (pages(), copied()); + write(0x33); + let second = copied(); + assert_eq!(second, [0x33; 16], "a later copy reads the CPU's bytes"); + assert_eq!(kept, first, "a later copy reads the pages"); + if kept == [0x11; 16] { + return true; + } + assert_eq!(kept, [0x5a; 16]); + false +} + +/// A no-copy buffer, a buffer placed in a no-copy heap and that buffer rebound to other pages, +/// made with Metal's private option bit 24, which Metal makes and keeps the GPU's writes from the +/// memory of (the M3 Max under macOS 27.0.1: a blit's fill reaches neither the CPU nor a later +/// command buffer, which reads the CPU's bytes): on macOS each drops a fill so, and nothing is +/// announced; elsewhere the fill reaches the pages, announced once. Each reports its options +/// without the bit, as Metal's does. +#[test] +fn the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory() { on_device(|device, messages| { let bit = ResourceOptions::PRIVATE_BIT; - let with_bit = |options: ResourceOptions| { - ResourceOptions::from_raw(options.raw() | bit).expect("Metal takes the private bit") - }; - let shared = with_bit(ResourceOptions::shared()); + let shared = with_private_bit(ResourceOptions::shared()); let plain = device .new_buffer(256, ResourceOptions::shared()) .unwrap() .resource_options(); - assert_eq!(plain.raw() & bit, 0); - let buffer = device.new_buffer(256, shared).unwrap(); - assert_eq!(buffer.resource_options(), plain); - let copied = device.new_buffer_with_bytes(&[7; 16], shared).unwrap(); - assert_eq!(copied.resource_options(), plain); - let mut d = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 4, 4, false); - d.resource_options = shared; - let texture = device.new_texture(&d).unwrap(); - assert_eq!(texture.resource_options().raw() & bit, 0); - let private = with_bit(ResourceOptions::private()); - let heap = device - .new_heap(&HeapDescriptor::new(HeapType::Automatic, 1 << 16, private)) - .unwrap(); - assert_eq!(heap.resource_options().raw() & bit, 0); - let placed = heap.new_buffer(256, private).unwrap(); - assert_eq!(placed.resource_options().raw() & bit, 0); - - // A no-copy buffer, the form RT4 measured: the GPU's writes reach the CPU, as without - // the bit. let memory = Mapping::anonymous(GUEST_PAGE); + let other = Mapping::anonymous(GUEST_PAGE); // SAFETY: the mapping outlives the buffer, which is dropped first. let no_copy = unsafe { device.new_buffer_with_bytes_no_copy( @@ -961,26 +1074,43 @@ fn the_private_option_bit_is_ignored_once() { None, ) }; - match no_copy { - Err(error) if not_importable(&error) => {} - no_copy => { - let no_copy = no_copy.unwrap(); - assert_eq!(no_copy.resource_options(), plain); - let queue = device.new_command_queue().unwrap(); - let command_buffer = queue.command_buffer().unwrap(); - let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(&no_copy, 0..16, 0x5a).unwrap(); - blit.end_encoding().unwrap(); - command_buffer.commit().unwrap(); - command_buffer.wait_until_completed_for(WAIT).unwrap(); - assert_eq!(command_buffer.error(), None); - // SAFETY: the mapping holds `GUEST_PAGE` bytes, and no command uses them now. - let bytes = unsafe { std::slice::from_raw_parts(memory.pointer().as_ptr(), 16) }; - assert_eq!(bytes, [0x5a; 16]); + let no_copy = match no_copy { + Err(error) if not_importable(&error) => { + eprintln!("PRIVATEBIT: the device imports no host memory: {error:?}"); + return; } + no_copy => no_copy.unwrap(), + }; + assert_eq!(no_copy.resource_options(), plain); + assert_eq!(drops_the_fill(device, &no_copy), DROPS_WRITES); + // Rebound to other pages, it drops the GPU's writes to them too. + // SAFETY: the other mapping outlives the buffer, and no other thread encodes or commits. + unsafe { no_copy.rebind_bytes_no_copy(HostMemory::new(other.pointer()), None, None) } + .unwrap(); + assert_eq!(no_copy.contents(), Some(other.pointer())); + assert_eq!(drops_the_fill(device, &no_copy), DROPS_WRITES); + let heap_memory = Mapping::anonymous(HEAP); + let descriptor = HeapDescriptor::new(HeapType::Automatic, HEAP as u64, shared); + // SAFETY: the mapping outlives the heap, which is dropped first. + let heap = unsafe { + device.new_heap_with_bytes_no_copy( + HostMemory::new(heap_memory.pointer()), + &descriptor, + None, + None, + ) } - // Beside it, what the `Shared` resources force on the device. - assert_made_once(messages, &PRIVATE_OPTION, &shared_kinds(device)); + .unwrap(); + assert_eq!(heap.resource_options().raw() & bit, 0); + let placed = heap.new_buffer(256, ResourceOptions::shared()).unwrap(); + assert_eq!(drops_the_fill(device, &placed), DROPS_WRITES); + drop((placed, heap, no_copy)); + // Beside them, what the `Shared` resources force on the device. + let kinds: &[Degradation] = match DROPS_WRITES { + true => &[], + false => &PRIVATE_OPTION, + }; + assert_made_once(messages, kinds, &shared_kinds(device)); }); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs index 619539e97..184dba3b8 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs @@ -1985,7 +1985,8 @@ fn memory_metal_makes_no_buffer_over_is_refused_when_it_is_made() { /// did not make: what Metal stops (`Invalid`: Private and Memoryless storage), and what plain /// Metal answers nil for (`Nil`: length 0, and its descriptor form, and a length past /// `max_buffer_length`). (The private option bit the consumer's detached buffers -/// send, 0x1000000, is taken: `degrade_notices`' `the_private_option_bit_is_ignored_once`.) +/// send, 0x1000000, is taken: `degrade_notices`' +/// `the_private_option_bit_is_announced_where_the_gpu_s_writes_reach_the_memory`.) #[test] fn refused_no_copy_buffers_never_run_their_deallocator() { on_device(|device| { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs b/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs index 527627be8..9b0f880bb 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/render_executions.rs @@ -2572,32 +2572,32 @@ fn a_host_step_s_draw_of_a_state_made_after_the_commit_binds_a_neutral_made_befo }); } -/// The most sampler states [`a_host_step_s_draw_past_its_sampler_arrays_fails_its_command_buffer`] +/// The most sampler states [`a_host_step_s_draw_past_its_sampler_arrays_runs_with_the_states_it_lists`] /// makes to crowd its variant's set-1 sampler arrays (`resource_ids`' crowd). const HOST_CROWD: u64 = 2048; /// A command a host step records after its command buffer's commit is listed again by no commit /// (`sampler_listing.rs`), so one that leaves a live sampler state out of its argument samplers, /// more states living than its variant's set-1 sampler arrays hold (`heap_sets::fit_samplers`), -/// fails its command buffer as it completes (`CommandBufferError::UnlistedArgumentSampler`, Metal -/// code 1), announced once (`UNLISTED`) and counted once -/// (`WorkCounts::unlisted_argument_sampler_failures`), where the command buffer completed with the -/// function reading the neutral sampler for the state left out. The host step draws, as in +/// runs with the states it lists, announced once (`UNLISTED`) and counted once +/// (`WorkCounts::unlisted_argument_sampler_buffers`): the command buffer completes, and a function +/// reading a state left out would read the neutral sampler. The host step draws, as in /// [`a_host_step_s_draw_of_a_state_made_after_the_commit_binds_a_neutral_made_before_it`], a state /// made after the commit whose fragment function samples a texture through a sampler state its /// argument buffer holds (`render_arguments::SAMPLED`). With 20 more states made after the commit, /// within the arrays, the draw writes Metal's texels and nothing fails or is counted. The line /// `SAMPLER-CAPACITY` reports the step's variant's arrays; where they hold at most [`HOST_CROWD`] -/// elements, as many more states made after the commit leave one out. Where they hold more (65536 +/// elements, as many more states made after the commit leave one out, and the draw, whose state +/// was made before them and is listed, still writes Metal's texels. Where they hold more (65536 /// on lavapipe and the M4), filling them takes more Vulkan samplers than lavapipe allows /// (`maxSamplerAllocationCount` 32768), so that half runs only on such a device. #[test] -fn a_host_step_s_draw_past_its_sampler_arrays_fails_its_command_buffer() { +fn a_host_step_s_draw_past_its_sampler_arrays_runs_with_the_states_it_lists() { let case = public_render(SAMPLED); let metal = case.metal_output.clone().unwrap(); on_device(|device, messages| { - let failures = || device.work_counts().unlisted_argument_sampler_failures; - let before = failures(); + let unlisted = || device.work_counts().unlisted_argument_sampler_buffers; + let before = unlisted(); let render = &case.render; let fragment = render.fragment.as_ref().expect("a fragment case"); let members = Members::of(device, fragment); @@ -2695,7 +2695,7 @@ fn a_host_step_s_draw_past_its_sampler_arrays_fails_its_command_buffer() { let (command_buffer, target) = step(20); assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); assert_eq!(output(&case, &target, &members), metal, "Metal's texels"); - assert_eq!(failures(), before, "20 more states"); + assert_eq!(unlisted(), before, "20 more states"); let made = [sampled_descriptor(device, &case)]; assert_made_once(messages, &HOST_STEPS, &forced_with(device, &made)); let executions = command_buffer.executions(); @@ -2717,12 +2717,11 @@ fn a_host_step_s_draw_past_its_sampler_arrays_fails_its_command_buffer() { device.name() ); if u64::from(capacity) <= HOST_CROWD { - let (command_buffer, _) = step(capacity.into()); - assert_eq!(command_buffer.status(), CommandBufferStatus::Error); - let error = command_buffer.error().expect("the command buffer's error"); - assert_eq!(error, CommandBufferError::UnlistedArgumentSampler); - assert_eq!(error.metal_code(), 1); - assert_eq!(failures(), before + 1, "counted once"); + let (command_buffer, target) = step(capacity.into()); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + assert_eq!(output(&case, &target, &members), metal, "past the arrays"); + assert_eq!(unlisted(), before + 1, "counted once"); let steps = HOST_STEPS.into_iter().collect(); assert_made_once(messages, &UNLISTED, &steps); } diff --git a/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs b/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs index 7ea5e67e9..aacd5597f 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/resource_ids.rs @@ -6,7 +6,7 @@ //! M4 probe, residency part C), a heap's and a sparse heap's alike, and the neutral //! texture once that holder went. The kernel samples a 2-by-2 `RGBA32Uint` texture through a //! sampler held beside it, so its output is the texels it reached (a float twin of the case reads -//! `RGBA16Float` linearly). Each degradation site of the kinds ([`RESOURCE_IDS`] and the device +//! `RGBA16Float` linearly). Each degradation site of the kinds (the device //! heap's: [`UNVIEWABLE`], [`UNNAMED_SHADOWS`], [`PAST_CAPACITY`], [`PAST_LAYOUT_SUPPORT`], //! [`OWN_COPIES`]) is taken on a device of its own and announced once. @@ -38,23 +38,13 @@ use metal2vulkan::metal::{ SamplerMinMagFilter, TextureType, TextureUsage, }; use metal2vulkan_runtime::{ - BlitOption, Buffer, BufferContents, BufferDescriptor, CommandBuffer, CommandBufferError, - CommandBufferStatus, CommandQueue, ComputePipelineState, Deallocator, DebugMessage, - Degradation, Device, DeviceOptions, Error, EventRef, ExecutedPipeline, Fence, Heap, - HeapDescriptor, HeapType, HostMemory, IdPlacement, IndirectCommandBuffer, - IndirectCommandBufferDescriptor, Invalid, IoSurfacePlane, KeepAlive, MessageSeverity, - MessageSink, Origin, Problem, Region, RenderPassDescriptor, ResourceId, ResourceIdKind, - ResourceOptions, SamplerState, SamplerStateOptions, SharedEvent, Size, Texture, - TextureDescriptor, TextureSwizzleChannels, + BlitOption, Buffer, BufferContents, BufferDescriptor, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, ComputePipelineState, Deallocator, DebugMessage, Degradation, Device, DeviceOptions, Error, EventRef, ExecutedPipeline, Fence, Heap, HeapDescriptor, HeapType, HostMemory, IdPlacement, IndirectCommandBuffer, IndirectCommandBufferDescriptor, Invalid, IoSurfacePlane, KeepAlive, MemoryKind, MessageSeverity, MessageSink, Origin, Problem, Region, RenderPassDescriptor, ResourceId, ResourceIdKind, ResourceOptions, SamplerState, SamplerStateOptions, SharedEvent, Size, Texture, TextureDescriptor, TextureSwizzleChannels, }; use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -/// The kind this module's takeover tests take: one site per test, each on a device of its own. -pub(super) const RESOURCE_IDS: [Degradation; 1] = [Degradation::ResourceIdTakeover]; - /// The kind [`a_sampler_state_at_any_id_is_listed`] takes where more sampler states live than /// the device's or the pipeline's sampler arrays hold (and expects absent elsewhere). pub(super) const UNLISTED: [Degradation; 1] = [Degradation::UnlistedArgumentSampler]; @@ -1745,30 +1735,84 @@ fn a_device_without_pending_writes_binds_a_copy_per_command_buffer() { ); } -/// A sampler state made to support argument buffers while a committed command buffer that lists -/// the argument samplers waits is announced: its sampler table lists the states of its -/// encoding. +/// A sampler state that takes the ID a dispatch's argument buffer names, made after its command +/// buffer committed and before the event it waits for is signalled, is reached through that ID, as +/// Metal's function reaches it (the M3 Max under macOS 27.0.1: a state made after the commit, +/// its ID written into the argument buffer before the signal, is the one sampled): the batch's +/// submission lists the states live then. Nothing is announced. (On a device without +/// `descriptorBindingUpdateUnusedWhilePending`, which no venue is, the commit's listing stands: +/// `sampler_listing.rs`.) #[test] -fn a_sampler_state_made_while_samplers_are_listed_degrades() { +fn a_sampler_state_made_after_the_commit_before_its_wait_is_reached_by_its_id() { + on_device(|device, messages| { + let mut sampling = Sampling::new(device); + let key = *sampling + .case + .compute + .argument_buffer_samplers + .keys() + .next() + .unwrap(); + let resource = &sampling.case.compute.argument_buffer_samplers[&key]; + let mut descriptor = argument_sampler_descriptor(resource); + descriptor.normalized_coordinates = false; + assert_ne!(corner(), sampling.case.metal_output); + let texture = sampling.texture().clone(); + let event = device.new_shared_event().unwrap(); + let wait = EventRef::from(&event); + let (command_buffer, buffers) = + sampling.encode(device, &texture, Some(&texture), Some(wait)); + command_buffer.commit().unwrap(); + let own = sampling.base.argument_samplers.remove(&key).unwrap(); + let id = own.gpu_resource_id(); + drop(own); + let mut options = SamplerStateOptions::default(); + options.support_argument_buffers = true; + options.placement = IdPlacement::At(id); + let state = device + .new_sampler_state_with_options(&descriptor, options) + .unwrap(); + assert_eq!(state.gpu_resource_id(), id); + event.set_signaled_value(1); + assert_eq!( + sampling.output(&command_buffer, &buffers), + corner(), + "through ID {} after the commit", + id.0 + ); + sampling.announced(device, messages, &[]); + drop(state); + }); +} + +/// Sampler states made after a dispatch's command buffer committed and before the event it waits +/// for is signalled, 64 more than the case's (past twice the capacity class of the states live as +/// the dispatch was encoded), are more than the command's plan's tables hold as its batch is +/// submitted: the command keeps the states its commit listed, the case's among them, so the +/// command buffer completes with the case's output, announced once (`UNLISTED`, on the scheduler's +/// thread) and counted once (`WorkCounts::unlisted_argument_sampler_buffers`). +#[test] +fn sampler_states_made_after_the_commit_past_the_class_keep_the_commit_s_listing() { on_device(|device, messages| { let sampling = Sampling::new(device); let texture = sampling.texture(); + let unlisted = || device.work_counts().unlisted_argument_sampler_buffers; + let before = unlisted(); let event = device.new_shared_event().unwrap(); let wait = EventRef::from(&event); let (command_buffer, buffers) = sampling.encode(device, texture, Some(texture), Some(wait)); command_buffer.commit().unwrap(); - let mut options = SamplerStateOptions::default(); - options.support_argument_buffers = true; - let mut descriptor = SamplerDescriptor::new(); - descriptor.min_filter = SamplerMinMagFilter::Linear; - let state = device - .new_sampler_state_with_options(&descriptor, options) - .unwrap(); + let past = distinct_sampler_states(device, 64); event.set_signaled_value(1); - let output = sampling.output(&command_buffer, &buffers); - assert_eq!(output, sampling.case.metal_output); - drop(state); - sampling.announced(device, messages, &RESOURCE_IDS); + assert_eq!( + sampling.output(&command_buffer, &buffers), + sampling.case.metal_output, + "64 more states" + ); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(unlisted(), before + 1); + sampling.announced(device, messages, &UNLISTED); + drop(past); }); } @@ -1876,13 +1920,13 @@ pub(super) fn distinct_sampler_states(device: &Device, count: u64) -> Vec