From 48caeeb155340432106c23721b016737f4e6f169 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 8 Nov 2026 04:29:19 -0800 Subject: [PATCH] DegradeNotice::command_buffer: the command buffer whose work announced a notice A consumer that makes some notices fatal (reims-vgpu's ReleasedCommandState, PrivateResourceOption, HostDeallocatorDelayed) could not tell which command buffer a notice was about: a ReleasedCommandState announced at a host step on the scheduler's steps thread ended its whole VM. Now every notice carries the ID of the command buffer whose work the runtime was doing on the announcing thread, so the consumer can fail that one command buffer. What changed: - CommandBuffer::object_id: an ObjectId, minted at the command buffer's making from the process-wide count buffers, textures and heaps use. - DegradeNotice::command_buffer: Option, read at the notice's making from a thread-local scope (degradation::NoticesFor), as `call` reads the call being lowered. The scope is set where the runtime holds the command buffer and does its work: the compute and blit encoders' logged funnels and their other recording calls and ends, the render lowering's at-call funnel, its unit calls, its batches' lowering (on the lowering thread or a drain) and its end, the resource state encoder's calls, encoder openings, the commit (at the call or queued behind a render end), a batch's submission and the storage-form settle that rides on it, host steps, a rebind's encoding again, and GPU-time reads. Nested scopes name the innermost. - None, explicitly, for a recovery of the device (device-recovered), for grouped-completion (several command buffers' batches), and inside the program's code the runtime calls (exit_guard::program, indirect command checks, executed-commands handlers). - A bind's memoized notices, announced again at each later bind under announce_each, are named as that bind's: its command buffer and the call being lowered (the call was the first bind's before; same mechanism). - ObjectId docs, docs/API.md section 9, docs/RUNTIME-PORTING.md; API signatures re-blessed (two records: the field and the method). Tests (runtime crate, device tests): - notice_command_buffers: an ICB execution recorded at a host step announces released-command-state on the steps thread naming the executing command buffer; its commit's host-replayed-indirect-commands, on the program's thread, names it too; private-resource-option of an ICB made between the encoder's calls names none. - deferred_calls: the call-naming test also checks the command buffer under both lowering policies; a new test waits for the lowering thread to announce unsized-points after end_encoding and checks the thread, call and command buffer, and that a device notice between the encoder's calls names none. - vertex_conversion_notices: a memoized bind notice (device-nan-encoding) announced at a second command buffer's draw names that command buffer and its own call index, with bound_notices_made proving the memo was reused. (cherry picked from commit b4c2ba83ea726229f129a405ce6f432b0bdb0127) --- crates/metal2vulkan-runtime/src/blit.rs | 3 + .../src/command_buffer/group.rs | 4 +- .../src/command_buffer/mod.rs | 32 +++- .../src/command_buffer/reencode.rs | 1 + .../src/command_buffer/storage_form.rs | 1 + .../src/command_buffer/submit.rs | 1 + crates/metal2vulkan-runtime/src/compute.rs | 4 + .../metal2vulkan-runtime/src/degradation.rs | 99 +++++++++++ crates/metal2vulkan-runtime/src/encoder.rs | 7 + .../src/executed_commands.rs | 3 + crates/metal2vulkan-runtime/src/exit_guard.rs | 11 +- .../src/indirect_command_buffer.rs | 4 +- .../metal2vulkan-runtime/src/predication.rs | 5 + crates/metal2vulkan-runtime/src/render.rs | 2 + .../src/render/deferral.rs | 9 +- .../metal2vulkan-runtime/src/render/replay.rs | 1 + crates/metal2vulkan-runtime/src/resource.rs | 14 +- .../src/sparse/encoder.rs | 8 + .../src/tests/deferred_calls.rs | 79 ++++++++- crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/notice_command_buffers.rs | 159 ++++++++++++++++++ .../src/tests/vertex_conversion_notices.rs | 75 ++++++++- crates/metal2vulkan/tests/api_signatures.tsv | 2 + docs/API.md | 10 ++ docs/RUNTIME-PORTING.md | 2 +- 25 files changed, 516 insertions(+), 22 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/notice_command_buffers.rs diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index 9c2de3423..34643995b 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -184,6 +184,7 @@ impl CommandBuffer { /// `blitCommandEncoder`. Refused while another encoder of this command buffer is open, /// after one was abandoned, and after commit. pub fn blit_command_encoder(&self) -> Result { + let _for = self.notices_for(); let core = EncoderCore::open(self, "blit_command_encoder", EncoderKind::Blit, true)?; Ok(BlitCommandEncoder { core, @@ -232,6 +233,7 @@ impl BlitCommandEncoder { call: impl FnOnce(&mut CallLog) -> BlitCall, run: impl FnOnce(&mut Self) -> Result, ) -> Result { + let _for = self.core.notices_for(); self.refuse_aborted()?; let at = match self.log.as_mut().filter(|log| !log.muted()) { Some(log) => { @@ -648,6 +650,7 @@ impl BlitCommandEncoder { /// `endEncoding`. pub fn end_encoding(self) -> Result<(), Error> { + let _for = self.core.notices_for(); // The core's shadows copy back what the blits wrote through heap shadows. The fill tiles // are their command buffer's, which holds them until it completes. let BlitCommandEncoder { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/group.rs b/crates/metal2vulkan-runtime/src/command_buffer/group.rs index 9ab564ecd..9624c6dd6 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/group.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/group.rs @@ -83,7 +83,7 @@ use super::submit::Submission; use super::{submission_error, CommandBufferShared}; -use crate::degradation::Degradation; +use crate::degradation::{Degradation, NoticesFor}; use crate::device::relay::Relayed; use crate::error::CommandBufferError; use crate::exit_guard::{self, Call}; @@ -547,6 +547,8 @@ impl Group { }; if several && outcome.is_ok() { let batches = count + usize::from(!alone); + // Several command buffers' batches: none of them named. + let _several = NoticesFor::none(); device.degrade_once(Degradation::GroupedCompletion, || { ( format!("{batches} batches of command buffers on one queue"), diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 35173afc7..57ea2d7d4 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -63,7 +63,7 @@ use super::compute::EncoderState; use super::contexts::{self, Run}; use super::copied::CopiesReached; use super::deferred::{Deferred, Prepared, StepInputs}; -use super::degradation::Degradation; +use super::degradation::{Degradation, NoticesFor}; use super::descriptor_arena::DescriptorArena; use super::device::relay::Relayed; use super::device::{lock, DeviceShared}; @@ -221,6 +221,8 @@ impl WeakCommandBuffer { } pub(super) struct CommandBufferShared { + /// Its ID ([`CommandBuffer::object_id`]), which the notices announced for its work name. + id: ObjectId, /// The generation of its device it was made on (`device/line.rs`), taken once at its making: /// its encoders' commands reach the device's state through it, at one load, with no kind of /// handle to tell apart. Declared before `device`, so it goes first. @@ -2104,6 +2106,7 @@ impl CommandBuffer { pub(super) fn new(queue: &QueueGen, root: &CommandQueue, slot: Slot) -> CommandBuffer { let footprints = Footprints::default(); CommandBuffer(Arc::new(CommandBufferShared { + id: ObjectId::new(), generation: Arc::clone(queue.device().shared_arc()), device: queue.device().clone(), queue: queue.clone(), @@ -2237,6 +2240,24 @@ impl CommandBuffer { &self.0.device } + /// The command buffer's ID: a runtime extension, no Metal property. Metal names a command + /// buffer by its pointer, which another object may take once it is freed. This number is one + /// of the process's object IDs (as a buffer's, texture's or heap's, never another object's), + /// the command buffer's for its whole life (a clone is the same command buffer): what a degrade + /// notice announced for its work names ([`DegradeNotice::command_buffer`]), so a program can + /// fail the one command buffer a notice was about. + /// + /// [`DegradeNotice::command_buffer`]: crate::DegradeNotice::command_buffer + pub fn object_id(&self) -> ObjectId { + self.0.id + } + + /// This thread doing the command buffer's work until the guard goes: the notices announced + /// meanwhile name it ([`NoticesFor`]). + pub(crate) fn notices_for(&self) -> NoticesFor { + self.0.notices_for() + } + /// The state of the generation of its device it was made on, its device's /// ([`CommandBufferShared::generation`]): what its encoders' commands reach, at one load. #[inline] @@ -3080,6 +3101,7 @@ impl CommandBuffer { run: CommitRun, hand: Hand, ) -> Result<(), Error> { + let _for = self.notices_for(); // The waiting fetched render targets take their storage form at this commit where it // allows (`storage_form.rs`): one atomic read where none waits. The scheduler's thread // ends the switch once it submitted the command buffer. None where nothing of it runs. @@ -3851,6 +3873,7 @@ impl CommandBuffer { /// does not answer from the host), and for a command buffer that found no slot of the /// device's timestamp pools free at its commit, and no pool more. fn gpu_times(&self) -> Result<(u64, u64), Error> { + let _for = self.notices_for(); let device = &self.0.device; let shared = device.shared(); let untimed = || Error::Unsupported(Unsupported::not_representable(Feature::GpuTimes)); @@ -4096,6 +4119,12 @@ impl CommandBufferShared { &self.device } + /// This thread doing the command buffer's work until the guard goes + /// ([`CommandBuffer::notices_for`]). + pub(super) fn notices_for(&self) -> NoticesFor { + NoticesFor::new(self.id) + } + /// This command buffer's address, which names it to [`own`]'s marker. fn address(&self) -> usize { self as *const CommandBufferShared as usize @@ -4325,6 +4354,7 @@ impl CommandBufferShared { /// any, is dropped. A failure is kept for the batch's submission, which fails the command /// buffer with it. pub(crate) fn host_step(self: &Arc, index: usize) { + let _for = self.notices_for(); // A rebind's encoding again of its encoders records into its pool too: one at a time. let _turn = lock(&self.reencoding); // Its instances numbered from its commit's place among the program's calls. diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 149bfb431..862363ec8 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -96,6 +96,7 @@ impl CommandBufferShared { /// first recording, which its group's submission fails. A command buffer that completed /// encodes nothing again. pub(crate) fn reencode(self: &Arc) { + let _for = self.notices_for(); let turn = lock(&self.reencoding); let marked = self.reencode.load(Ordering::Acquire); if marked == 0 { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs index 7af5fe532..b745e5d9c 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/storage_form.rs @@ -113,6 +113,7 @@ impl CommandBufferShared { /// ran (no check failed a submission of it, and its submission did not fail). Whether one /// rode on it. pub(crate) fn settle_storage_forms(&self) -> bool { + let _for = self.notices_for(); let state = lock(&self.state); let Some(riding) = &state.storage_form else { return false; diff --git a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs index cc3ae0403..39495bd2f 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/submit.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/submit.rs @@ -422,6 +422,7 @@ impl CommandBufferShared { alone: bool, scheduler: &mut scheduler::State, ) -> Result { + let _for = self.notices_for(); let device = &self.device; if device.is_lost() { return Err(CommandBufferError::DeviceLost); diff --git a/crates/metal2vulkan-runtime/src/compute.rs b/crates/metal2vulkan-runtime/src/compute.rs index a8346e3e2..077f443a4 100644 --- a/crates/metal2vulkan-runtime/src/compute.rs +++ b/crates/metal2vulkan-runtime/src/compute.rs @@ -252,6 +252,7 @@ impl CommandBuffer { call: &'static str, dispatch_type: DispatchType, ) -> Result { + let _for = self.notices_for(); // Metal's process ends here under some protection options (`command_buffer/protection.rs`). self.refuse_protected_encoder(call)?; let core = EncoderCore::open( @@ -351,6 +352,7 @@ impl ComputeCommandEncoder { call: impl FnOnce(&mut CallLog) -> ComputeCall, run: impl FnOnce(&mut Self) -> Result, ) -> Result { + let _for = self.core.notices_for(); let at = self.log(call); let ran = run(self); if let (Err(_), Some(at), Some(log)) = (&ran, at, &mut self.log) { @@ -1166,6 +1168,7 @@ impl ComputeCommandEncoder { /// `RENDER_TARGETS` records nothing. On a serial encoder, which orders its dispatches anyway, /// it adds nothing Metal would not do. pub fn memory_barrier_with_scope(&mut self, scope: BarrierScope) { + let _for = self.core.notices_for(); self.log(|_| ComputeCall::BarrierWithScope(scope)); if !scope.intersects(BarrierScope::BUFFERS.union(BarrierScope::TEXTURES)) { return; @@ -1600,6 +1603,7 @@ impl ComputeCommandEncoder { /// `endEncoding`. What it binds is held until the command buffer completes, as Metal holds /// what an encoder was handed. pub fn end_encoding(mut self) -> Result<(), Error> { + let _for = self.core.notices_for(); // Its unit of command predication takes what it encoded (`predication.rs`). self.end_predication()?; self.table.let_go_all(&mut self.core); diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index cfc14aa4a..75ebbac11 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2694,6 +2694,30 @@ pub struct DegradeNotice { /// its place among the encoder's calls. `None` for a notice announced inside the program's /// call itself, and for every other notice. pub call: Option, + /// The command buffer whose work announced it: its ID + /// ([`CommandBuffer::object_id`](crate::CommandBuffer::object_id)). A runtime extension; + /// Metal has no notices, and reports a command buffer's errors on the command buffer + /// (`MTLCommandBuffer.error`). Set for a notice announced while the runtime + /// does one command buffer's work on the announcing thread: a call of one of its encoders, + /// that call's lowering after it returned (`RenderLoweringPolicy::Worker`, on whichever + /// thread lowers it), the opening of an encoder of it, its commit (at the call, or once a + /// render encoder's end it waited for was lowered), the submission of a batch of it and the + /// settling of what rode on that batch, a host step of it on the scheduler's steps thread (an + /// indirect command buffer's execution recorded there among them), an encoding again of its + /// encoders at a rebind, and a read of its GPU times once it completed + /// ([`CommandBuffer::gpu_start_time`](crate::CommandBuffer::gpu_start_time), + /// [`CommandBuffer::gpu_end_time`](crate::CommandBuffer::gpu_end_time)). A notice a bind + /// announces at every occurrence (`DeviceOptions::announce_each`) names the command buffer of + /// that bind, not of the bind that first made it. `None` for every other notice: one + /// announced by the device, a library, a pipeline state, a resource or a queue outside any + /// command buffer's work (making, releasing, rebinding or detaching one, and the pages of a + /// detached or released no-copy buffer); one about several command buffers' batches together + /// ([`Degradation::GroupedCompletion`]); and one of a recovery of the device + /// ([`Degradation::DeviceRecovered`]), whichever call met it. The program's code the runtime + /// calls (a handler, a submission check, an indirect command check, a message sink) is no + /// command buffer's work: what its calls announce names none, but a call of an encoder, which + /// names the encoder's command buffer. + pub command_buffer: Option, } /// A notice announced where the runtime's rule announces none @@ -2756,9 +2780,25 @@ impl DegradeNotice { object_id: None, misplaced: None, call: crate::render::lowering::current(), + command_buffer: NoticesFor::current(), } } + /// The notice as announced now, by a bind that announces it again as made by an earlier bind + /// (`Device::announce_bound`): the call being lowered and the command buffer whose work runs + /// on this thread now, in place of the earlier bind's. + fn announced_here(&self) -> Option { + let (call, command_buffer) = (crate::render::lowering::current(), NoticesFor::current()); + if self.call == call && self.command_buffer == command_buffer { + return None; + } + Some(DegradeNotice { + call, + command_buffer, + ..self.clone() + }) + } + /// The notice as a message: a warning of the performance kind (a performance degradation) /// or the general kind (a precision or validity one), its `id_name` the code, its text /// `metal2vulkan: : ; []`. @@ -2864,6 +2904,53 @@ impl Announced { } } +thread_local! { + /// The command buffer whose work this thread does now ([`NoticesFor`]). + static NOTICES_FOR: Cell> = const { Cell::new(None) }; +} + +/// This thread doing one command buffer's work, from its making until it is dropped: every notice +/// announced meanwhile names that command buffer ([`DegradeNotice::command_buffer`]). Made where +/// the runtime holds the command buffer, at each place that does its work +/// (`CommandBuffer::notices_for`); one made inside another names its own command buffer until it +/// goes, then the other's again, and [`NoticesFor::none`] names none meanwhile. Neither `Send` nor +/// `Sync`: it is this thread's. +pub(crate) struct NoticesFor { + outer: Option, + _thread: std::marker::PhantomData<*const ()>, +} + +impl NoticesFor { + /// The work of the command buffer of ID `command_buffer`, from now. + pub(crate) fn new(command_buffer: ObjectId) -> NoticesFor { + NoticesFor::of(Some(command_buffer)) + } + + /// Work for no command buffer, from now, inside one's: what is announced about several + /// command buffers, or about the device. + pub(crate) fn none() -> NoticesFor { + NoticesFor::of(None) + } + + fn of(command_buffer: Option) -> NoticesFor { + NoticesFor { + outer: NOTICES_FOR.with(|current| current.replace(command_buffer)), + _thread: std::marker::PhantomData, + } + } + + /// The command buffer whose work this thread does now, if any. + pub(crate) fn current() -> Option { + NOTICES_FOR.with(Cell::get) + } +} + +impl Drop for NoticesFor { + fn drop(&mut self) { + NOTICES_FOR.with(|current| current.set(self.outer)); + } +} + thread_local! { /// How many notices this thread met that their device announces, or refuses, at every /// occurrence ([`EachWatch`]). @@ -3284,6 +3371,8 @@ impl Device { let degradation = Degradation::DeviceRecovered; let misplaced = check_announcement(degradation, true); let (object, reason) = describe(); + // The device's, whichever command buffer's work met it. + let _device = NoticesFor::none(); let message = DegradeNotice::new(degradation, object, reason).message(); self.deliver_placed(degradation, message, misplaced); } @@ -3298,6 +3387,8 @@ impl Device { let degradation = Degradation::DeviceRecovered; let misplaced = check_announcement(degradation, false); let (object, reason) = describe(); + // The device's, whichever command buffer's work met it. + let _device = NoticesFor::none(); let message = DegradeNotice::new(degradation, object, reason).message(); self.deliver_placed(degradation, message, misplaced); } @@ -3502,6 +3593,14 @@ impl Device { } for (degradation, message) in notices { met_each(); + // Made by an earlier bind: named as this one's. + let here = (message.degradation.as_ref()) + .and_then(DegradeNotice::announced_here) + .map(|notice| DebugMessage { + degradation: Some(notice), + ..message.clone() + }); + let message = here.as_ref().unwrap_or(message); match check_announcement(*degradation, true) { None => self.deliver(message), misplaced => self.deliver_placed(*degradation, message.clone(), misplaced), diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 04de80413..62da42942 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -33,6 +33,7 @@ use super::churn_counts::KeepBy; use super::command_buffer::rebound_use::Unlogged; use super::command_buffer::{recording_error, CommandBuffer}; use super::deferred::{Deferred, StepInputs}; +use super::degradation::NoticesFor; use super::error::{internal, invalid, vulkan, CommandBufferError, Error}; use super::execution::Execution; use super::fresh_unwritten::{FreshRead, FreshUnwritten}; @@ -901,6 +902,12 @@ impl EncoderCore { &self.open.command_buffer } + /// This thread doing the work of the command buffer the encoder records into until the guard + /// goes: the notices announced meanwhile name it (`CommandBuffer::notices_for`). + pub(super) fn notices_for(&self) -> NoticesFor { + self.open.command_buffer.notices_for() + } + /// Refuse an object of `device` in Metal's `call` unless `device` is the encoder's. #[inline(always)] pub(super) fn check_device(&self, call: &'static str, device: &Device) -> Result<(), Error> { diff --git a/crates/metal2vulkan-runtime/src/executed_commands.rs b/crates/metal2vulkan-runtime/src/executed_commands.rs index 1af1877e8..995565e90 100644 --- a/crates/metal2vulkan-runtime/src/executed_commands.rs +++ b/crates/metal2vulkan-runtime/src/executed_commands.rs @@ -19,6 +19,7 @@ //! execution read; with one, the facts are gathered from what the reading resolved already. use super::command_buffer::CommandBuffer; +use super::degradation::NoticesFor; use super::error::{invalid, Error, Problem}; use super::indirect_command_buffer::IndirectCommandBuffer; use super::residency::Residency; @@ -127,6 +128,8 @@ impl CommandBuffer { unread_states_can_encode, writable: residency.writable_indirect_command_buffers(), }; + // The program's code: no command buffer's work of the runtime's. + let _program = NoticesFor::none(); for handler in &handlers { handler(&executed); } diff --git a/crates/metal2vulkan-runtime/src/exit_guard.rs b/crates/metal2vulkan-runtime/src/exit_guard.rs index 8703a0921..3911ee12c 100644 --- a/crates/metal2vulkan-runtime/src/exit_guard.rs +++ b/crates/metal2vulkan-runtime/src/exit_guard.rs @@ -1252,10 +1252,11 @@ pub(crate) fn at_least_user_initiated() -> bool { /// Run the program's code `f` (a handler, a notification, a deallocator, a message sink) on /// this thread, catching a panic: what it calls is the program's, as on the program's own -/// threads. Every call of the program's code goes through here. In builds with debug assertions -/// (every test run), end the process where this thread is inside a passing hold of a device's -/// resources, which a making on another thread may wait for (`resource_ids.rs`): `f` may wait -/// for that making. +/// threads, and no command buffer's work of the runtime's (`degradation::NoticesFor::none`) but +/// where it calls an encoder. Every call of the program's code goes through here. In builds with +/// debug assertions (every test run), end the process where this thread is inside a passing hold +/// of a device's resources, which a making on another thread may wait for (`resource_ids.rs`): +/// `f` may wait for that making. pub(crate) fn program(f: impl FnOnce()) { if cfg!(debug_assertions) && crate::resource_ids::inside_passing_hold() { let name = std::thread::current().name().map(str::to_owned); @@ -1268,7 +1269,9 @@ pub(crate) fn program(f: impl FnOnce()) { } PROGRAM.with(|program| program.set(program.get() + 1)); let base = BASE.with(|base| base.replace(OWN.with(Cell::get))); + let program = crate::degradation::NoticesFor::none(); let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)); + drop(program); BASE.with(|outer| outer.set(base)); PROGRAM.with(|program| program.set(program.get() - 1)); } diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index 8ac56b5f7..b80a3ccbe 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -65,7 +65,7 @@ use super::address::{AddressPlacement, Place, RecordsId}; use super::buffer::{Buffer, Modes}; -use super::degradation::Degradation; +use super::degradation::{Degradation, NoticesFor}; use super::depth_stencil::DepthStencilState; use super::device::lock; use super::error::{internal, invalid, Error, MemoryKind, Problem, RuntimeGap}; @@ -2325,6 +2325,8 @@ impl IndirectCommandBuffer { .map(|(&(index, record), set)| (index, record, set.as_ref())); let commands = self.getter_commands(read); let mut check = lock(check); + // The program's code: no command buffer's work of the runtime's. + let _program = NoticesFor::none(); for (&(index, _), command) in held.iter().zip(&commands) { check(u64::from(index), command); } diff --git a/crates/metal2vulkan-runtime/src/predication.rs b/crates/metal2vulkan-runtime/src/predication.rs index 874e89ca2..3ba344fc0 100644 --- a/crates/metal2vulkan-runtime/src/predication.rs +++ b/crates/metal2vulkan-runtime/src/predication.rs @@ -1957,6 +1957,7 @@ impl ComputeCommandEncoder { /// for the End that closes that block; with no block open it is an unbalanced record, /// answering `NO` (the module docs). pub fn encode_end_if(&mut self) -> Result { + let _for = self.core().notices_for(); let at = self.log(|_| ComputeCall::EndIf(false)); let result = self.encode_end_if_uncounted(); let result = self.counted(result); @@ -1997,6 +1998,7 @@ impl ComputeCommandEncoder { comparison: u64, reference_value: u32, ) -> Result<(), Error> { + let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_start_while_uncounted(buffer, offset, comparison, reference_value); self.counted(result) @@ -2033,6 +2035,7 @@ impl ComputeCommandEncoder { /// run, and again while that End's condition holds after each run, as /// [`encode_start_while`](Self::encode_start_while)'s run, laid down as there. pub fn encode_start_do_while(&mut self) -> Result<(), Error> { + let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_start_do_while_uncounted(); self.counted(result) @@ -2048,6 +2051,7 @@ impl ComputeCommandEncoder { /// block it kills the outermost open block and answers `NO`; with no block open it is an /// unbalanced record, answering `NO` (the module docs). pub fn encode_end_while(&mut self) -> Result { + let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_end_while_uncounted(); self.counted(result) @@ -2076,6 +2080,7 @@ impl ComputeCommandEncoder { comparison: u64, reference_value: u32, ) -> Result { + let _for = self.core().notices_for(); self.stop_logging(); let result = self.encode_end_do_while_uncounted(buffer, offset, comparison, reference_value); diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 5182e9d42..e03651302 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -1950,6 +1950,7 @@ impl Lowering { /// The lowering of [`RenderCommandEncoder::end_encoding`] (`RenderLowering::end_encoding`). pub(crate) fn end_encoding(self) -> Result<(), Error> { + let _for = self.core.notices_for(); self.ending().end_encoding() } @@ -1973,6 +1974,7 @@ impl CommandBuffer { &self, descriptor: &RenderPassDescriptor, ) -> Result { + let _for = self.notices_for(); // The last render encoder's end, where its call left it to the device's lowering thread. self.settle_end(); // Metal's process ends here under some protection options (`command_buffer/protection.rs`). diff --git a/crates/metal2vulkan-runtime/src/render/deferral.rs b/crates/metal2vulkan-runtime/src/render/deferral.rs index 8afac5864..d1b06ae6c 100644 --- a/crates/metal2vulkan-runtime/src/render/deferral.rs +++ b/crates/metal2vulkan-runtime/src/render/deferral.rs @@ -142,6 +142,7 @@ impl Batch { if self.calls.calls.is_empty() || *refused { return; } + let _for = lowering.core.notices_for(); let counts = &lowering.core.device().shared().counts; counts.render_log_batch_lowered(by_thread); lowering.core.judges_unattached(true); @@ -781,11 +782,15 @@ impl RenderCommandEncoder { /// does. pub(crate) fn at_call_unit(&mut self, f: impl FnOnce(&mut Lowering)) { self.next += 1; + let lowered = |lowering: &mut Lowering| { + let _for = lowering.core.notices_for(); + f(lowering); + }; match (&mut self.own, &self.logged) { - (Some(lowering), _) => f(lowering), + (Some(lowering), _) => lowered(lowering), (None, Some(logged)) => { if let Some(lowering) = lock(&logged.slot.lowerer).lowering.as_mut() { - f(lowering); + lowered(lowering); } } (None, None) => {} diff --git a/crates/metal2vulkan-runtime/src/render/replay.rs b/crates/metal2vulkan-runtime/src/render/replay.rs index bff1a99f3..902000a62 100644 --- a/crates/metal2vulkan-runtime/src/render/replay.rs +++ b/crates/metal2vulkan-runtime/src/render/replay.rs @@ -681,6 +681,7 @@ impl Lowering { &mut self, run: impl FnOnce(&mut Lowering) -> Result, ) -> Result { + let _for = self.core.notices_for(); let at = self.log.as_ref().map(|log| log.calls.calls.len()); let ran = run(self); if let (Err(_), Some(at), Some(log)) = (&ran, at, &mut self.log) { diff --git a/crates/metal2vulkan-runtime/src/resource.rs b/crates/metal2vulkan-runtime/src/resource.rs index 9ed2867e7..ae75e247e 100644 --- a/crates/metal2vulkan-runtime/src/resource.rs +++ b/crates/metal2vulkan-runtime/src/resource.rs @@ -23,13 +23,13 @@ impl ResourceKey { } } -/// A buffer's, texture's or heap's identity (`Buffer::object_id`, `Texture::object_id`, -/// `Heap::object_id`): a runtime extension, no Metal type. Metal names an object by its pointer -/// (`id`), which another object may take once it is freed, and by nothing else where it has no -/// address (a sparse heap's `gpuAddress` is 0). This number is unique among the process's -/// buffers, textures and heaps, is the object's for its whole life (a clone is the same object), -/// and is never given to another, so a program can key what it knows of an object by it without -/// holding the object. +/// A buffer's, texture's, heap's or command buffer's identity (`Buffer::object_id`, +/// `Texture::object_id`, `Heap::object_id`, `CommandBuffer::object_id`): a runtime extension, no +/// Metal type. Metal names an object by its pointer (`id`), which another object may take once it +/// is freed, and by nothing else where it has no address (a sparse heap's `gpuAddress` is 0). +/// This number is unique among the process's buffers, textures, heaps and command buffers, is the +/// object's for its whole life (a clone is the same object), and is never given to another, so a +/// program can key what it knows of an object by it without holding the object. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ObjectId(u64); diff --git a/crates/metal2vulkan-runtime/src/sparse/encoder.rs b/crates/metal2vulkan-runtime/src/sparse/encoder.rs index 823ba3d25..99c548323 100644 --- a/crates/metal2vulkan-runtime/src/sparse/encoder.rs +++ b/crates/metal2vulkan-runtime/src/sparse/encoder.rs @@ -81,6 +81,7 @@ impl CommandBuffer { /// Refused as every encoder is: the command buffer committed, or an encoder open or abandoned /// (`Invalid`). pub fn resource_state_command_encoder(&self) -> Result { + let _for = self.notices_for(); // The last render encoder's end, where its call left it to the device's lowering thread. self.settle_end(); self.refuse_protected_state_encoder()?; @@ -147,6 +148,7 @@ impl ResourceStateCommandEncoder { level: u64, slice: u64, ) -> Result<(), Error> { + let _for = self.open.command_buffer.notices_for(); self.update_texture_mappings(texture, mode, &[region], &[level], &[slice]) } @@ -163,6 +165,7 @@ impl ResourceStateCommandEncoder { levels: &[u64], slices: &[u64], ) -> Result<(), Error> { + let _for = self.open.command_buffer.notices_for(); const CALL: &str = "update_texture_mappings"; if levels.len() != regions.len() || slices.len() != regions.len() { return Err(invalid(CALL, Problem::Sparse(SparseProblem::Lengths))); @@ -227,6 +230,7 @@ impl ResourceStateCommandEncoder { indirect_buffer: &Buffer, indirect_buffer_offset: u64, ) -> Result<(), Error> { + let _for = self.open.command_buffer.notices_for(); const CALL: &str = "update_texture_mapping_indirect"; let offset = indirect_buffer_offset - indirect_buffer_offset % 4; if !indirect_buffer @@ -329,6 +333,7 @@ impl ResourceStateCommandEncoder { destination_level: u64, destination_origin: Origin, ) -> Result<(), Error> { + let _for = self.open.command_buffer.notices_for(); const CALL: &str = "move_texture_mappings"; let (from, to) = match (self.sparse(CALL, source)?, self.sparse(CALL, destination)?) { (Some(from), Some(to)) => (from, to), @@ -365,6 +370,7 @@ impl ResourceStateCommandEncoder { /// /// Refused (`Invalid`): a fence of another device. pub fn update_fence(&mut self, fence: &Fence) -> Result<(), Error> { + let _for = self.open.command_buffer.notices_for(); if !fence.device().same(self.open.command_buffer.device()) { return Err(fence .device() @@ -385,6 +391,7 @@ impl ResourceStateCommandEncoder { /// /// Refused (`Invalid`): a fence of another device. pub fn wait_for_fence(&mut self, fence: &Fence) -> Result<(), Error> { + let _for = self.open.command_buffer.notices_for(); const CALL: &str = "wait_for_fence"; if !fence.device().same(self.open.command_buffer.device()) { return Err(fence @@ -404,6 +411,7 @@ impl ResourceStateCommandEncoder { /// `endEncoding`: the updates go to the command buffer, in a batch that binds them before /// the encoders after this one. pub fn end_encoding(self) -> Result<(), Error> { + let _for = self.open.command_buffer.notices_for(); let ResourceStateCommandEncoder { mut open, updates, diff --git a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs index e70d81cd5..9e668e1a8 100644 --- a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs +++ b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs @@ -373,8 +373,9 @@ const POINTS: EncoderCall = EncoderCall { }; /// A notice announced while a call is lowered names it under `Worker`, and none under `AtCall`, -/// where the call lowers itself; with no kind refused (the default) it reaches the sink and the -/// command buffer runs. +/// where the call lowers itself, and names the call's command buffer under both +/// (`DegradeNotice::command_buffer`); with no kind refused (the default) it reaches the sink and +/// the command buffer runs. #[test] fn a_notice_announced_as_a_call_is_lowered_names_it() { let scratch = Scratch::new("deferred-notice"); @@ -403,9 +404,83 @@ fn a_notice_announced_as_a_call_is_lowered_names_it() { _ => None, }; assert_eq!(notice.call, named, "{policy:?}"); + assert_eq!( + notice.command_buffer, + Some(command_buffer.object_id()), + "{policy:?}" + ); } } +/// Under `Worker`, a notice the device's lowering thread announces as it lowers a logged call, +/// after the encoder's end returned and before the program makes any other call, names the call +/// and its command buffer (`DegradeNotice::command_buffer`), not another command buffer the program +/// holds; a notice the device announces between two calls of the encoder, for a resource it makes +/// (`private-resource-option`, an indirect command buffer of Metal's private option bit), names +/// none. +#[test] +fn a_notice_the_lowering_thread_announces_names_its_command_buffer() { + let scratch = Scratch::new("deferred-notice-thread"); + let heard: Arc)>>> = Arc::default(); + let device = device_with(&scratch.0, &Heard::default(), |options| { + options.policy.render_lowering = RenderLoweringPolicy::Worker; + let heard = Arc::clone(&heard); + options.messages = Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + heard.lock().unwrap().push((notice.clone(), thread_name())); + } + })); + }); + let state = rectangle_state(&device); + let queue = device.new_command_queue().unwrap(); + let other = queue.command_buffer().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + assert_ne!(other.object_id(), command_buffer.object_id()); + let target = target(&device); + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + rectangle(&state, &mut encoder); + // A resource made between the encoder's calls: the device's notice, no command buffer's. + let options = ResourceOptions::shared().raw() | ResourceOptions::PRIVATE_BIT; + let mut commands = crate::IndirectCommandBufferDescriptor::new(); + commands.command_types = metal2vulkan::metal::IndirectCommandType::CONCURRENT_DISPATCH_THREADS; + commands.max_kernel_buffer_bind_count = 1; + let _private = device + .new_indirect_command_buffer(&commands, 1, ResourceOptions::from_raw(options).unwrap()) + .unwrap(); + let color = bytes_of(&COLOR, f32::to_le_bytes); + encoder.set_fragment_bytes(&color, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Point, 0, 4, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + // No call of the program's lowers the draw: the lowering thread does. + let find = |kind: Degradation| { + let heard = heard.lock().unwrap(); + (heard.iter()) + .find(|(notice, _)| notice.degradation == kind) + .cloned() + }; + let deadline = Instant::now() + WAIT; + let (points, on) = loop { + if let Some(found) = find(Degradation::UnsizedPoints) { + break found; + } + assert!(Instant::now() < deadline, "no notice of unsized points"); + std::thread::sleep(Duration::from_millis(1)); + }; + assert_eq!(on.as_deref(), Some("metal2vulkan-lowering")); + assert_eq!(points.call, Some(POINTS)); + assert_eq!(points.command_buffer, Some(command_buffer.object_id())); + let (private, _) = find(Degradation::PrivateResourceOption).expect("private-resource-option"); + assert_eq!(private.command_buffer, None); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + drop(other); +} + /// A kind the device refuses while lowering (`lowering_refuses`) refuses the call it is announced /// at under `Worker`: the call returned, the notice reaches no sink, and the command buffer fails /// naming it (`CallRefused`), the notice its error, the encoder and the one after it running diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 58306d1d0..2817170ef 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -283,6 +283,8 @@ mod neutral_zeros_shared; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod no_copy_lies; mod noted_apart; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod notice_command_buffers; mod numbered_samplers; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod opencl_kernels; diff --git a/crates/metal2vulkan-runtime/src/tests/notice_command_buffers.rs b/crates/metal2vulkan-runtime/src/tests/notice_command_buffers.rs new file mode 100644 index 000000000..ea5fbf603 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/notice_command_buffers.rs @@ -0,0 +1,159 @@ +//! A degrade notice names the command buffer whose work announced it +//! (`DegradeNotice::command_buffer`, `CommandBuffer::object_id`), on whichever thread the work +//! runs: an indirect command buffer's execution recorded at a host step on the scheduler's steps +//! thread announces `released-command-state` there naming the executing command buffer, its commit +//! announces `host-replayed-indirect-commands` on the program's thread naming it too, and a notice +//! of the device's (`private-resource-option`, a buffer of commands made while another command +//! buffer's encoder is open) names none. +//! +//! A device test: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. The kernel is `scale_and_offset` of the owned fixture +//! `validation/fixtures/public/examples/runtime_examples.ll` (`llvm-as`). + +use super::blit_holds::{Scratch, WAIT}; +use super::encoder_holds::library; +use crate::write_routes::GpuWriter; +use crate::{ + CommandBufferStatus, ComputePipelineState, Degradation, DegradeNotice, Device, DeviceKind, + DeviceOptions, IndirectCommandBufferDescriptor, MessageSink, PipelineOptions, ResourceOptions, + ShaderCacheOptions, Size, +}; +use metal2vulkan::metal::IndirectCommandType; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; +use std::path::Path; +use std::sync::{Arc, Mutex}; +use std::thread::ThreadId; + +/// What the sink heard: each notice, with the thread that announced it and whether that thread +/// was recording a host step then. +type Heard = Arc>>; + +/// The threads each dispatch runs. +const COUNT: u32 = 64; + +/// A device of the kind the cfg selects, its shader cache in `cache`, its notices into `heard`. +fn device(cache: &Path, heard: &Heard) -> Device { + let heard = Arc::clone(heard); + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![ + DeviceKind::Discrete, + DeviceKind::Integrated, + DeviceKind::Virtual, + ], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + messages: Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + let step = crate::exit_guard::in_host_step(); + let thread = std::thread::current().id(); + heard.lock().unwrap().push((notice.clone(), thread, step)); + } + })), + ..DeviceOptions::default() + }; + Device::system_default_with(&options).unwrap() +} + +/// A state of `scale_and_offset` that an indirect command buffer's commands may set. +fn state(device: &Device) -> ComputePipelineState { + let function = library(device, "examples/runtime_examples.ll") + .new_function_with_name("scale_and_offset") + .unwrap(); + let mut descriptor = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + descriptor.support_indirect_command_buffers = true; + device + .new_compute_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap() +} + +/// A command buffer executes a buffer of commands whose records the GPU may write, its one command +/// set to a state the program released after another state took its ID: the commit leaves the +/// execution to a host step, whose recording cannot tell whether the GPU wrote the released +/// state's ID while the other held it (`Unmatched::Unsure`) and announces +/// `released-command-state`. Both that notice, heard at the host step on a thread other than the +/// program's, and the commit's `host-replayed-indirect-commands`, heard on the program's thread +/// outside any host step, name the executing command buffer, not the one made before it; the +/// device's `private-resource-option`, of a buffer of commands made while the executing command +/// buffer's encoder is open, names none. +#[test] +fn notices_name_the_command_buffer_whose_work_announced_them() { + let scratch = Scratch::new("notice-command-buffers"); + let heard = Heard::default(); + let device = device(&scratch.0, &heard); + let shared = ResourceOptions::shared(); + let input: Vec = (0..COUNT).flat_map(|i| (i as f32).to_le_bytes()).collect(); + let input = device.new_buffer_with_bytes(&input, shared).unwrap(); + let output = device.new_buffer(u64::from(COUNT) * 4, shared).unwrap(); + let scale = device + .new_buffer_with_bytes(&2.0f32.to_le_bytes(), shared) + .unwrap(); + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::CONCURRENT_DISPATCH_THREADS; + descriptor.max_kernel_buffer_bind_count = 3; + let icb = device + .new_indirect_command_buffer(&descriptor, 1, shared) + .unwrap(); + let released = state(&device); + let command = icb.indirect_compute_command_at(0).unwrap(); + command.set_compute_pipeline_state(&released).unwrap(); + for (index, buffer) in (0..).zip([&input, &output, &scale]) { + command.set_kernel_buffer(Some(buffer), 0, index).unwrap(); + } + let (grid, group) = ( + Size::new(u64::from(COUNT), 1, 1), + Size::new(COUNT.into(), 1, 1), + ); + command.concurrent_dispatch_threads(grid, group).unwrap(); + // The program releases the state, another takes its ID, and then the GPU may write the + // records: one may name the ID as the other held it. + let id = released.gpu_resource_id(); + drop(released); + let holder = state(&device); + assert_eq!(holder.gpu_resource_id(), id); + icb.written_by_gpu(GpuWriter::Reset); + drop(icb.gpu_write()); + + let queue = device.new_command_queue().unwrap(); + let before = queue.command_buffer().unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let id = command_buffer.object_id(); + assert_ne!(before.object_id(), id); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + // The device's notice, made between the encoder's calls. + let private = ResourceOptions::from_raw(shared.raw() | ResourceOptions::PRIVATE_BIT).unwrap(); + let _private = device + .new_indirect_command_buffer(&descriptor, 1, private) + .unwrap(); + encoder.execute_commands_in_buffer(&icb, 0..1).unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + + let program = std::thread::current().id(); + let heard = heard.lock().unwrap(); + let find = |kind: Degradation| { + (heard.iter()) + .find(|(notice, ..)| notice.degradation == kind) + .unwrap_or_else(|| panic!("no {}: {heard:?}", kind.code())) + }; + let (notice, thread, step) = find(Degradation::ReleasedCommandState); + assert!(*step, "released-command-state outside a host step"); + assert_ne!(*thread, program, "a host step on the program's thread"); + assert_eq!(notice.command_buffer, Some(id), "{notice:?}"); + let (notice, thread, step) = find(Degradation::HostReplayedIndirectCommands); + assert!( + !*step && *thread == program, + "the commit's notice elsewhere" + ); + assert_eq!(notice.command_buffer, Some(id), "{notice:?}"); + let (notice, ..) = find(Degradation::PrivateResourceOption); + assert_eq!(notice.command_buffer, None, "{notice:?}"); + drop(before); +} diff --git a/crates/metal2vulkan-runtime/src/tests/vertex_conversion_notices.rs b/crates/metal2vulkan-runtime/src/tests/vertex_conversion_notices.rs index 888283950..09d736c85 100644 --- a/crates/metal2vulkan-runtime/src/tests/vertex_conversion_notices.rs +++ b/crates/metal2vulkan-runtime/src/tests/vertex_conversion_notices.rs @@ -21,10 +21,11 @@ use super::blit_holds::{Scratch, WAIT}; use super::encoder_holds::{library, words_of}; use crate::{ - CommandBufferStatus, Degradation, DegradeNotice, Device, DeviceKind, DeviceOptions, Library, - MessageSink, PipelineOptions, RenderPassDescriptor, RenderPipelineState, ResourceOptions, - ShaderCacheOptions, + CommandBufferStatus, Degradation, DegradeNotice, Device, DeviceKind, DeviceOptions, + EncoderCall, Library, MessageSink, PipelineOptions, RenderPassDescriptor, RenderPipelineState, + ResourceOptions, ShaderCacheOptions, }; +use metal2vulkan::device::RenderLoweringPolicy; use metal2vulkan::error::DriverDeviation; use metal2vulkan::metal::{PrimitiveType, VertexFormat}; use metal2vulkan::pipeline::{ @@ -46,6 +47,11 @@ type Heard = Arc>>; /// A device of the kind the cfg selects, with an empty shader cache of its own, that announces /// [`NOTES`] at every occurrence, its notices into `heard`. fn device(cache: &Path, heard: &Heard) -> Device { + device_lowering(cache, heard, RenderLoweringPolicy::AtCall) +} + +/// [`device`], lowering render calls as `lowering` says. +fn device_lowering(cache: &Path, heard: &Heard, lowering: RenderLoweringPolicy) -> Device { let heard = Arc::clone(heard); let options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { @@ -68,6 +74,8 @@ fn device(cache: &Path, heard: &Heard) -> Device { announce_each: NOTES.into_iter().collect(), ..DeviceOptions::default() }; + let mut options = options; + options.policy.render_lowering = lowering; Device::system_default_with(&options).unwrap() } @@ -190,3 +198,64 @@ fn a_state_announces_its_formats_conversions_from_one_translation() { assert_eq!(&kinds, want, "{format:?}"); } } + +/// A bind's notice made once and announced at each later bind of the same variant (the +/// variant's `half` attribute's `device-nan-encoding`, asked for at every occurrence) names, at +/// each, the command buffer and the logged call of that bind, under `Worker`: a second command +/// buffer's draw, a call later in its encoder than the first's, is named as its own though its +/// notice was made at the first's bind. +#[test] +fn a_bind_s_notice_names_its_own_command_buffer_and_call() { + let scratch = Scratch::new("vertex-conversion-binds"); + let heard = Heard::default(); + let device = device_lowering(&scratch.0, &heard, RenderLoweringPolicy::Worker); + let library = library(&device, "engine/dsx_int_attributes.ll"); + let state = state(&device, &library, VertexFormat::Half4); + let out = device.new_buffer(16, ResourceOptions::default()).unwrap(); + let mut pass = RenderPassDescriptor::new(); + pass.render_target_width = 1; + pass.render_target_height = 1; + pass.default_raster_sample_count = 1; + let queue = device.new_command_queue().unwrap(); + // The draw of each command buffer, after `extra` repeated binds of buffer 0. + let drawn = |extra: usize| { + 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_bytes(&[0x7f; 16], 1).unwrap(); + for _ in 0..=extra { + encoder.set_vertex_buffer(Some(&out), 0, 0).unwrap(); + } + 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(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + let call = EncoderCall { + selector: "drawPrimitives:vertexStart:vertexCount:instanceCount:baseInstance:", + index: 3 + extra as u32, + }; + (command_buffer, call) + }; + let first = drawn(0); + let made = device.work_counts().bound_notices_made; + let second = drawn(1); + assert_eq!( + device.work_counts().bound_notices_made, + made, + "the second bind made its notices again: the naming below proves nothing" + ); + let mut named: Vec<_> = (heard.lock().unwrap().iter()) + .filter(|notice| notice.degradation == Degradation::DeviceNanEncoding) + .map(|notice| (notice.command_buffer, notice.call)) + .collect(); + // A bind may take a variant's pipeline twice; each names its own draw. + named.dedup(); + let expected: Vec<_> = [&first, &second] + .iter() + .map(|(command_buffer, call)| (Some(command_buffer.object_id()), Some(*call))) + .collect(); + assert_eq!(named, expected); +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 67a742826..8af3838c3 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2029,6 +2029,7 @@ field metal2vulkan-runtime::DebugMessage.kind pub kind: MessageKind field metal2vulkan-runtime::DebugMessage.severity pub severity: MessageSeverity field metal2vulkan-runtime::DebugMessage.text pub text: String field metal2vulkan-runtime::DegradeNotice.call pub call: Option +field metal2vulkan-runtime::DegradeNotice.command_buffer pub command_buffer: Option field metal2vulkan-runtime::DegradeNotice.cost pub cost: &'static str field metal2vulkan-runtime::DegradeNotice.degradation pub degradation: Degradation field metal2vulkan-runtime::DegradeNotice.misplaced pub misplaced: Option @@ -7862,6 +7863,7 @@ method metal2vulkan-runtime::CommandBuffer::gpu_end_time pub fn gpu_end_time(&se method metal2vulkan-runtime::CommandBuffer::gpu_start_time pub fn gpu_start_time(&self) -> Result method metal2vulkan-runtime::CommandBuffer::kernel_end_time pub fn kernel_end_time(&self) -> f64 method metal2vulkan-runtime::CommandBuffer::kernel_start_time pub fn kernel_start_time(&self) -> f64 +method metal2vulkan-runtime::CommandBuffer::object_id pub fn object_id(&self) -> ObjectId method metal2vulkan-runtime::CommandBuffer::refusal pub fn refusal(&self) -> Option method metal2vulkan-runtime::CommandBuffer::render_command_encoder pub fn render_command_encoder(&self, descriptor: &RenderPassDescriptor) -> Result method metal2vulkan-runtime::CommandBuffer::resource_state_command_encoder pub fn resource_state_command_encoder(&self) -> Result diff --git a/docs/API.md b/docs/API.md index 75219ee0c..e79b84e52 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1537,6 +1537,16 @@ How a notice reaches you: - A notice announced while a render encoder lowers a call it logged names that call (`DegradeNotice::call`: its Metal selector and its index among the encoder's calls); `None` elsewhere. +- A notice announced while the runtime does one command buffer's work names that command buffer + (`DegradeNotice::command_buffer`, its `CommandBuffer::object_id`), so a program can fail that + command buffer rather than end the process: its encoders' calls and their lowering on the + lowering thread, an encoder's opening, its commit (at the call, or once a render encoder's end + it waited for was lowered), the submission of its batches, its host steps on the scheduler's + steps thread (an indirect command buffer's execution recorded there among them), its encoders + encoded again at a rebind, and a read of its GPU times. `None` for the rest: the device's, a + library's, a pipeline state's, a resource's or a queue's notices outside a command buffer's + work, one about several command buffers' batches together (`grouped-completion`), and a + recovery of the device's (`device-recovered`). - Decode a notice by its `Degradation` or its code, never its text. The codes are a contract: none is renamed. - `Degradation::exactness()` says whether the program still gets Metal's answer: `Exact` (most diff --git a/docs/RUNTIME-PORTING.md b/docs/RUNTIME-PORTING.md index f0cdff487..d016dcff4 100644 --- a/docs/RUNTIME-PORTING.md +++ b/docs/RUNTIME-PORTING.md @@ -153,7 +153,7 @@ narrow refusal that the call's rustdoc describes. | `commit_and_submit` | (none: a runtime extension) | `CommandBuffer::commit_and_submit`: `commit`, then the calling thread submits the ready command buffers in commit order, this one among them (one held back holding back only the later commits that wait behind it, as on the scheduler's thread), where no other pass is under way and each needs no host step or storage-form switch, running their submission checks just before each submission (one that waits for a shared event's GPU signal to land is left to the scheduler's thread; a plain event's wait goes to the `VkQueue`) and their submission handlers inside the call; the rest goes to the scheduler's thread. One left for a render encoder's end (`RenderLoweringPolicy::Worker`) returns as `commit` does, and the thread that runs its commit once the end is lowered makes the pass | | `add_completion_seen_handler` | (none: a runtime extension) | `CommandBuffer::add_completion_seen_handler`: a handler run once the command buffer completed, its status and GPU times final, on the runtime's thread that saw it complete where its transition to `Completed` runs there, or runs to its completion-seen handlers there (one with completed handlers, the rest on its queue's handler thread), else on its queue's handler thread, before its completed handlers; short, and never blocking | | `set_submission_check` | (none: a runtime extension) | `CommandBuffer::set_submission_check`: a check of each of Metal's submissions of the command buffer, run once its event waits are met (an `Event` wait for a submitted signal at once, its wait on the `VkQueue`; a `SharedEvent` wait only a GPU signal still running reaches once that signal lands, as Metal schedules each), just before it is submitted, on the thread that submits it (the device's scheduler thread, or one in `commit_and_submit` or making the pass of one left for a render encoder's end); a code it answers fails that submission alone, as Metal fails one that uses a resource detached by then | -| `object_id` | (none: Metal names an object by pointer) | `Buffer::object_id`, `Texture::object_id`, `Heap::object_id`: an `ObjectId` unique for the object's life, never reused (a sparse heap's `gpu_address` is 0) | +| `object_id` | (none: Metal names an object by pointer) | `Buffer::object_id`, `Texture::object_id`, `Heap::object_id`, `CommandBuffer::object_id`: an `ObjectId` unique for the object's life, never reused (a sparse heap's `gpu_address` is 0); a degrade notice announced for a command buffer's work names its command buffer's (`DegradeNotice::command_buffer`) | ### `ComputeCmd`: `MTLComputeCommandEncoder` commands