diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index d82ccd9f4..9e1944ddc 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -2403,6 +2403,20 @@ impl CommandBuffer { self.state().uploads.bytes() } + /// Give its command pool back to the device's spares now, whatever its work's state, as a + /// command buffer that never completed would: a device test's deliberate early give-back, + /// which the device's pending audit finds (`tests::pending_audit_device`). Whether it held + /// one. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn give_pool_back_early(&self) -> bool { + let Some(pool) = self.state().pool.take() else { + return false; + }; + let shared = self.0.device.shared(); + shared.spares.give_command_pool(shared, pool, false); + true + } + /// Whether `waiting` holds this command buffer. pub(crate) fn is(&self, waiting: &dyn Waiting) -> bool { self.0.address() == waiting.address() diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index 54fbca7bd..206d46dfa 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -1069,6 +1069,12 @@ impl CommandBufferShared { && !first_work.has_first() && !first_work.has_staged() && images.is_empty(); + // What the batch's submission carries, to its value, from here: the device's pending + // audit's (`pending_audit.rs`), where it is on. + let carried = (shared.queues[queue].timeline, at.value); + if let Some(audit) = raw.pending_audit() { + audit.submitted(raw, carried, &[work.as_slice(), finale.as_slice()]); + } if grouped { scheduler.group.open(queue, &scheduler.waited[queue]); } else { @@ -1101,6 +1107,9 @@ impl CommandBufferShared { .group .submit(device, &mut scheduler.waited[queue], Some(after)); if let Err(error) = submitted { + if let Some(audit) = raw.pending_audit() { + audit.withdrawn(carried, &[work.as_slice(), finale.as_slice()]); + } if let Some(fence) = fence { // SAFETY: the failed submission is not pending; inside the section. // Released, not kept: Vulkan leaves a fence's state after a failed diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index 44b15f3e1..8f4100134 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -353,6 +353,8 @@ impl Device { pipeline_records: raw.pipeline_records, fail_in_place_check: false, assume_submissions_merge: false, + // On where `METAL2VULKAN_PENDING_AUDIT` is set (`assemble`). + pending_audit: false, announce_each: raw.announce_each, lowering_refuses: raw.lowering_refuses, view_reinterpretation, diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index cd524e429..9ee985c0e 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -211,6 +211,14 @@ pub struct DeviceOptions { /// grouped path on every run. No Metal counterpart. #[doc(hidden)] pub assume_submissions_merge: bool, + /// Turn each device's pending audit on: a diagnostic that checks, at each begin of a + /// `VkCommandBuffer`, reset or give-back of its pool and submission of it again, that the + /// GPU completed every submission that carries it, and logs each one that did not (id name + /// `metal2vulkan-pending-audit`, `pending_audit.rs`); it changes no work. Off by default; + /// `METAL2VULKAN_PENDING_AUDIT`, set, turns it on for every device too. For the tests that + /// hold it to a finding. No Metal counterpart. + #[doc(hidden)] + pub pending_audit: bool, /// Color formats each device takes as no color attachment, as a device without the /// attachment feature of them does: their tilings' `COLOR_ATTACHMENT` and blend features and /// their attachment sample counts are left out of the description the device plans and @@ -317,6 +325,7 @@ impl std::fmt::Debug for DeviceOptions { record_executions, fail_in_place_check, assume_submissions_merge, + pending_audit, withheld_attachment_formats, pipeline_records, extra_queues, @@ -348,6 +357,7 @@ impl std::fmt::Debug for DeviceOptions { .field("record_executions", record_executions) .field("fail_in_place_check", fail_in_place_check) .field("assume_submissions_merge", assume_submissions_merge) + .field("pending_audit", pending_audit) .field("withheld_attachment_formats", withheld_attachment_formats) .field( "pipeline_records", @@ -1913,6 +1923,7 @@ pub(super) fn create_on( pipeline_records: options.pipeline_records.clone(), fail_in_place_check: options.fail_in_place_check, assume_submissions_merge: options.assume_submissions_merge, + pending_audit: options.pending_audit, view_reinterpretation, generated_commands, host_image_copy, @@ -2076,6 +2087,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { record_executions, fail_in_place_check, assume_submissions_merge, + pending_audit, withheld_attachment_formats, pipeline_records: _, extra_queues, @@ -2102,6 +2114,7 @@ fn same_options(a: &DeviceOptions, b: &DeviceOptions) -> bool { && *record_executions == b.record_executions && *fail_in_place_check == b.fail_in_place_check && *assume_submissions_merge == b.assume_submissions_merge + && *pending_audit == b.pending_audit && *withheld_attachment_formats == b.withheld_attachment_formats && *extra_queues == b.extra_queues && *reserved_queues == b.reserved_queues diff --git a/crates/metal2vulkan-runtime/src/device/functions.rs b/crates/metal2vulkan-runtime/src/device/functions.rs index 3008d6604..a81fd79a0 100644 --- a/crates/metal2vulkan-runtime/src/device/functions.rs +++ b/crates/metal2vulkan-runtime/src/device/functions.rs @@ -12,7 +12,10 @@ //! their destination (`tracker::Barrier::record`, `image_barrier::MemoryReads`), the push //! command where the device has it (`binding::push_descriptor_command`), and //! `vkSetDebugUtilsObjectNameEXT` where its instance reports messages (`pipeline/graphics.rs`). -//! Its copy commands count each place in the runtime that records them ([`CopySites`]). +//! Its copy commands count each place in the runtime that records them ([`CopySites`]). Where the +//! device's pending audit is on (`pending_audit.rs`), its `vkBeginCommandBuffer` checks the command +//! buffer first and its `vkCmdExecuteCommands` notes the secondaries each primary executes: both +//! tables hold the audit, so every begin and execution made through them reaches it. //! //! Each `vkCmdCopyBuffer` region over [`SPLIT_ABOVE`] bytes whose size is no multiple of //! [`SPLIT_UNIT`] is recorded as two regions of the same command: its bytes up to the last whole @@ -32,6 +35,7 @@ use crate::exit_guard::{self, Call}; use crate::image_barrier::MemoryReads; +use crate::pending_audit::PendingAudit; use crate::recorder::Slot; use crate::work_counts::{CopySite, CopySites, COPY_SITES}; use ash::vk; @@ -74,7 +78,8 @@ fn split(region: &vk::BufferCopy) -> Option<[vk::BufferCopy; 2]> { /// A device's functions as the runtime records commands with them: the `ash::Device`, the reads /// a global memory barrier recorded into a command buffer of the device's queue family for /// encoders names in place of `MEMORY_READ`, the push command and the naming of an object, and -/// the places that recorded its copy commands (the module docs). +/// the places that recorded its copy commands, and the device's pending audit where it is on (the +/// module docs). #[derive(Clone)] pub(crate) struct Vk { device: ash::Device, @@ -82,19 +87,22 @@ pub(crate) struct Vk { push_descriptor: Option, object_name: Option, copies: Arc, + audit: Option>, } impl Vk { /// `device`'s functions, whose global memory barriers name `reads`, with `push_descriptor`, /// its push command where it has one, and `object_name`, its naming of an object where its - /// instance reports messages, whose copy commands count their places in `copies`: for the - /// work the runtime records before the device's functions are made (`prime.rs`). + /// instance reports messages, whose copy commands count their places in `copies`, auditing + /// with `audit` where given: for the work the runtime records before the device's functions + /// are made (`prime.rs`), with none. pub(super) fn new( device: ash::Device, reads: MemoryReads, push_descriptor: Option, object_name: Option, copies: Arc, + audit: Option>, ) -> Vk { Vk { device, @@ -102,6 +110,50 @@ impl Vk { push_descriptor, object_name, copies, + audit, + } + } + + /// The device's pending audit, where it is on (`pending_audit.rs`). + pub(crate) fn pending_audit(&self) -> Option<&PendingAudit> { + self.audit.as_deref() + } + + /// `vkBeginCommandBuffer`, the command buffer checked first by the device's pending audit + /// where it is on (the module docs). + /// + /// # Safety + /// + /// As `ash::Device::begin_command_buffer`'s. + pub(crate) unsafe fn begin_command_buffer( + &self, + command_buffer: vk::CommandBuffer, + begin_info: &vk::CommandBufferBeginInfo<'_>, + ) -> ash::prelude::VkResult<()> { + if let Some(audit) = &self.audit { + audit.begins(&self.device, command_buffer, begin_info.flags); + } + // SAFETY: the caller's contract. + unsafe { (self.device).begin_command_buffer(command_buffer, begin_info) } + } + + /// `vkCmdExecuteCommands`, noted by the device's pending audit where it is on (the module + /// docs). + /// + /// # Safety + /// + /// As `ash::Device::cmd_execute_commands`'s. + pub(crate) unsafe fn cmd_execute_commands( + &self, + primary_command_buffer: vk::CommandBuffer, + secondary_command_buffers: &[vk::CommandBuffer], + ) { + if let Some(audit) = &self.audit { + audit.executes(primary_command_buffer, secondary_command_buffers); + } + // SAFETY: the caller's contract. + unsafe { + (self.device).cmd_execute_commands(primary_command_buffer, secondary_command_buffers); } } @@ -268,7 +320,8 @@ impl Functions { /// The functions of `all`'s device, made from `instance`, whose global memory barriers name /// `reads`, with `push_descriptor`, its push command where it has one, and `object_name`, its /// naming of an object where its instance reports messages, whose commands go through - /// `recording`, its slot where it has one (`recorder`). + /// `recording`, its slot where it has one (`recorder`), auditing with `audit` where given + /// (`pending_audit.rs`). /// /// # Safety /// @@ -282,6 +335,7 @@ impl Functions { push_descriptor: Option, object_name: Option, recording: Option<&Slot>, + audit: Option>, ) -> Functions { let handle = all.handle(); let get = instance.fp_v1_0().get_device_proc_addr; @@ -327,8 +381,16 @@ impl Functions { push_descriptor, object_name, Arc::clone(&copies), + audit.clone(), + ), + sectioned: Vk::new( + sectioned, + reads, + push_descriptor, + object_name, + copies, + audit, ), - sectioned: Vk::new(sectioned, reads, push_descriptor, object_name, copies), entry_points, } } @@ -338,6 +400,11 @@ impl Functions { &self.entry_points } + /// The device's pending audit, where it is on, which both tables hold (the module docs). + pub(crate) fn pending_audit(&self) -> Option<&PendingAudit> { + self.all.pending_audit() + } + /// The device's functions for this thread now (see the module). pub(crate) fn get(&self) -> &Vk { exit_guard::check(); diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 4048d4181..25b44cd9d 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -70,6 +70,7 @@ use super::memory::Memory; use super::memory_log::MemoryLog; use super::mipmap_scratch::MipmapScratch; use super::owned_kernel::OwnedKernels; +use super::pending_audit::PendingAudit; use super::recycle::{self, BufferMaking, Recycler}; use super::released_programs::Keepers; use super::render_state::DepthRanges; @@ -728,6 +729,12 @@ impl DeviceShared { self.functions.get() } + /// The device's pending audit, where it is on (`pending_audit.rs`): read with no call of the + /// device's, on any thread; its checks read the device's timelines through [`vk`](Self::vk). + pub(crate) fn pending_audit(&self) -> Option<&PendingAudit> { + self.functions.pending_audit() + } + /// Nanoseconds the device's pipeline makings spent inside its driver, graphics then compute /// (`compiles.rs`, `WorkCounts::render_pipeline_create_nanos` and /// `compute_pipeline_create_nanos`). @@ -1564,6 +1571,9 @@ pub(super) struct Parts { /// Its submission check of merged submissions holds without its answer /// (`DeviceOptions::assume_submissions_merge`). pub(super) assume_submissions_merge: bool, + /// Its pending audit is on (`DeviceOptions::pending_audit`; `pending_audit.rs`), as it is + /// where `METAL2VULKAN_PENDING_AUDIT` is set. + pub(super) pending_audit: bool, /// Its views may reinterpret an image's components ([`DeviceShared`]'s field), outside /// `enabled`'s vocabulary. pub(super) view_reinterpretation: bool, @@ -1665,6 +1675,7 @@ impl Device { pipeline_records, fail_in_place_check, assume_submissions_merge, + pending_audit, view_reinterpretation, generated_commands, host_image_copy, @@ -1992,6 +2003,7 @@ impl Device { push_descriptor, object_name, Default::default(), + None, ), &loader_word, queue_family, @@ -2250,6 +2262,7 @@ impl Device { push_descriptor, object_name, recording.as_ref(), + PendingAudit::new(pending_audit, instance.sink()), ) }) }; diff --git a/crates/metal2vulkan-runtime/src/device/staging.rs b/crates/metal2vulkan-runtime/src/device/staging.rs index 59208b14d..d4f30c7e0 100644 --- a/crates/metal2vulkan-runtime/src/device/staging.rs +++ b/crates/metal2vulkan-runtime/src/device/staging.rs @@ -242,6 +242,12 @@ impl StagingLock<'_> { .command_buffers(&buffers) .signal_semaphores(&signal_semaphores) .push_next(&mut timeline); + // What the submission carries, to its value: the device's pending audit's + // (`pending_audit.rs`), where it is on. + let carried = (made.timeline, value); + if let Some(audit) = raw.pending_audit() { + audit.submitted(raw, carried, &[&buffers[..]]); + } // SAFETY: the queue is used under the staging lock alone; the command buffer is // executable; every value waited for was signalled (the host saw it); the signal of the // timeline is above its value. @@ -253,6 +259,9 @@ impl StagingLock<'_> { }; shared.queue_quiet.ended(); exit_guard::called(Call::QueueSubmit); + if let (Err(_), Some(audit)) = (&submitted, raw.pending_audit()) { + audit.withdrawn(carried, &[&buffers[..]]); + } submitted.map_err(|error| device.failed(error))?; made.signalled = value; made.buffers[at].1 = value; diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index 9e64f8366..edecd4054 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -344,6 +344,12 @@ impl Device { // The first work waits as the work's does (a heap's fill another queue did comes before // a move of an image placed in it). let submits = [submit]; + // What the submission carries, to its value: the device's pending audit's + // (`pending_audit.rs`), where it is on. + let carried = (objects.timeline, value); + if let Some(audit) = raw.pending_audit() { + audit.submitted(raw, carried, &[&buffers[..]]); + } // Where freed memory waits for the work in flight, it waits for this until it completed // (`freed_memory.rs`). let _own = (shared.parking.get()).map(|parking| parking.own_submission(self)); @@ -375,6 +381,9 @@ impl Device { // A `vkQueueSubmit` that fails leaves what its submissions reference as it was, or loses // the device: the work goes back as `taken` drops. if let Err(error) = made { + if let Some(audit) = raw.pending_audit() { + audit.withdrawn(carried, &[&buffers[..]]); + } shared.loader_word.end_step(word, mark); return Err(self.failed(error)); } diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 6a6615804..c09105a61 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -175,6 +175,7 @@ mod neutral; mod noted_apart; mod owned_kernel; mod pass_runs; +mod pending_audit; mod pending_dispatch; mod pipeline; mod pixel_format_info; diff --git a/crates/metal2vulkan-runtime/src/pending_audit.rs b/crates/metal2vulkan-runtime/src/pending_audit.rs new file mode 100644 index 000000000..6c3541334 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/pending_audit.rs @@ -0,0 +1,420 @@ +//! The pending audit: a default-off diagnostic, `METAL2VULKAN_PENDING_AUDIT` +//! (`metal2vulkan::env_vars`) or `DeviceOptions::pending_audit`, that checks, each time the runtime +//! frees or reuses what a `VkCommandBuffer` recorded, that the GPU completed every submission that +//! carries it, against the GPU's own timelines rather than what the host saw of them. +//! +//! - **What it checks** ([`Freeing`]). Each `vkBeginCommandBuffer` the device's functions make +//! (`device/functions.rs`: every begin of the runtime's, a primary begun ahead in a spare pool +//! among them, `spares.rs`), which resets the command buffer; each `vkResetCommandPool` of a spare +//! command pool, and each command pool given back to the device's spares, for every command +//! buffer the pool made (`Spares::command_pool`, `Spares::give_command_pool`); and each +//! submission of a command buffer that was submitted before, unless it was begun for +//! simultaneous use (ANV rewrites a chainable primary's last jump at each submission: Mesa, +//! `anv_cmd_buffer_record_chain_submit`). ANV frees a command buffer's batch, dynamic and surface +//! state, back to the device's pools, as it is reset (Mesa, `anv_cmd_buffer_reset`). +//! - **What carries a command buffer.** A batch's submission, from the moment the batch goes to its +//! `VkQueue` or waits in the scheduler's group (`command_buffer/submit.rs`), to the queue's +//! timeline value it signals; a secondary command buffer through each primary that executes it +//! (each `vkCmdExecuteCommands` since that primary's last begin); the device's own submissions +//! and the staging queue's, to their own timelines (`device/submit.rs`, `device/staging.rs`). A +//! submission that fails is withdrawn. Other submissions carry nothing (the predicated loop's +//! runs again, at fences, `command_buffer/rerun.rs`; the device's checks as it is made). +//! - **The answer is the GPU's.** At each check it reads each carrying timeline +//! (`vkGetSemaphoreCounterValue`): a value not reached means the GPU may still run that +//! submission. A read that fails (a lost device) finds nothing. A command buffer whose carrying +//! submissions all completed leaves the ledger. +//! - **What it prints.** One line as the device is made, and one per finding, through the +//! device's message sink at `Info` severity (id name `metal2vulkan-pending-audit`), else on +//! stderr: what was done, the thread, the command buffer, the timeline semaphore, its counter and +//! the value the submission signals, and for the first [`BACKTRACES`] findings the thread's +//! backtrace. As the device goes, the checks made and the findings, by kind. +//! - **It changes nothing.** It reads counters and logs: every begin, reset, give-back and +//! submission goes on as it would without it. +//! - **What it costs on.** A lock of the ledger at each begin, execution of secondaries, pool +//! reset, pool given back and submission; a map entry per command buffer per submission until a +//! check finds the submission completed; one `vkGetSemaphoreCounterValue` per carrying timeline +//! at each check of a command buffer the ledger holds; a backtrace for each of the first +//! [`BACKTRACES`] findings. Off, one test of an `Option` at each of those places. + +use crate::device::lock; +use crate::driver_facts::inform_through; +use crate::exit_guard::{self, Call}; +use crate::MessageSink; +use ash::vk::{self, Handle}; +use std::backtrace::Backtrace; +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; + +/// The id name of the audit's messages. +const ID_NAME: &str = "metal2vulkan-pending-audit"; + +/// The findings that print the thread's backtrace: the first ones. +const BACKTRACES: u64 = 8; + +/// What frees or reuses what a command buffer recorded (the module docs). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Freeing { + /// `vkBeginCommandBuffer`, which resets it. + Begin, + /// `vkResetCommandPool` of the pool that made it. + PoolReset, + /// The pool that made it given back to the device's spares, for the next command buffer to + /// take. + GiveBack, + /// A submission of it again. + Submit, +} + +impl Freeing { + /// Every kind, in the order of the counts' arrays. + pub(crate) const ALL: [Freeing; 4] = [ + Freeing::Begin, + Freeing::PoolReset, + Freeing::GiveBack, + Freeing::Submit, + ]; + + /// What it says in a line. + fn says(self) -> &'static str { + match self { + Freeing::Begin => "a begin (vkBeginCommandBuffer)", + Freeing::PoolReset => "a reset of its pool (vkResetCommandPool)", + Freeing::GiveBack => "its pool given back to the device's spares", + Freeing::Submit => "a submission of it again", + } + } +} + +/// A command buffer a check found carried by a submission the GPU may still run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Pending { + pub(crate) buffer: vk::CommandBuffer, + /// The timeline the submission signals, and the value. + pub(crate) semaphore: vk::Semaphore, + pub(crate) value: u64, + /// The timeline's counter, as read. + pub(crate) counter: u64, +} + +/// What carries each command buffer (the module docs). +#[derive(Default)] +pub(crate) struct Ledger { + /// Each command buffer submitted, with the timelines whose values complete the submissions + /// that carry it: per timeline, the highest value (a timeline's signal completes every + /// submission before it in submission order on its queue). + carried: HashMap>, + /// The secondaries each primary executed since its last begin. + executes: HashMap>, + /// The command buffers last begun for simultaneous use, which may be pending in several + /// submissions at once. + simultaneous: HashSet, +} + +impl Ledger { + /// `buffers` (and the secondaries each executes) go in a submission that signals `semaphore` + /// to `value`. + pub(crate) fn submitted( + &mut self, + (semaphore, value): (vk::Semaphore, u64), + buffers: &[vk::CommandBuffer], + ) { + let Ledger { + carried, executes, .. + } = self; + for buffer in buffers { + let secondaries = executes.get(buffer).map_or(&[][..], Vec::as_slice); + for &carried_one in std::iter::once(buffer).chain(secondaries) { + let timelines = carried.entry(carried_one).or_default(); + match timelines.iter_mut().find(|(of, _)| *of == semaphore) { + Some((_, highest)) => *highest = (*highest).max(value), + None => timelines.push((semaphore, value)), + } + } + } + } + + /// The submission of `buffers` that would have signalled `semaphore` to `value` failed: + /// nothing of it is pending. + pub(crate) fn withdrawn( + &mut self, + (semaphore, value): (vk::Semaphore, u64), + buffers: &[vk::CommandBuffer], + ) { + let Ledger { + carried, executes, .. + } = self; + for buffer in buffers { + let secondaries = executes.get(buffer).map_or(&[][..], Vec::as_slice); + for carried_one in std::iter::once(buffer).chain(secondaries) { + let Some(timelines) = carried.get_mut(carried_one) else { + continue; + }; + timelines.retain(|&(of, highest)| (of, highest) != (semaphore, value)); + if timelines.is_empty() { + carried.remove(carried_one); + } + } + } + } + + /// `primary` executes `secondaries` (`vkCmdExecuteCommands`). + pub(crate) fn executes( + &mut self, + primary: vk::CommandBuffer, + secondaries: &[vk::CommandBuffer], + ) { + (self.executes.entry(primary).or_default()).extend_from_slice(secondaries); + } + + /// `buffer` was begun, for simultaneous use where `simultaneous`: what it executed before is + /// no longer its own. + pub(crate) fn begun(&mut self, buffer: vk::CommandBuffer, simultaneous: bool) { + self.executes.remove(&buffer); + match simultaneous { + true => self.simultaneous.insert(buffer), + false => self.simultaneous.remove(&buffer), + }; + } + + /// Of `buffers`, those a submission may be pending in many at once: begun for simultaneous + /// use, which a submission again does not reuse. + pub(crate) fn submitted_again(&self, buffers: &[vk::CommandBuffer]) -> Vec { + let Ledger { + executes, + simultaneous, + .. + } = self; + let mut again = Vec::new(); + for buffer in buffers { + let secondaries = executes.get(buffer).map_or(&[][..], Vec::as_slice); + let each = std::iter::once(buffer).chain(secondaries); + again.extend(each.filter(|buffer| !simultaneous.contains(buffer))); + } + again + } + + /// Of `buffers`, those carried by a submission whose timeline's counter, as `read` reads it, + /// is below the submission's value; carrying submissions found completed leave the ledger. + /// A timeline `read` cannot read finds nothing. + pub(crate) fn pending( + &mut self, + buffers: &[vk::CommandBuffer], + mut read: impl FnMut(vk::Semaphore) -> Option, + ) -> Vec { + let mut counters: Vec<(vk::Semaphore, Option)> = Vec::new(); + let mut found = Vec::new(); + for &buffer in buffers { + let Some(timelines) = self.carried.get_mut(&buffer) else { + continue; + }; + timelines.retain(|&(semaphore, value)| { + let counter = match counters.iter().find(|(of, _)| *of == semaphore) { + Some(&(_, counter)) => counter, + None => { + let counter = read(semaphore); + counters.push((semaphore, counter)); + counter + } + }; + match counter { + Some(counter) if counter >= value => false, + Some(counter) => { + found.push(Pending { + buffer, + semaphore, + value, + counter, + }); + true + } + None => true, + } + }); + if timelines.is_empty() { + self.carried.remove(&buffer); + } + } + found + } +} + +/// The checks a device's audit made and the findings, by kind ([`Freeing::ALL`]'s order). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Counts { + pub(crate) checks: [u64; 4], + pub(crate) found: [u64; 4], +} + +/// A device's pending audit, where it is on (the module docs). +pub(crate) struct PendingAudit { + sink: Option, + ledger: Mutex, + checks: [AtomicU64; 4], + found: [AtomicU64; 4], +} + +impl PendingAudit { + /// The audit of a device whose instance reports to `sink`, where `asked` + /// (`DeviceOptions::pending_audit`) or the variable is set; its first line said. + pub(crate) fn new(asked: bool, sink: Option<&MessageSink>) -> Option> { + if !asked && !metal2vulkan::env_vars::pending_audit() { + return None; + } + let audit = PendingAudit { + sink: sink.cloned(), + ledger: Mutex::new(Ledger::default()), + checks: Default::default(), + found: Default::default(), + }; + audit.line( + "metal2vulkan: pending audit: on: each begin, pool reset, pool given back and \ + submission again of a command buffer is checked against the timelines of the \ + submissions that carry it" + .to_owned(), + ); + Some(Arc::new(audit)) + } + + /// `buffers` go in a submission that signals `semaphore` to `value`: each of them submitted + /// before and not begun for simultaneous use is checked first ([`Freeing::Submit`]). + pub(crate) fn submitted( + &self, + raw: &ash::Device, + (semaphore, value): (vk::Semaphore, u64), + buffers: &[&[vk::CommandBuffer]], + ) { + let mut found = Vec::new(); + { + let mut ledger = lock(&self.ledger); + for &buffers in buffers { + let again = ledger.submitted_again(buffers); + found.extend(self.check_in(&mut ledger, raw, Freeing::Submit, &again)); + ledger.submitted((semaphore, value), buffers); + } + } + self.report(Freeing::Submit, found); + } + + /// The submission of `buffers` that would have signalled `semaphore` to `value` failed. + pub(crate) fn withdrawn( + &self, + (semaphore, value): (vk::Semaphore, u64), + buffers: &[&[vk::CommandBuffer]], + ) { + let mut ledger = lock(&self.ledger); + for &buffers in buffers { + ledger.withdrawn((semaphore, value), buffers); + } + } + + /// `primary` executes `secondaries`. + pub(crate) fn executes(&self, primary: vk::CommandBuffer, secondaries: &[vk::CommandBuffer]) { + lock(&self.ledger).executes(primary, secondaries); + } + + /// `buffer` is about to be begun with `flags`: checked ([`Freeing::Begin`]), then begun. + pub(crate) fn begins( + &self, + raw: &ash::Device, + buffer: vk::CommandBuffer, + flags: vk::CommandBufferUsageFlags, + ) { + let found = { + let mut ledger = lock(&self.ledger); + let found = self.check_in(&mut ledger, raw, Freeing::Begin, &[buffer]); + let simultaneous = flags.contains(vk::CommandBufferUsageFlags::SIMULTANEOUS_USE); + ledger.begun(buffer, simultaneous); + found + }; + self.report(Freeing::Begin, found); + } + + /// `what` is about to free or reuse what `buffers` recorded: checked. + pub(crate) fn check(&self, raw: &ash::Device, what: Freeing, buffers: &[vk::CommandBuffer]) { + let found = self.check_in(&mut lock(&self.ledger), raw, what, buffers); + self.report(what, found); + } + + /// The checks made and the findings so far. + pub(crate) fn counts(&self) -> Counts { + let read = |counts: &[AtomicU64; 4]| counts.each_ref().map(|n| n.load(Ordering::Relaxed)); + Counts { + checks: read(&self.checks), + found: read(&self.found), + } + } + + /// [`check`](Self::check) under the ledger's lock, `ledger`: what it found, said once the + /// lock is let go of (a sink may call the runtime). + fn check_in( + &self, + ledger: &mut Ledger, + raw: &ash::Device, + what: Freeing, + buffers: &[vk::CommandBuffer], + ) -> Vec { + if buffers.is_empty() { + return Vec::new(); + } + self.checks[what as usize].fetch_add(1, Ordering::Relaxed); + ledger.pending(buffers, |semaphore| { + // SAFETY: a timeline of the device's, which lives while the device does. + let read = unsafe { raw.get_semaphore_counter_value(semaphore) }; + exit_guard::called(Call::GetSemaphoreCounterValue); + read.ok() + }) + } + + /// Count and say each of `found`, which `what` met. + fn report(&self, what: Freeing, found: Vec) { + for pending in found { + let finding = self.found[what as usize].fetch_add(1, Ordering::Relaxed) + 1; + let total: u64 = (self.found.iter()).map(|n| n.load(Ordering::Relaxed)).sum(); + let trace = match total <= BACKTRACES { + true => format!("\n{}", Backtrace::force_capture()), + false => String::new(), + }; + let thread = std::thread::current(); + let Pending { + buffer, + semaphore, + value, + counter, + } = pending; + self.line(format!( + "metal2vulkan: pending audit: {} of command buffer 0x{:x} on thread {}, while a \ + submission that carries it may run: timeline semaphore 0x{:x} at {counter}, \ + below the submission's value {value} (finding {finding} of its kind){trace}", + what.says(), + buffer.as_raw(), + thread.name().unwrap_or("unnamed"), + semaphore.as_raw(), + )); + } + } + + /// Deliver `text`, a line of the audit. + fn line(&self, text: String) { + inform_through(self.sink.as_ref(), ID_NAME, text); + } +} + +/// Its last line, as the device goes: the checks and findings, by kind. +impl Drop for PendingAudit { + fn drop(&mut self) { + let Counts { checks, found } = self.counts(); + let each = (Freeing::ALL.iter().enumerate()) + .map(|(at, what)| { + format!( + "{}: {} checks, {} found", + what.says(), + checks[at], + found[at] + ) + }) + .collect::>() + .join("; "); + self.line(format!("metal2vulkan: pending audit: {each}")); + } +} diff --git a/crates/metal2vulkan-runtime/src/spares.rs b/crates/metal2vulkan-runtime/src/spares.rs index 5a4ad4e25..d000380b8 100644 --- a/crates/metal2vulkan-runtime/src/spares.rs +++ b/crates/metal2vulkan-runtime/src/spares.rs @@ -99,11 +99,16 @@ //! - **Released with the device**, as its teardown begins (`DeviceShared`'s drop, after //! `vkDeviceWaitIdle`): every command buffer holds the device, so none is left to give one //! back. +//! - **Audited where the device's pending audit is on** (`pending_audit.rs`): a pool given back, +//! and a spare pool its taker resets, has each of its command buffers checked against the +//! submissions that carry it, its primary begun ahead among them; the begin ahead is checked as +//! every begin is (`device/functions.rs`). use super::descriptor_arena::{Room, SetNeeds}; use super::device::{lock, DeviceShared}; use super::error::{vulkan, Error}; use super::exit_guard::{self, Call}; +use super::pending_audit::Freeing; use super::release::{self, Released}; use ash::vk; use std::collections::VecDeque; @@ -197,6 +202,14 @@ impl CommandPool { self.recording = false; } + /// Every command buffer made from the pool, of both levels, the primary begun ahead among + /// them: what its reset or give-back frees (the device's pending audit, `pending_audit.rs`). + fn buffers(&self) -> Vec { + let [primaries, secondaries] = &self.made; + let made = primaries.iter().chain(secondaries).copied(); + made.chain(self.begun).collect() + } + /// Whether the pool made no secondary command buffer (the module docs). pub(super) fn wants_secondary(&self) -> bool { self.made[level_index(vk::CommandBufferLevel::SECONDARY)].is_empty() @@ -313,6 +326,9 @@ impl Spares { return Ok(None); }; if pool.recording { + if let Some(audit) = device.pending_audit() { + audit.check(device.vk(), Freeing::PoolReset, &pool.buffers()); + } // SAFETY: the pool is the caller's alone now, and nothing of it is pending: the // command buffer that gave it back ended its work or was never submitted. let reset = unsafe { @@ -343,6 +359,13 @@ impl Spares { mut pool: CommandPool, settled: bool, ) { + // The audit reads the device's timelines inside a section of the exit guard, on + // whatever thread gives the pool back. + if let Some(audit) = device.pending_audit() { + if let Some(_busy) = exit_guard::enter() { + audit.check(device.vk(), Freeing::GiveBack, &pool.buffers()); + } + } pool.recording = !settled; pool.stock(device); keep_command_pool(&mut lock(&self.command_pools), pool); diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 3ae984add..a11f71af0 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -338,6 +338,9 @@ mod padding_unobserved; mod pass_end_tiles; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod passing_holds; +mod pending_audit; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod pending_audit_device; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod pending_rebind; mod pipeline; diff --git a/crates/metal2vulkan-runtime/src/tests/pending_audit.rs b/crates/metal2vulkan-runtime/src/tests/pending_audit.rs new file mode 100644 index 000000000..fe0bf239c --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/pending_audit.rs @@ -0,0 +1,153 @@ +//! The pending audit's ledger (`pending_audit.rs`): what carries each command buffer, a secondary +//! through each primary that executes it, and which command buffers a check finds pending against +//! the timelines as read. + +use crate::pending_audit::{Ledger, Pending}; +use ash::vk::{self, Handle}; + +/// Command buffer `n`. +fn buffer(n: u64) -> vk::CommandBuffer { + vk::CommandBuffer::from_raw(n) +} + +/// Timeline semaphore `n`. +fn timeline(n: u64) -> vk::Semaphore { + vk::Semaphore::from_raw(n) +} + +/// A read of timelines whose counters are `counters` (semaphore, counter); none of another. +fn reader(counters: &[(u64, u64)]) -> impl FnMut(vk::Semaphore) -> Option + '_ { + move |semaphore| { + (counters.iter()) + .find(|&&(of, _)| timeline(of) == semaphore) + .map(|&(_, counter)| counter) + } +} + +/// A command buffer is pending while the timeline of a submission that carries it is below that +/// submission's value, found at each check until the timeline reaches it; then it leaves the +/// ledger, and no later check reads a timeline for it. One never submitted is pending nowhere. +#[test] +fn a_command_buffer_is_pending_until_its_timeline_reaches_the_value() { + let mut ledger = Ledger::default(); + ledger.submitted((timeline(1), 5), &[buffer(10), buffer(11)]); + let pending = Pending { + buffer: buffer(10), + semaphore: timeline(1), + value: 5, + counter: 4, + }; + assert_eq!(ledger.pending(&[buffer(10)], reader(&[(1, 4)])), [pending]); + assert_eq!(ledger.pending(&[buffer(10)], reader(&[(1, 4)])), [pending]); + let both = [buffer(10), buffer(11)]; + assert!(ledger.pending(&both, reader(&[(1, 5)])).is_empty()); + let mut reads = 0; + let found = ledger.pending(&both, |_| { + reads += 1; + Some(0) + }); + assert_eq!((found, reads), (Vec::new(), 0), "both left the ledger"); + assert!(ledger.pending(&[buffer(12)], reader(&[(1, 0)])).is_empty()); +} + +/// A check reads each timeline once, however many command buffers it carries. +#[test] +fn a_check_reads_each_timeline_once() { + let mut ledger = Ledger::default(); + ledger.submitted((timeline(1), 5), &[buffer(10), buffer(11)]); + ledger.submitted((timeline(2), 3), &[buffer(11)]); + let mut reads = Vec::new(); + let found = ledger.pending(&[buffer(10), buffer(11)], |semaphore| { + reads.push(semaphore); + Some(4) + }); + assert_eq!(reads, [timeline(1), timeline(2)]); + assert_eq!(found.len(), 2, "both carried by the submission at 5"); +} + +/// A command buffer submitted again waits for its latest submission on each timeline, and for +/// each timeline apart. +#[test] +fn a_command_buffer_waits_for_its_latest_submission_on_each_timeline() { + let mut ledger = Ledger::default(); + ledger.submitted((timeline(1), 5), &[buffer(10)]); + ledger.submitted((timeline(1), 7), &[buffer(10)]); + ledger.submitted((timeline(2), 3), &[buffer(10)]); + let found = ledger.pending(&[buffer(10)], reader(&[(1, 6), (2, 2)])); + let values: Vec<(vk::Semaphore, u64, u64)> = (found.iter()) + .map(|pending| (pending.semaphore, pending.value, pending.counter)) + .collect(); + assert_eq!(values, [(timeline(1), 7, 6), (timeline(2), 3, 2)]); + assert!(ledger + .pending(&[buffer(10)], reader(&[(1, 7), (2, 3)])) + .is_empty()); +} + +/// A secondary command buffer is carried by each primary that executes it, through that +/// primary's submissions; a primary begun again executes nothing it did before, so its next +/// submission carries none of it. +#[test] +fn a_secondary_is_carried_through_each_primary_that_executes_it() { + let mut ledger = Ledger::default(); + let (primary, other, secondary) = (buffer(1), buffer(2), buffer(3)); + ledger.executes(primary, &[secondary]); + ledger.executes(other, &[secondary]); + ledger.submitted((timeline(1), 5), &[primary]); + ledger.submitted((timeline(2), 9), &[other]); + let pending = Pending { + buffer: secondary, + semaphore: timeline(2), + value: 9, + counter: 8, + }; + assert_eq!( + ledger.pending(&[secondary], reader(&[(1, 5), (2, 8)])), + [pending] + ); + assert!(ledger.pending(&[secondary], reader(&[(2, 9)])).is_empty()); + ledger.begun(primary, false); + ledger.submitted((timeline(1), 6), &[primary]); + assert!(ledger.pending(&[secondary], reader(&[(1, 5)])).is_empty()); + assert_eq!(ledger.pending(&[primary], reader(&[(1, 5)])).len(), 1); +} + +/// A submission that failed carries nothing: neither its command buffers nor the secondaries they +/// execute. +#[test] +fn a_failed_submission_carries_nothing() { + let mut ledger = Ledger::default(); + let (primary, secondary) = (buffer(1), buffer(2)); + ledger.executes(primary, &[secondary]); + ledger.submitted((timeline(1), 5), &[primary]); + ledger.withdrawn((timeline(1), 5), &[primary]); + assert!(ledger + .pending(&[primary, secondary], reader(&[(1, 0)])) + .is_empty()); +} + +/// A timeline that cannot be read (a lost device) finds nothing, and forgets nothing. +#[test] +fn a_timeline_that_cannot_be_read_finds_nothing() { + let mut ledger = Ledger::default(); + ledger.submitted((timeline(1), 5), &[buffer(10)]); + assert!(ledger.pending(&[buffer(10)], |_| None).is_empty()); + assert_eq!(ledger.pending(&[buffer(10)], reader(&[(1, 4)])).len(), 1); +} + +/// A submission again checks the command buffers it submits and the secondaries they execute, +/// but those last begun for simultaneous use, which may be pending in several submissions. +#[test] +fn a_submission_again_checks_all_but_those_begun_for_simultaneous_use() { + let mut ledger = Ledger::default(); + let (once, simultaneous, secondary, kept) = (buffer(1), buffer(2), buffer(3), buffer(4)); + ledger.begun(once, false); + ledger.begun(simultaneous, true); + ledger.begun(kept, true); + ledger.executes(once, &[secondary, kept]); + assert_eq!( + ledger.submitted_again(&[once, simultaneous]), + [once, secondary] + ); + ledger.begun(simultaneous, false); + assert_eq!(ledger.submitted_again(&[simultaneous]), [simultaneous]); +} diff --git a/crates/metal2vulkan-runtime/src/tests/pending_audit_device.rs b/crates/metal2vulkan-runtime/src/tests/pending_audit_device.rs new file mode 100644 index 000000000..b11b07f84 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/pending_audit_device.rs @@ -0,0 +1,154 @@ +//! The pending audit on a device (`pending_audit.rs`): a command pool given back to the device's +//! spares while a command buffer of it waits on the GPU is found, once, and said in a line; the +//! command buffer that then takes that pool (its taking resets it), the primary its completing +//! thread begins ahead in the pool, and the command buffer that takes that primary are each +//! checked, and none is found pending. The command buffer is held on the GPU by its wait for a +//! plain event's signal reserved for the caller (`Event::reserve_vk_signal`), which the test makes +//! from the host once the give-back was found: the contract's signal where the caller's submission +//! is not made. +//! +//! Device tests: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. + +use super::blit_holds::{options, until, Scratch, WAIT}; +use crate::pending_audit::{Counts, Freeing}; +use crate::{ + Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, Event, MessageSink, + ResourceOptions, VkEventSignal, +}; +use ash::vk; +use std::sync::{Arc, Mutex}; + +/// The bytes each command buffer fills. +const BYTES: u64 = 4096; + +/// The id name of the audit's lines. +const AUDIT: &str = "metal2vulkan-pending-audit"; + +/// A committed command buffer of `queue` that fills `target`, after a wait for `event` to reach 1 +/// where given. +fn filling(queue: &CommandQueue, target: &Buffer, event: Option<&Event>) -> CommandBuffer { + let command_buffer = queue.command_buffer().unwrap(); + if let Some(event) = event { + command_buffer + .encode_wait_for_event(event.into(), 1) + .unwrap(); + } + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(target, 0..BYTES, 0x5a).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer +} + +/// The checks and findings of `device`'s audit so far. +fn counts(device: &Device) -> Counts { + let audit = device.shared().pending_audit(); + audit.expect("the device's pending audit is on").counts() +} + +#[test] +fn a_pool_given_back_while_its_command_buffer_waits_on_the_gpu_is_found() { + let scratch = Scratch::new("pending-audit"); + let lines = Arc::new(Mutex::new(Vec::new())); + let kept = Arc::clone(&lines); + let mut options = options(&scratch.0); + options.pending_audit = true; + options.messages = Some(MessageSink::new(move |message| { + if message.id_name == AUDIT { + kept.lock().unwrap().push(message.text.clone()); + } + })); + let device = Device::system_default_with(&options).unwrap(); + let said = || lines.lock().unwrap().clone(); + assert!( + said().iter().any(|line| line.contains("pending audit: on")), + "the audit says it is on: {:?}", + said() + ); + let queue = device.new_command_queue().unwrap(); + let target = device + .new_buffer(BYTES, ResourceOptions::private()) + .unwrap(); + let event = device.new_event().unwrap(); + // SAFETY: the reserved signal is made below, from the host, once the give-back was found, + // and waits for no earlier signal (asserted): the contract's signal where the caller's + // submission is not made. The event lives until it landed. + let reserved = unsafe { event.reserve_vk_signal(1) }.unwrap(); + let VkEventSignal::Counter { counter, after } = reserved else { + panic!("a signal above the event's value is reserved: {reserved:?}"); + }; + assert_eq!(after, None, "the event's first signal waits for none"); + let held = filling(&queue, &target, Some(&event)); + until("the held command buffer submitted", || { + held.status() == CommandBufferStatus::Scheduled + }); + assert_eq!(counts(&device).found, [0; 4], "{:?}", said()); + + // The deliberate early give-back: its command buffers wait on the GPU for the signal. + assert!( + held.give_pool_back_early(), + "the held command buffer holds its pool" + ); + let given = counts(&device); + let mut expected = [0; 4]; + expected[Freeing::GiveBack as usize] = 1; + assert_eq!(given.found, expected, "{:?}", said()); + assert!( + said() + .iter() + .any(|line| line.contains("its pool given back to the device's spares")), + "the finding is said: {:?}", + said() + ); + + // The reserved signal lets the held command buffer run. + let raw = device.shared().vk(); + // SAFETY: the event's timeline semaphore, signalled to its reserved counter once, as above. + let semaphore = unsafe { event.vk_semaphore() }; + let signal = vk::SemaphoreSignalInfo::default() + .semaphore(semaphore) + .value(counter); + // SAFETY: as above; the semaphore is below `counter`, which nothing else signals. + unsafe { raw.signal_semaphore(&signal) }.unwrap(); + held.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(held.status(), CommandBufferStatus::Completed); + + // The pool given back, taken (and reset) by the next command buffer, which completes while + // no thread waits for it, so its completing thread begins a primary of the pool ahead; then a + // command buffer that takes that primary. Nothing is found pending. + let checked = counts(&device); + let work = device.work_counts(); + let next = filling(&queue, &target, None); + until( + "the next command buffer completed, no thread waiting", + || next.status() == CommandBufferStatus::Completed, + ); + until("its pool's primary begun ahead", || { + device.work_counts().primaries_begun_ahead > work.primaries_begun_ahead + }); + let last = filling(&queue, &target, None); + last.wait_until_completed_for(WAIT).unwrap(); + let done = device.work_counts(); + assert!( + done.spare_command_pools_reset > work.spare_command_pools_reset, + "the next command buffer reset the pool given back" + ); + assert!( + done.encoder_primaries_begun_ahead > work.encoder_primaries_begun_ahead, + "the last command buffer took the primary begun ahead" + ); + let audited = counts(&device); + for what in [Freeing::Begin, Freeing::PoolReset, Freeing::GiveBack] { + assert!( + audited.checks[what as usize] > checked.checks[what as usize], + "{what:?} checked: {checked:?} then {audited:?}" + ); + } + assert_eq!( + audited.found, + given.found, + "nothing more found: {:?}", + said() + ); +} diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index e9389e229..a0dd939ac 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -145,7 +145,7 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan-air/src/lib.rs", compile), ("metal2vulkan/src/cache/digest.rs", "the content digest, which defines the artifact rather than acting on it"), ("metal2vulkan/src/cache/mod.rs", "the plan's specialization and variant keys, whose values the plan digest holds, and RUNTIME_VERSION itself, which cannot be among the sources it versions"), - ("metal2vulkan/src/env_vars.rs", "the operational variables' accessors: the runtime reads only METAL2VULKAN_LOG_PIPELINES, METAL2VULKAN_LOG_MEMORY and METAL2VULKAN_LOG_SHADOWS, default-off diagnostics that print and change no run"), + ("metal2vulkan/src/env_vars.rs", "the operational variables' accessors: the runtime reads only METAL2VULKAN_LOG_PIPELINES, METAL2VULKAN_LOG_MEMORY, METAL2VULKAN_LOG_SHADOWS and METAL2VULKAN_PENDING_AUDIT, default-off diagnostics that print and change no run"), ("metal2vulkan/src/error/mod.rs", "the error vocabulary: the runtime's code decides which error a run reports, and a record keeps the error as reported"), ("metal2vulkan/src/library/mod.rs", compile), ("metal2vulkan/src/lower/access/imageblock.rs", compile), diff --git a/crates/metal2vulkan/src/env_vars.rs b/crates/metal2vulkan/src/env_vars.rs index 28b545980..2e614c337 100644 --- a/crates/metal2vulkan/src/env_vars.rs +++ b/crates/metal2vulkan/src/env_vars.rs @@ -60,6 +60,22 @@ pub const REGISTRY: &[EnvVar] = &[ its memory class (placed), bytes, offset and block, to show what makes and \ frees blocks; set to anything but empty or 0", }, + EnvVar { + name: "METAL2VULKAN_PENDING_AUDIT", + default: "unset (off)", + effect: "metal2vulkan-runtime's diagnostics: each device checks, at each \ + vkBeginCommandBuffer, vkResetCommandPool and command pool given back to its \ + spares, and at each submission of a command buffer submitted before, that the \ + GPU completed every submission carrying the command buffers concerned (a \ + secondary through each primary that executes it), reading those submissions' \ + timelines with vkGetSemaphoreCounterValue; it logs each one found pending, \ + through the device's message sink or on stderr, with the thread's backtrace for \ + the first 8, and changes no work. Costs when set: a lock of the device's ledger \ + at each of those calls and at each vkCmdExecuteCommands, an entry per command \ + buffer per submission until a check finds it completed, one \ + vkGetSemaphoreCounterValue per carrying timeline at each check of a command \ + buffer still in the ledger; set to anything but empty or 0", + }, EnvVar { name: "METAL2VULKAN_LOG_SHADOWS", default: "unset (off)", @@ -121,6 +137,13 @@ pub fn log_shadows() -> bool { .is_some_and(|value| !value.is_empty() && value != "0") } +/// Whether each metal2vulkan-runtime device runs its pending audit (`REGISTRY`): set, and neither +/// empty nor `0`. A default-off diagnostic: it reads timelines and prints, and changes no work. +pub fn pending_audit() -> bool { + std::env::var_os("METAL2VULKAN_PENDING_AUDIT") + .is_some_and(|value| !value.is_empty() && value != "0") +} + /// Optional path override for an external tool `cmd` (`llvm-as`, `spirv-val`, …), read from /// `METAL2VULKAN_` (uppercased, `-`→`_`). A dynamic family — one var per tool the binary or /// the crate's test support runs — documented in `REGISTRY` as a single `METAL2VULKAN_` diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 39126e6c9..9f2ee12ed 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2089,6 +2089,7 @@ field metal2vulkan-runtime::DeviceOptions.lowering_refuses pub lowering_refuses: field metal2vulkan-runtime::DeviceOptions.mac_class pub mac_class: Option field metal2vulkan-runtime::DeviceOptions.messages pub messages: Option field metal2vulkan-runtime::DeviceOptions.optional_device_extensions pub optional_device_extensions: Vec +field metal2vulkan-runtime::DeviceOptions.pending_audit pub pending_audit: bool field metal2vulkan-runtime::DeviceOptions.pipeline_records pub pipeline_records: Option> field metal2vulkan-runtime::DeviceOptions.policy pub policy: DevicePolicy field metal2vulkan-runtime::DeviceOptions.record_executions pub record_executions: bool diff --git a/docs/API.md b/docs/API.md index d913d1f8e..ff1f8be45 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1631,6 +1631,16 @@ texture's image of its stored frame and its twin, a two-plane extended-range tex depth or stencil texture's tiled twin over a surface plane, and a YCbCr texture's converted image and render shadow. A heap texture's shadow, a view's shadow of an image and a texture buffer's staging are not logged. +With `METAL2VULKAN_PENDING_AUDIT` set (or `DeviceOptions::pending_audit`), a device checks, at each +`vkBeginCommandBuffer`, each `vkResetCommandPool` of a spare command pool, each command pool given +back to its spares and each submission of a command buffer submitted before (one not begun for +simultaneous use), that the GPU completed every submission that carries the command buffers +concerned: a batch's, the device's own and the staging queue's, to the timeline value each signals, +and a secondary through each primary that executes it. It reads those timelines +(`vkGetSemaphoreCounterValue`) and logs each command buffer found pending (id name +`metal2vulkan-pending-audit`, `Info` severity): what was done, the thread, the command buffer, the +timeline, its counter and the value, with the thread's backtrace for the first 8; and a line as the +device is made and as it goes, with the checks and findings by kind. It changes no work. Whatever the variables, a placement heap's `newTextureWithDescriptor:offset:` that makes no texture (`Nil` or `OutOfMemory`) at an offset inside the heap says so (id name `metal2vulkan-heap-texture-refused`, `Info` severity): the descriptor, the offset, the heap's size,