diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 3b13ced11..e84f90e4d 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -318,6 +318,11 @@ pub(super) struct CommandBufferShared { /// where they are every one the pool handed out and it completed, it gives the pool back /// with none recording (`spares.rs`). raws_ended: AtomicU64, + /// The draws its recordings recorded into its pools' `VkCommandBuffer`s, with the state + /// commands they set, its host steps' among them ([`CommandBuffer::recorded`]): where they + /// reach `spares::RECORDED`, its pools free every command buffer they hold as it gives them + /// back (`spares.rs`). + recorded: AtomicU64, /// Its kernel times, apart from the state, which the scheduler holds while it records and /// submits a batch: a read waits for neither (`gpu_time.rs`). kernel: KernelTimes, @@ -2271,8 +2276,11 @@ impl Drop for CommandBufferShared { // A turn of a texture's faces its pass made whose part no submission ran: the next batch // that names the face turned to takes the copy (`texture/faces.rs`). shared.face_swaps.ran_nothing(self.address()); + let recorded = self.recorded.load(Ordering::Relaxed); for pool in pool { - shared.spares.give_command_pool(shared, pool, false); + shared + .spares + .give_command_pool(shared, pool, false, recorded); } } } @@ -2420,6 +2428,7 @@ impl CommandBuffer { at_completion: Mutex::new(Vec::new()), unnoted: AtomicBool::new(false), raws_ended: AtomicU64::new(0), + recorded: AtomicU64::new(0), kernel: KernelTimes::default(), status: AtomicU8::new(status_word(CommandBufferStatus::NotEnqueued)), error: OnceLock::new(), @@ -2622,8 +2631,11 @@ impl CommandBuffer { let pools = self.state().pools(); let shared = self.0.device.shared(); let held = !pools.is_empty(); + let recorded = self.0.recorded.load(Ordering::Relaxed); for pool in pools { - shared.spares.give_command_pool(shared, pool, false); + shared + .spares + .give_command_pool(shared, pool, false, recorded); } held } @@ -2859,6 +2871,15 @@ impl CommandBuffer { unsafe { self.0.end_raw(raw) } } + /// `commands` more recorded into its pools' `VkCommandBuffer`s: draws, a rate-mapped pass's + /// region by region, and the state commands they set (`render.rs`). What a command buffer's + /// recording takes of its driver's device-wide pools stays taken until it is begun again, + /// reset or freed, so its pools free their command buffers as they go back where these + /// reach `spares::RECORDED` (`spares.rs`). + pub(super) fn recorded(&self, commands: u64) { + self.0.recorded.fetch_add(commands, Ordering::Relaxed); + } + /// Give up `raw`, a secondary command buffer recording that nothing will execute (a render /// pass instance its pass replaced or gave up before running it, or the one instance of a /// pass that changes nothing): it ends ([`end_raw`](Self::end_raw)), so its pool goes back @@ -5905,8 +5926,11 @@ impl CommandBufferShared { && u64::try_from(handed).is_ok_and(|handed| handed == ended); settled_pool = settled.then_some(first.raw); let shared = self.device.shared(); + let recorded = self.recorded.load(Ordering::Relaxed); for pool in pools { - shared.spares.give_command_pool(shared, pool, settled); + shared + .spares + .give_command_pool(shared, pool, settled, recorded); } } state.unplaced(); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs index d34e75e57..f1ffc43d6 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/rerun.rs @@ -536,7 +536,10 @@ fn run_again(check: &LoopCheck, buffer: Hold) { .into_inner() .unwrap_or_else(|poisoned| poisoned.into_inner()); let shared = device.shared(); - shared.spares.give_command_pool(shared, pool, settled); + let recorded = buffer.recorded.load(Ordering::Relaxed); + shared + .spares + .give_command_pool(shared, pool, settled, recorded); } } *lock(&check.rounds) = Rounds::Ended; diff --git a/crates/metal2vulkan-runtime/src/kept_commands.rs b/crates/metal2vulkan-runtime/src/kept_commands.rs index 757f09f22..9266f8f40 100644 --- a/crates/metal2vulkan-runtime/src/kept_commands.rs +++ b/crates/metal2vulkan-runtime/src/kept_commands.rs @@ -163,7 +163,8 @@ impl Drop for KeptContext { let pool = lock(&self.pool).take(); if let Some(pool) = pool { let shared = self.device.shared(); - shared.spares.give_command_pool(shared, pool, false); + // Its chunks' draws count among those of the command buffer that recorded them. + shared.spares.give_command_pool(shared, pool, false, 0); } lock(&self.descriptors).give_back(); } diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index a0bdc0cc8..3af4384b2 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -10750,6 +10750,9 @@ impl RenderLowering { }; let mut owned = Vec::new(); let mut states_recorded = Recorded::default(); + // The Vulkan draws it records, now or once its pipeline is made: its command + // buffer's count of what its recordings hold (`CommandBuffer::recorded`). + let mut draws_recorded = 0u64; // A draw read through snapshots records its recordings twice: every snapshot draw, // then every drawing draw (`render/snapshot.rs`); one read in place, once. let phases: &[Option] = match &pair_base { @@ -10812,6 +10815,7 @@ impl RenderLowering { let (push, vk_draws) = entry(a); for state in draw_states.of(a) { for &(index, indirect, draw) in vk_draws { + draws_recorded += 1; if indirect.is_some() && phase != Some(snapshot::Phase::Snapshot) && matches!( @@ -10913,6 +10917,7 @@ impl RenderLowering { } draw_alone = states_recorded.draw_alone(); states_recorded.count(self.core.counts()); + (self.core.command_buffer()).recorded(draws_recorded + states_recorded.states); if let Some((making, state, draws, query)) = split { // The record's times: the pipeline's, then those of the other `VkPipeline`s the // draw records, made at the draw, set once the making made it. Every copy of the diff --git a/crates/metal2vulkan-runtime/src/spares.rs b/crates/metal2vulkan-runtime/src/spares.rs index f940e4f44..cc1236b8b 100644 --- a/crates/metal2vulkan-runtime/src/spares.rs +++ b/crates/metal2vulkan-runtime/src/spares.rs @@ -91,6 +91,23 @@ //! of one dispatch each added 378 MiB, the spares holding 4,000 command buffers of about 96 KiB //! each, which went as those pools sat idle past [`IDLE_FOR`], 15.1 MiB over the start left //! after 17 s. +//! - **A command buffer that recorded much frees every command buffer of its pools.** A +//! recording holds what its commands took of the driver's device-wide pools until its command +//! buffer is begun again, reset or freed, and a pool kept as a spare keeps its command buffers' +//! recordings for its next takers' begins. ANV (Mesa 26.2.6, an Iris Xe) takes each draw's +//! changed viewport and scissor state from a device-wide dynamic state pool of 1 GiB, and a +//! rate-mapped pass records each draw once per region of its map, each with its own viewport +//! and scissor (`rate_mapped_pass.rs`): a guest's passes of an indirect command buffer's draws +//! over a map, which its host steps replayed at about 880,000 draws a step, filled that pool +//! with four command buffers alive, one of them holding 97.5 MiB of it; ANV then wrote through +//! a null state inside `vkCmdDrawIndexed`, and the process faulted. A command buffer counts +//! the draws its recordings recorded, its host steps' included, with the state commands they +//! set (`CommandBuffer::recorded`); where they reach +//! [`RECORDED`], each pool it gives back frees every command buffer it holds, on the device's +//! free thread, as a spare left idle does, and goes back among the spares as the newest, stocked +//! with a secondary. Below [`RECORDED`] a pool keeps its command buffers, as above. Counted: +//! `WorkCounts::spare_command_buffers_freed_past_recorded`. A command buffer whose own +//! recordings fill the driver's pool is a known gap (docs/FAST-PATHS.md). //! - **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 @@ -256,6 +273,11 @@ pub(super) const FREED_AT_ONCE: usize = 32; /// command buffers with recordings a device on ANV below Xe-HP holds at once (the module docs). pub(super) const HELD: usize = 4096; +/// The commands (draws and the state commands they set) past which a command buffer's pools free +/// every command buffer they hold as it gives them back, with what their recordings took of the +/// driver's device-wide pools (the module docs). +pub(super) const RECORDED: u64 = 1 << 16; + /// The command buffers a command buffer hands out of its first pool alone, making those it lacks /// there; past them, its pools out of one of a level, it takes a spare holding the most of that /// level (the module docs). @@ -284,6 +306,9 @@ pub(super) struct Churn { pub(super) past_held: u64, /// Freed by a spare left idle or shed past [`HELD`] ([`CommandPool::shed`]). pub(super) shed: u64, + /// Freed from a pool given back by a command buffer that recorded [`RECORDED`] commands or + /// more ([`Spares::give_command_pool`]). + pub(super) past_recorded: u64, } /// A command pool and the command buffers made from it, by level: those a command buffer handed @@ -731,8 +756,10 @@ impl Spares { /// Keep `pool` of `device`, of a command buffer whose work ended or that was never /// submitted: nothing of it is pending, and nothing else holds it; `settled` where the /// command buffer completed and ended every command buffer of it handed out, so none is - /// recording (the module docs). A pool that made no secondary command buffer makes one. Where - /// it holds command buffers past its recent uses, those are freed; the oldest spare no + /// recording (the module docs); `recorded` the commands that command buffer recorded + /// (`CommandBuffer::recorded`). A pool that made no secondary command buffer makes one. Where + /// it holds command buffers past its recent uses, those are freed, and every one it holds + /// where `recorded` reaches [`RECORDED`]; the oldest spare no /// command buffer took for [`IDLE_FOR`] frees all of its own ([`take_idle`]); and past /// [`HELD`] command buffers in the spares and the pool together, the oldest spares free all /// of theirs, and the pool those past it ([`past_held`]); each pool out of the spares until @@ -742,6 +769,7 @@ impl Spares { device: &DeviceShared, mut pool: CommandPool, settled: bool, + recorded: u64, ) { // The audit reads the device's timelines inside a section of the exit guard, on // whatever thread gives the pool back. @@ -754,8 +782,16 @@ impl Spares { pool.recording = !settled; let mut past = pool.given_back(now); let recent = past.len(); + // A use that recorded much frees every command buffer the pool holds, with what their + // recordings took of the driver's pools. + let heavy = match recorded >= RECORDED { + true => pool.shed(), + false => Vec::new(), + }; + let weighed = heavy.len(); + past.extend(heavy); pool.stock(device); - let mut freed = [recent, 0, 0]; + let mut freed = [recent, 0, 0, weighed]; let (given, shed) = { let mut pools = lock(&self.command_pools); pools.came_back(&mut pool); @@ -768,6 +804,7 @@ impl Spares { let mut churn = lock(&self.churn); churn.past_recent_uses += recent as u64; churn.past_held += held.len() as u64; + churn.past_recorded += weighed as u64; } past.extend(held); let given = match past.is_empty() { diff --git a/crates/metal2vulkan-runtime/src/tests/spares.rs b/crates/metal2vulkan-runtime/src/tests/spares.rs index 7e93c2fec..4d8a88faa 100644 --- a/crates/metal2vulkan-runtime/src/tests/spares.rs +++ b/crates/metal2vulkan-runtime/src/tests/spares.rs @@ -648,10 +648,16 @@ mod device { use super::{HELD, RECENT_FOR, RECENT_USES}; use crate::command_buffer::kept_barriers::KEPT; use crate::free_thread::FreeThread; - use crate::spares::{FREED_AT_ONCE, ONE_POOL}; + use crate::spares::{FREED_AT_ONCE, ONE_POOL, RECORDED}; + use crate::tests::encoder_holds::library; use crate::tests::freed_memory::device; - use crate::{Buffer, CommandBufferStatus, CommandQueue, Device, ResourceOptions}; + use crate::{ + Buffer, CommandBufferStatus, CommandQueue, Device, PipelineOptions, RenderPassDescriptor, + RenderPipelineState, ResourceOptions, + }; use ash::vk; + use metal2vulkan::metal::PrimitiveType; + use metal2vulkan::pipeline::{RenderPipelineDescriptor, StageSource}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -1131,4 +1137,108 @@ mod device { drop((own, shared, queue, device)); let _ = std::fs::remove_dir_all(&scratch); } + + /// A command buffer of `queue` of one pass without attachments of `draws` draws of + /// `ob3_index_buffer` (rasterization disabled), each marking `seen`, committed and waited for, + /// then the frees its pools' give-back posted; its status once it completed or failed. + fn drawn( + device: &Device, + queue: &CommandQueue, + state: &RenderPipelineState, + seen: &Buffer, + draws: u64, + ) -> CommandBufferStatus { + let mut pass = RenderPassDescriptor::new(); + pass.render_target_width = 1; + pass.render_target_height = 1; + pass.default_raster_sample_count = 1; + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(state).unwrap(); + encoder.set_vertex_buffer(Some(seen), 0, 0).unwrap(); + for _ in 0..draws { + (encoder.draw_primitives(PrimitiveType::Point, 0, 1, 1, 0)).unwrap(); + } + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + device.shared().frees.drain(); + command_buffer.status() + } + + /// A command buffer that recorded [`RECORDED`] draws and state commands or more frees every + /// command buffer its pools hold as it gives them back, on the device's free thread: what + /// its recordings took of the driver's device-wide pools goes with them, where kept they + /// held it until begun again (ANV's dynamic state pool of 1 GiB, which a rate-mapped pass's + /// region by region draws filled: `spares.rs`). One that recorded fewer keeps them, and the + /// next takes them again. + #[test] + fn a_command_buffer_that_recorded_much_frees_its_pools_command_buffers() { + let scratch = + std::env::temp_dir().join(format!("m2v-spares-recorded-{}", std::process::id())); + std::fs::create_dir_all(&scratch).unwrap(); + let device = device(&scratch); + let queue = device.new_command_queue().unwrap(); + let function = library(&device, "engine/ob3_index_buffer.ll") + .new_function_with_name("ob3_index_buffer") + .unwrap(); + let mut descriptor = + RenderPipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + descriptor.rasterization_enabled = false; + let state = device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + let seen = device.new_buffer(4096, ResourceOptions::private()).unwrap(); + let freed = || { + device + .work_counts() + .spare_command_buffers_freed_past_recorded + }; + // Every command buffer the spares freed, for whatever reason. + let all_freed = || { + let counts = device.work_counts(); + counts.spare_command_buffers_freed_past_recent_uses + + counts.spare_command_buffers_freed_past_held + + counts.spare_command_buffers_shed + + counts.spare_command_buffers_freed_past_recorded + }; + let light = drawn(&device, &queue, &state, &seen, 2); + assert_eq!(light, CommandBufferStatus::Completed); + assert_eq!(freed(), 0, "a command buffer of two draws keeps its pool's"); + let (held, before) = (device.shared().spares.command_buffers_held(), all_freed()); + let heavy = drawn(&device, &queue, &state, &seen, RECORDED); + assert_eq!(heavy, CommandBufferStatus::Completed); + let (after, churn) = ( + device.shared().spares.command_buffers_held(), + device.shared().spares.churn(), + ); + let freed_on = device.shared().spares.freed_on(); + println!( + "SPARES {}: {held} held after two draws, {after} after {RECORDED} draws, which freed \ + {} past their record on {freed_on:?}", + device.name(), + freed(), + ); + assert!( + all_freed() > before, + "a command buffer of {RECORDED} draws freed none of its pool's command buffers" + ); + assert_eq!(all_freed() - before, freed(), "each freed past its record"); + assert_eq!(freed(), churn.past_recorded); + assert!( + freed_on.iter().all(|name| name == FREE_THREAD), + "freed on {freed_on:?}, not on {FREE_THREAD} alone" + ); + // The pool keeps only the secondary a pool given back is stocked with, and the primary + // a settled one begins ahead: no more than the light command buffer's left. + assert!( + after <= held, + "{after} held after the heavy command buffer, {held} before" + ); + let light = drawn(&device, &queue, &state, &seen, 2); + assert_eq!(light, CommandBufferStatus::Completed); + assert_eq!(freed(), churn.past_recorded, "two draws keep their pool's"); + drop((state, seen, queue, device)); + let _ = std::fs::remove_dir_all(&scratch); + } } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index bf3bcbfc2..5056af94b 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -64,9 +64,10 @@ pub(crate) struct Counters { spare_command_pools_taken_past_first: AtomicU64, spare_command_pools_reset: AtomicU64, /// The command buffers the spare command pools freed, by why (`spares.rs`): past a pool's - /// recent uses, past `HELD` of a pool given back, and shed by a spare; then the trims of - /// their pools. - spare_command_buffers_freed: [AtomicU64; 3], + /// recent uses, past `HELD` of a pool given back, shed by a spare, and every one of a pool + /// given back by a command buffer that recorded `RECORDED` commands or more; then the trims + /// of their pools. + spare_command_buffers_freed: [AtomicU64; 4], spare_command_pool_trims: AtomicU64, live_tables_uploaded: AtomicU64, timeline_waits: AtomicU64, @@ -1980,14 +1981,15 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } - /// A pool given back freed `recent` command buffers past its recent uses and `held` past - /// `HELD`, spares shed `shed`, and their pools are trimmed `trims` times (`spares.rs`). + /// A pool given back freed `recent` command buffers past its recent uses, `held` past + /// `HELD` and `recorded` as its command buffer recorded `RECORDED` commands or more, spares + /// shed `shed`, and their pools are trimmed `trims` times (`spares.rs`). pub(crate) fn spare_command_buffers_freed( &self, - [recent, held, shed]: [usize; 3], + [recent, held, shed, recorded]: [usize; 4], trims: usize, ) { - for (count, freed) in [recent, held, shed] + for (count, freed) in [recent, held, shed, recorded] .into_iter() .zip(&self.spare_command_buffers_freed) { @@ -5186,6 +5188,12 @@ pub struct WorkCounts { /// The command buffers spares freed whole: one no command buffer took for 10 s, and the /// oldest ones past the 4096 the spares hold at most (`spares.rs`). pub spare_command_buffers_shed: u64, + /// The command buffers a pool given back freed, every one it held, as the command buffer + /// that gave it back recorded 65,536 draws and state commands or more (`spares.rs`'s + /// `RECORDED`): a rate-mapped pass records each draw once per region of its map, and what a + /// recording took of its driver's device-wide pools stays taken until its command buffer is + /// begun again, reset or freed. + pub spare_command_buffers_freed_past_recorded: u64, /// The `vkTrimCommandPool` calls after those frees, one after each 32 command buffers freed /// at most, which return to the device what its driver kept of them (none on a driver whose /// trim fails the kept barriers, `spares.rs`). @@ -9297,6 +9305,8 @@ impl Device { .load(Ordering::Relaxed), spare_command_buffers_shed: counters.spare_command_buffers_freed[2] .load(Ordering::Relaxed), + spare_command_buffers_freed_past_recorded: counters.spare_command_buffers_freed[3] + .load(Ordering::Relaxed), spare_command_pool_trims: counters.spare_command_pool_trims.load(Ordering::Relaxed), live_tables_uploaded: counters.live_tables_uploaded.load(Ordering::Relaxed), timeline_waits: counters.timeline_waits.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_volume.rs b/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_volume.rs index c9dded244..1d06e3afe 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_volume.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rate_mapped_volume.rs @@ -250,7 +250,7 @@ fn map(device: &Device) -> RasterizationRateMap { fn line(counts: &WorkCounts) -> String { format!( "draw_indexed {} set_viewport {} taken {} freed past recent uses {} past held {} shed {} \ - host steps {}", + host steps {} freed past recorded {}", counts.commands_recorded.cmd_draw_indexed, counts.commands_recorded.cmd_set_viewport, counts.spare_command_pools_taken, @@ -258,6 +258,7 @@ fn line(counts: &WorkCounts) -> String { counts.spare_command_buffers_freed_past_held, counts.spare_command_buffers_shed, counts.host_steps_recorded, + counts.spare_command_buffers_freed_past_recorded, ) } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 039c0df84..aa1ce6082 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -3397,6 +3397,7 @@ field metal2vulkan-runtime::WorkCounts.slot_wait_nanos pub slot_wait_nanos: u64 field metal2vulkan-runtime::WorkCounts.slot_waits pub slot_waits: u64 field metal2vulkan-runtime::WorkCounts.snapshot_inline_splits pub snapshot_inline_splits: u64 field metal2vulkan-runtime::WorkCounts.spare_command_buffers_freed_past_held pub spare_command_buffers_freed_past_held: u64 +field metal2vulkan-runtime::WorkCounts.spare_command_buffers_freed_past_recorded pub spare_command_buffers_freed_past_recorded: u64 field metal2vulkan-runtime::WorkCounts.spare_command_buffers_freed_past_recent_uses pub spare_command_buffers_freed_past_recent_uses: u64 field metal2vulkan-runtime::WorkCounts.spare_command_buffers_shed pub spare_command_buffers_shed: u64 field metal2vulkan-runtime::WorkCounts.spare_command_pool_trims pub spare_command_pool_trims: u64 diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index c0bcce69b..95eacec11 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -558,6 +558,14 @@ driver's. Each is open work. command buffer submitted before that completion, read the writes, which Metal drops. - **A `synchronize_resource` of a two-copy buffer encoded before a rebind copies to the pages the buffer lay in when it was encoded** (`managed_copy.rs`), not to the new ones. +- **On ANV, command buffers whose own recordings fill the driver's dynamic state pool crash the + process inside the driver** (`spares.rs`). A rate-mapped pass records each draw once per region + of its map, each with its own viewport and scissor, and ANV (Mesa 26.2.6, an Iris Xe) takes + that state from a device-wide pool of 1 GiB: one command buffer of a guest's replayed passes + held 97.5 MiB of it. Command buffers alive together that record about ten times that, one + alone included, fill it, and ANV then writes through a null state inside `vkCmdDraw*` instead + of failing the command buffer. What spare pools keep of such recordings is freed as they go + back (`RECORDED`); what command buffers alive at once record is not bounded. - **A heap texture Metal keeps uncompressed lies in its driver's layout, not Metal's tiles, where its image fits the heap's answer in the heap's memory** (`texture/heap.rs`,