From f02e4d40afbf8bf9a4e79ffee7b16334c200cec6 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 9 Nov 2026 15:02:34 -0800 Subject: [PATCH] Spares on ANV: free command buffers without trimming the pool, the kept barriers' submissions fail after a trim Iris's runtime_lane::predication::streams_run_what_metal_ran failed at 39b45dd232 as a GpuRecoveryVictim: vkQueueSubmit of a batch returned VK_ERROR_DEVICE_LOST (submit.rs's submit_batch), because DRM_IOCTL_I915_GEM_EXECBUFFER2 returned ENOENT (strace), the execbuffer's object list holding an object of handle 0 (INTEL_DEBUG=submit). Bisected to 9c458c96a6, the give-back's frees moved to the free thread, uncapped. The cause is ANV's chaining (Mesa main of 2026-11-09, read): a submission's command buffers are chained, each one's last batch buffer object jumping to the next one's first, and under i915 the jump adds the next one's object to those the first names (anv_cmd_buffer_record_chain_submit), which only a reset or begin clears (anv_batch_bo_start). The kept barriers are submitted again as recorded, so each submission names every command buffer that ever came next after one. A freed command buffer stays in Mesa's common pool with its first batch buffer object until vkTrimCommandPool destroys it; batch buffer objects are slices of 2 MiB slabs whose handle is closed once every slice is free. The spares' uncapped frees and trims emptied whole slabs, and the next submission of a kept barrier named a closed handle. The probes on ms01's Iris Xe (Mesa 26.2.6, i915): the stream failed in each of 4 runs as committed; it passed in each of 2 runs that freed without trimming, 2 that freed nothing, and 3 whose kept barriers were begun with SIMULTANEOUS_USE (which ANV never chains). Every command buffer submitted at the failure was owned and none freed (an ownership trace of the spares), and the validation layer, on in that test, reported nothing at the failure. RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission names it, on every ANV GPU (under the xe kernel driver ANV records no such objects, but no GPU of it is measured). There a spare pool's command buffers are freed, still on the free thread, and the pool is not trimmed (release::PoolBuffers takes a trim flag; Spares::new(trims) from the device's defects); the priming still trims, its command buffer never following a kept one. The kept barriers keep their chaining: SIMULTANEOUS_USE would split each batch into an execbuffer per kept barrier. The cost on ANV: a pool keeps, in the driver, as many command buffers' objects as it held at once, reset. Tests: tests::spares::device::kept_barriers_run_again_after_the_command_buffers_after_them_were_freed (a burst whose middle KEPT encoders come after kept barriers, freed past the recent uses, then the kept barriers submitted again; every command buffer completes, no recovery); tests::driver_defects lists the defect for every ANV profile. To be run on ms01's Iris Xe with the fix and without it. api_signatures.tsv blessed (one variant row); docs/REFUSALS.md regenerated: unchanged. (cherry picked from commit 4e392a6bc8507445693982c6c041535490a4cc34) --- .../src/command_buffer/kept_barriers.rs | 5 +- crates/metal2vulkan-runtime/src/device/mod.rs | 8 +- .../metal2vulkan-runtime/src/device/prime.rs | 14 ++- .../src/driver_defects.rs | 30 +++++++ crates/metal2vulkan-runtime/src/release.rs | 30 ++++--- crates/metal2vulkan-runtime/src/spares.rs | 68 ++++++++++++--- .../src/tests/driver_defects.rs | 8 +- .../metal2vulkan-runtime/src/tests/spares.rs | 86 +++++++++++++++++-- crates/metal2vulkan/src/error/mod.rs | 7 ++ crates/metal2vulkan/tests/api_signatures.tsv | 1 + 10 files changed, 223 insertions(+), 34 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs b/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs index 27c5b6bec..abc5ac228 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/kept_barriers.rs @@ -23,7 +23,10 @@ //! (`anv_cmd_buffer_is_chainable`), and submits the rest one execbuffer each. The batch that //! takes one marks it with its own timeline value before it is submitted: a batch whose //! submission fails leaves that value to the queue's next batch, so the command buffer waits -//! for that one instead. +//! for that one instead. Chained so, a kept command buffer names in each submission every +//! command buffer that ever came next after it, and the submission fails once one of those was +//! trimmed away (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`): there the +//! spares free command buffers without trimming their pools (`spares.rs`). //! - **Timestamps, per slot.** A command buffer that writes timestamps writes them into one slot's //! two queries, so it is kept for its slot ([`SlotStamps`]): one per slot and list, taken again //! only by a batch of a later holding of that slot (`gpu_time::Slot::lease`), once the batch diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 1ae61f92d..410ad2d9b 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -2487,6 +2487,12 @@ impl Device { // Read before the properties move into the device's shared state (below): whether the // scheduler's thread waits for the GPU itself (`scheduler::waits_on_gpu`). let waits_on_gpu = crate::scheduler::waits_on_gpu(&properties.driver_defects); + // And whether a spare command pool is trimmed after its frees: not where a trim fails the + // kept barriers (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`, + // `spares.rs`). + let trims_spares = !properties + .driver_defects + .contains(&RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission); if let (Some(relay), true) = (instance.relay(), relays) { for slot in &queues { let queue = slot.with(|queue| queue); @@ -2682,7 +2688,7 @@ impl Device { host_copies, zero_initialize_device_memory, sparse, - spares: Spares::default(), + spares: Spares::new(trims_spares), live_binds: Default::default(), coverage_pools: Default::default(), live_dispatches: Default::default(), diff --git a/crates/metal2vulkan-runtime/src/device/prime.rs b/crates/metal2vulkan-runtime/src/device/prime.rs index 9af8bbae7..eada5530e 100644 --- a/crates/metal2vulkan-runtime/src/device/prime.rs +++ b/crates/metal2vulkan-runtime/src/device/prime.rs @@ -783,10 +783,20 @@ impl Primer<'_> { .map_err(vulkan)?; self.made(Call::QueueWaitIdle); // A spare pool's command buffers freed and the pool trimmed as a command buffer gives it - // back (`spares.rs`). + // back (`spares.rs`). Trimmed on every device: no command buffer submitted again ever + // came before the priming's (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`). // SAFETY: the command buffer is the priming's pool's, its one submission completed, and // the pool is the priming's alone. - unsafe { release::object(device, release::PoolBuffers(pool, &buffers)) }; + unsafe { + release::object( + device, + release::PoolBuffers { + pool, + buffers: &buffers, + trim: true, + }, + ) + }; self.made(Call::FreeCommandBuffers); self.made(Call::TrimCommandPool); if let Some(queries) = queries { diff --git a/crates/metal2vulkan-runtime/src/driver_defects.rs b/crates/metal2vulkan-runtime/src/driver_defects.rs index 2a113c6d1..805f890d9 100644 --- a/crates/metal2vulkan-runtime/src/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/driver_defects.rs @@ -545,6 +545,31 @@ pub(super) struct Affected { /// `tests::host_ram_device::a_run_bound_and_a_chunk_bound_buffer_over_the_same_pages_order_by_their_host_bytes` /// and `a_run_bound_buffer_and_a_copy_of_its_pages_order_by_their_host_bytes` failed there in /// each of two runs. Nothing is refused, as on MoltenVK. +/// +/// `TrimmedCommandBufferFailsResubmission`: +/// - Mesa's ANV (`INTEL_OPEN_SOURCE_MESA`): a submission's command buffers are chained into one +/// batch, each one's end jumping to the first batch buffer object of the next +/// (`anv_cmd_buffer_record_chain_submit` in `anv_batch_chain.c`), and under i915 that jump adds +/// the next one's buffer object to those its last batch buffer object names, which only its +/// reset or begin clears (`anv_batch_bo_start`). A command buffer submitted again as recorded, +/// as a batch's kept barriers are (`command_buffer/kept_barriers.rs`), so names at each +/// submission the first batch buffer object of every command buffer that ever came next after +/// it. A freed command buffer stays in its pool, its first batch buffer object with it, for the +/// pool's later allocations (`vk_command_pool.c`), until `vkTrimCommandPool` destroys it; a +/// batch buffer object is a slice of a larger one (`anv_slab_bo.c`), whose handle is released +/// once every slice of it is free. The next submission that names such a handle fails: +/// `DRM_IOCTL_I915_GEM_EXECBUFFER2` returns `ENOENT`, its object list holding an object of +/// handle 0 (`INTEL_DEBUG=submit`), and `vkQueueSubmit` returns `VK_ERROR_DEVICE_LOST`. +/// Measured on Iris Xe Graphics (Raptor Lake-P) under Mesa 26.2.6 on i915: +/// `runtime_lane::predication::streams_run_what_metal_ran`, under the validation layer, which +/// reported nothing, failed so in each of 4 runs once a spare pool's frees ran uncapped on the +/// device's free thread (`spares.rs`), and passed in each of 2 runs whose frees did not trim, +/// 2 that freed nothing, and 3 whose kept barriers were begun with +/// `VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT`, which ANV never chains. Read in Mesa main's +/// source of 2026-11-09. Nothing is refused: a spare pool's command buffers are freed without +/// trimming the pool there, so its later command buffers take them again; what each holds of +/// its recording the driver releases as it frees it. Under the xe kernel driver ANV names no +/// such objects (`uses_relocs`), but no GPU of it is measured, so every ANV GPU takes the path. pub(super) const AFFECTED: &[Affected] = &[ Affected { defect: RuntimeDriverDefect::HostTransferImagesCopiedAtBind, @@ -713,6 +738,11 @@ pub(super) const AFFECTED: &[Affected] = &[ driver: DriverId::INTEL_OPEN_SOURCE_MESA, clean: &[], }, + Affected { + defect: RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission, + driver: DriverId::INTEL_OPEN_SOURCE_MESA, + clean: &[], + }, ]; /// The defects of the driver and device `description` names, its GPU read by the `deviceID` it diff --git a/crates/metal2vulkan-runtime/src/release.rs b/crates/metal2vulkan-runtime/src/release.rs index 0e7da9887..1725f5471 100644 --- a/crates/metal2vulkan-runtime/src/release.rs +++ b/crates/metal2vulkan-runtime/src/release.rs @@ -145,25 +145,33 @@ pub(crate) unsafe fn generated(commands: &Commands, object: Generated) -> bool { } /// Command buffers of one command pool, freed together (`vkFreeCommandBuffers`), the pool then -/// trimmed (`vkTrimCommandPool`), so that the driver returns what it keeps of them: a spare pool's -/// past its recent uses (`spares.rs`). -pub(crate) struct PoolBuffers<'a>( - pub(crate) vk::CommandPool, - pub(crate) &'a [vk::CommandBuffer], -); +/// trimmed (`vkTrimCommandPool`) where `trim`, so that the driver returns what it keeps of them: a +/// spare pool's past its recent uses (`spares.rs`), whose pool is not trimmed where the driver +/// fails a command buffer submitted again once one that came next after it is trimmed +/// (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`, `driver_defects.rs`). +pub(crate) struct PoolBuffers<'a> { + pub(crate) pool: vk::CommandPool, + pub(crate) buffers: &'a [vk::CommandBuffer], + pub(crate) trim: bool, +} impl Released for PoolBuffers<'_> { const CALL: Call = Call::FreeCommandBuffers; unsafe fn destroy(self, device: &ash::Device, _: Door) { - let PoolBuffers(pool, buffers) = self; + let PoolBuffers { + pool, + buffers, + trim, + } = self; // SAFETY: the caller's: none of the command buffers is pending, and it holds the pool // alone. - unsafe { - device.free_command_buffers(pool, buffers); - device.trim_command_pool(pool, vk::CommandPoolTrimFlags::empty()); + unsafe { device.free_command_buffers(pool, buffers) }; + if trim { + // SAFETY: as above. + unsafe { device.trim_command_pool(pool, vk::CommandPoolTrimFlags::empty()) }; + exit_guard::called(Call::TrimCommandPool); } - exit_guard::called(Call::TrimCommandPool); } } diff --git a/crates/metal2vulkan-runtime/src/spares.rs b/crates/metal2vulkan-runtime/src/spares.rs index cf37d7b57..86f0531a5 100644 --- a/crates/metal2vulkan-runtime/src/spares.rs +++ b/crates/metal2vulkan-runtime/src/spares.rs @@ -28,11 +28,12 @@ //! - **Freed on the device's free thread** ([`PoolFrees`], `free_thread.rs`), not on the thread //! giving the pool back, which for a command buffer that completed is its queue's completion //! thread before its completed handlers run and its waiters return: [`FREED_AT_ONCE`] command -//! buffers at a time, `vkFreeCommandBuffers` then `vkTrimCommandPool`, which returns what the -//! driver keeps of freed command buffers (`release.rs`'s `PoolBuffers`), each inside a section -//! of the exit guard. The pool stays out of the spares until its frees ran (a command pool needs -//! external synchronization), so a taker meanwhile takes another spare or makes a pool. Where -//! the free thread's queue is full, or the thread cannot start, they run on the giving thread. +//! buffers at a time, `vkFreeCommandBuffers` then `vkTrimCommandPool` (but on ANV, below), +//! which returns what the driver keeps of freed command buffers (`release.rs`'s +//! `PoolBuffers`), each inside a section of the exit guard. The pool stays out of the spares +//! until its frees ran (a command pool needs external synchronization), so a taker meanwhile +//! takes another spare or makes a pool. Where the free thread's queue is full, or the thread +//! cannot start, they run on the giving thread. //! The device's teardown waits for those posted before it releases the spares. Counted (the //! crate's tests): `Spares::freed_on`, the threads that freed them. On a Radeon 780M (RADV), in //! release (`tests::spares_latency`), a give-back that freed a burst's command buffers on the @@ -47,6 +48,15 @@ //! (0.22 ms at the slowest); on an Apple M3 Max (MoltenVK 1.4.2) 0.9 to 1.0 us each (3.5 us at //! the slowest), the process's physical footprint unchanged by them (its first 252 command //! buffers had added 176 KiB to it, which stayed); on lavapipe a few microseconds. +//! - **Not trimmed where a trim fails the kept barriers** (ANV: +//! `RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`, `driver_defects.rs`). A +//! batch's kept barriers are submitted again as recorded (`command_buffer/kept_barriers.rs`), +//! and there each such submission names every command buffer that ever came next after one; +//! once one of those is trimmed away, the submission fails and the device is lost. So the pool's +//! command buffers are freed and the pool is not trimmed: the driver keeps each one it freed, +//! reset, for the pool's later allocations (Mesa's common command pool, `vk_command_pool.c`), a +//! pool holding for the device's life as many command buffers' objects as it held at once, but +//! none of their recordings beyond each one's first batch buffer object. //! - **Descriptor pools are bounded.** At most [`DESCRIPTOR_POOLS`] descriptor pools of at most //! [`DESCRIPTORS`] descriptors together; a descriptor pool given back past them releases the //! oldest spares first, so the spares follow the shapes in use. The descriptors bound the @@ -160,8 +170,8 @@ pub(super) const RECENT_USES: usize = 8; /// module docs). pub(super) const IDLE_FOR: Duration = Duration::from_secs(10); -/// The most command buffers one `vkFreeCommandBuffers` frees, the pool trimmed after each (the -/// module docs). +/// The most command buffers one `vkFreeCommandBuffers` frees, the pool trimmed after each where +/// the device trims (the module docs). pub(super) const FREED_AT_ONCE: usize = 32; /// The index of `level`'s list in a [`CommandPool`]: primary 0, secondary 1. @@ -399,11 +409,14 @@ pub(super) struct DescriptorPool { } /// A device's spares. -#[derive(Default)] pub(super) struct Spares { /// Oldest first, shared with the device's free thread, which keeps a pool again once its /// command buffers are freed ([`PoolFrees`]). command_pools: Arc>>, + /// A pool is trimmed after its command buffers are freed, but where the driver fails a + /// command buffer submitted again once one that came next after it is trimmed (the module + /// docs). + trims: bool, /// The names of the threads that freed spares' command buffers, one each time, for the /// crate's device tests. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -415,6 +428,19 @@ pub(super) struct Spares { } impl Spares { + /// The spares of a device, which trims a command pool after freeing its command buffers + /// where `trims` (the module docs). + pub(super) fn new(trims: bool) -> Spares { + Spares { + command_pools: Default::default(), + trims, + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + freed_on: Default::default(), + descriptor_pools: Default::default(), + fitted_pools: Default::default(), + } + } + /// A spare command pool of `device` made for queue family `family`, none of whose command /// buffers is pending or recording (reset where one may be, the module docs); `None` when /// there is none, or this thread is in a section. @@ -520,6 +546,7 @@ impl Spares { pool, buffers, idle, + trim: self.trims, spares: Arc::clone(&self.command_pools), #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] freed_on: Arc::clone(&self.freed_on), @@ -533,6 +560,13 @@ impl Spares { lock(&self.freed_on).clone() } + /// Whether a pool is trimmed after its command buffers are freed, for the crate's device + /// tests. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(super) fn trims(&self) -> bool { + self.trims + } + /// The command buffers the spare command pools hold, for the crate's device tests. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(super) fn command_buffers_held(&self) -> usize { @@ -653,6 +687,8 @@ pub(crate) struct PoolFrees { buffers: Vec, /// Kept again as the oldest spare (a spare left idle), else as the newest. idle: bool, + /// The pool is trimmed after each free (the module docs). + trim: bool, /// The device's spare command pools. spares: Arc>>, #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] @@ -661,8 +697,8 @@ pub(crate) struct PoolFrees { impl PoolFrees { /// Free the command buffers through `device`, the device's functions taken inside a section of - /// the exit guard, [`FREED_AT_ONCE`] at a time, the pool trimmed after each (`release.rs`'s - /// `PoolBuffers`), then keep the pool among the spares again. + /// the exit guard, [`FREED_AT_ONCE`] at a time, the pool trimmed after each where the device + /// trims (`release.rs`'s `PoolBuffers`), then keep the pool among the spares again. /// /// # Safety /// @@ -672,13 +708,23 @@ impl PoolFrees { pool, buffers, idle, + trim, spares, #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] freed_on, } = self; for some in buffers.chunks(FREED_AT_ONCE) { // SAFETY: the caller's. - unsafe { release::object(device, release::PoolBuffers(pool.raw, some)) }; + unsafe { + release::object( + device, + release::PoolBuffers { + pool: pool.raw, + buffers: some, + trim, + }, + ) + }; } #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] lock(&freed_on).push(std::thread::current().name().unwrap_or_default().to_owned()); diff --git a/crates/metal2vulkan-runtime/src/tests/driver_defects.rs b/crates/metal2vulkan-runtime/src/tests/driver_defects.rs index ca9493ed2..8f86fd058 100644 --- a/crates/metal2vulkan-runtime/src/tests/driver_defects.rs +++ b/crates/metal2vulkan-runtime/src/tests/driver_defects.rs @@ -35,6 +35,7 @@ const UNPINNABLE: RuntimeDriverDefect = RuntimeDriverDefect::UnpinnablePagesBrea const VOLUME_BLITS: RuntimeDriverDefect = RuntimeDriverDefect::VolumeBlitsUnfiltered; const ALIASED_BLITS: RuntimeDriverDefect = RuntimeDriverDefect::AliasedImportBlitsUnordered; const VOLUME_RESOLVES: RuntimeDriverDefect = RuntimeDriverDefect::VolumeResolveFirstPlane; +const TRIMS: RuntimeDriverDefect = RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission; /// Every committed profile's driver has its defects at every release and GPU but those a probe /// found clean: MoltenVK the multisampled depth/stencil colour copies, the inexact depths past @@ -57,8 +58,9 @@ const VOLUME_RESOLVES: RuntimeDriverDefect = RuntimeDriverDefect::VolumeResolveF /// preprocessing after an execution set on every GPU but the 780M (Phoenix's and Hawk Point's), /// measured clean; ANV /// the compressed image's short size, the occlusion count per color output, the pushed -/// descriptors a pipeline bind leaves stale and the blits through two imports of the same host -/// pages a barrier does not order on every GPU (Arrow Lake's, not measured, too); +/// descriptors a pipeline bind leaves stale, the blits through two imports of the same host +/// pages a barrier does not order and the submission again of a command buffer that a trimmed one +/// came after on every GPU (Arrow Lake's, not measured, too); /// NVIDIA's the /// stencil colour copies on every GPU but the RTX 5080 Laptop GPU, measured clean (the GTX 1060 and /// the RTX 5080 desktop GPU, not measured, take them), the 10-bit codes its Y′CbCr conversion reads @@ -108,7 +110,7 @@ fn the_committed_profiles_drivers_have_their_defects() { vec![NAN_COPIES, PREPROCESS, TEN_BIT_WORDS, VOLUME_RESOLVES] } Some(DriverId::INTEL_OPEN_SOURCE_MESA) => { - vec![COMPRESSION, COUNTS, STALE_PUSHES, ALIASED_BLITS] + vec![COMPRESSION, COUNTS, STALE_PUSHES, ALIASED_BLITS, TRIMS] } Some(DriverId::NVIDIA_PROPRIETARY) if desc.device_id == 0x2c19 => { vec![TEN_BIT_WORDS, UNPINNABLE, VOLUME_RESOLVES] diff --git a/crates/metal2vulkan-runtime/src/tests/spares.rs b/crates/metal2vulkan-runtime/src/tests/spares.rs index 86a8197e6..2839b75a9 100644 --- a/crates/metal2vulkan-runtime/src/tests/spares.rs +++ b/crates/metal2vulkan-runtime/src/tests/spares.rs @@ -1,5 +1,5 @@ //! A device's spare command pools and descriptor pools (`spares.rs`): which command buffers a pool -//! hands out again, and what the bounds keep. The last test runs on a device: device tests compile +//! hands out again, and what the bounds keep. The last tests run on a device: device tests compile //! only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`). use crate::descriptor_arena::{Room, SetNeeds}; @@ -383,13 +383,19 @@ fn a_spare_left_idle_sheds_its_command_buffers_and_goes_back_the_oldest() { #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod device { use super::RECENT_USES; + use crate::command_buffer::kept_barriers::KEPT; use crate::tests::freed_memory::device; - use crate::{Buffer, CommandQueue, Device, ResourceOptions}; + use crate::{Buffer, CommandBufferStatus, CommandQueue, Device, ResourceOptions}; use std::time::{Duration, Instant}; /// The blit encoders of the burst's command buffer. const BURST: usize = 64; + /// The blit encoders of the trims test's burst, each filling a buffer of its own, before + /// those filling one buffer, each after a barrier, and after them. + const LEAD: usize = 320; + const TAIL: usize = 768; + /// The longest a command buffer, or the spares' count, is waited for. const WAIT: Duration = Duration::from_secs(30); @@ -399,16 +405,28 @@ mod device { /// Commit a command buffer of `queue` of `device` of `encoders` blit encoders, each filling /// `target`, and wait for it, then for the frees its pool's give-back posted to the device's /// free thread, so that the next command buffer takes the pool again. - fn fills(device: &Device, queue: &CommandQueue, target: &Buffer, encoders: usize) { + fn fills( + device: &Device, + queue: &CommandQueue, + target: &Buffer, + encoders: usize, + ) -> CommandBufferStatus { + fills_of(device, queue, &vec![target; encoders]) + } + + /// [`fills`] of one blit encoder for each of `targets`, filling its first 256 bytes; the + /// command buffer's status once it completed or failed. + fn fills_of(device: &Device, queue: &CommandQueue, targets: &[&Buffer]) -> CommandBufferStatus { let command_buffer = queue.command_buffer().unwrap(); - for at in 0..encoders { + for (at, target) in targets.iter().enumerate() { let mut blit = command_buffer.blit_command_encoder().unwrap(); - blit.fill_buffer(target, 0..4096, at as u8).unwrap(); + blit.fill_buffer(target, 0..256, at as u8).unwrap(); blit.end_encoding().unwrap(); } command_buffer.commit().unwrap(); command_buffer.wait_until_completed_for(WAIT).unwrap(); device.shared().frees.drain(); + command_buffer.status() } /// The command buffers the device's spare command pools hold once `done` holds of it, or @@ -466,4 +484,62 @@ mod device { drop((target, queue, device)); let _ = std::fs::remove_dir_all(&scratch); } + + /// The kept barriers a burst's encoders came after (`command_buffer/kept_barriers.rs`) are + /// submitted again, and complete, once the pool's recent uses no longer reach the burst and + /// its command buffers were freed. Each of the burst's middle [`KEPT`] encoders fills one + /// buffer after a barrier, so a kept command buffer comes before each, and the encoders + /// before and after them fill buffers of their own, with no barrier, so the command buffers + /// those barriers came before are neither the pool's first nor its last. On ANV, which names + /// in each submission of a kept command buffer every command buffer that ever came next after + /// it, those submissions failed and the device was lost where the pool was trimmed after the + /// frees (`RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission`). + #[test] + fn kept_barriers_run_again_after_the_command_buffers_after_them_were_freed() { + let scratch = std::env::temp_dir().join(format!("m2v-spares-trims-{}", std::process::id())); + std::fs::create_dir_all(&scratch).unwrap(); + let device = device(&scratch); + let queue = device.new_command_queue().unwrap(); + let options = ResourceOptions::private(); + let shared = device.new_buffer(256, options).unwrap(); + let own: Vec = (0..LEAD + TAIL) + .map(|_| device.new_buffer(256, options).unwrap()) + .collect(); + let (lead, tail) = own.split_at(LEAD); + let burst: Vec<&Buffer> = lead + .iter() + .chain(std::iter::repeat_n(&shared, KEPT)) + .chain(tail) + .collect(); + let mut statuses = vec![fills(&device, &queue, &shared, 1)]; + statuses.push(fills_of(&device, &queue, &burst)); + // The burst's use leaves the pool's recent uses after as many more, and the give-back + // then frees what it made. + for _ in 0..=RECENT_USES { + statuses.push(fills(&device, &queue, &shared, 2)); + } + let freed = device.shared().spares.freed_on().len(); + // The kept barriers taken again, before command buffers the pool makes anew past the + // two it kept. + for _ in 0..4 { + statuses.push(fills(&device, &queue, &shared, KEPT)); + } + let failed = statuses + .iter() + .filter(|status| **status != CommandBufferStatus::Completed) + .count(); + let recoveries = device.work_counts().device_recoveries; + println!( + "SPARES-TRIMS {}: trims {}; {freed} frees ran; {failed} of {} command buffers not \ + completed ({statuses:?}); {recoveries} recoveries", + device.name(), + device.shared().spares.trims(), + statuses.len() + ); + assert!(freed > 0, "the burst's command buffers were never freed"); + assert_eq!(failed, 0, "command buffers did not complete: {statuses:?}"); + assert_eq!(recoveries, 0, "the device recovered from a loss"); + drop((own, shared, queue, device)); + let _ = std::fs::remove_dir_all(&scratch); + } } diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index ee458e1f9..db82ec592 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -1093,6 +1093,13 @@ pub enum RuntimeDriverDefect { /// begins at plane 1. Nothing is refused: the runtime resolves into a scratch image of the /// pass's layers, copied into the planes the resolve belongs in after the pass. VolumeResolveFirstPlane, + /// A command buffer submitted again as it was recorded, once its earlier submissions + /// completed, fails that submission with `VK_ERROR_DEVICE_LOST`, and the device is lost, once + /// a command buffer that came next after it in one of those submissions' `pCommandBuffers` + /// was freed and its command pool trimmed (`vkTrimCommandPool`). Nothing is refused: the + /// runtime frees command buffers without trimming their pools there, and the driver keeps + /// what it holds of them for the pools' later command buffers. + TrimmedCommandBufferFailsResubmission, } /// One device capability a refusal can name. diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index b3edeb6aa..044a2fd11 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -14023,6 +14023,7 @@ variant metal2vulkan::error::RuntimeDriverDefect::PushedDescriptorsStaleAfterPip variant metal2vulkan::error::RuntimeDriverDefect::ReadsCommandBuffersAfterTheirSignal ReadsCommandBuffersAfterTheirSignal variant metal2vulkan::error::RuntimeDriverDefect::SetLayoutSupportUnderstated SetLayoutSupportUnderstated variant metal2vulkan::error::RuntimeDriverDefect::TenBitCodesReadAsWords TenBitCodesReadAsWords +variant metal2vulkan::error::RuntimeDriverDefect::TrimmedCommandBufferFailsResubmission TrimmedCommandBufferFailsResubmission variant metal2vulkan::error::RuntimeDriverDefect::TwoPlaneChromaMisplaced TwoPlaneChromaMisplaced variant metal2vulkan::error::RuntimeDriverDefect::UnpinnablePagesBreakHostMemory UnpinnablePagesBreakHostMemory variant metal2vulkan::error::RuntimeDriverDefect::VolumeBlitsUnfiltered VolumeBlitsUnfiltered