diff --git a/crates/metal2vulkan-harness/src/rt.rs b/crates/metal2vulkan-harness/src/rt.rs index 9ae9c386c..ddd5f9047 100644 --- a/crates/metal2vulkan-harness/src/rt.rs +++ b/crates/metal2vulkan-harness/src/rt.rs @@ -657,7 +657,7 @@ impl crate::CommandBuffer for rt::CommandBuffer { } fn wait_until_completed(&self) -> Result<()> { - rt::CommandBuffer::wait_until_completed(self); + rt::CommandBuffer::wait_until_completed(self).map_err(error)?; match self.status() { rt::CommandBufferStatus::Completed => Ok(()), status => { diff --git a/crates/metal2vulkan-rt/README.md b/crates/metal2vulkan-rt/README.md index e04f0fd03..93ba32863 100644 --- a/crates/metal2vulkan-rt/README.md +++ b/crates/metal2vulkan-rt/README.md @@ -54,7 +54,8 @@ Teardown stops the submit thread, which submits what is ready and ends what it h `CommandBufferError::NotRun`; the completion thread retires the rest as the GPU completes it and runs the handlers; the threads are joined and the GPU goes idle; `BlockMappings::unmap` runs for each block the consumer was handed. Teardown runs on the thread that drops the last handle, or, -where that is a handler or a listener, on the reaper once the handler returns. A call that holds a +where that is a handler (scheduled or completed) or a listener, on the reaper once the handler +returns. A call that holds a handle of its own gives it up before another thread can drop the last: `commit` gives up the command buffer's before the command buffer can complete. Then every block is freed and the `VkDevice` destroyed, once the runtime's last internal reference is gone: on the thread that tore @@ -626,10 +627,23 @@ made, with no lock, and never rewritten for layouts. buffer before it, in flight, or at once where that one has completed. Where that one is in a group held, it joins the group, which goes at once, so its completion waits only on submitted work. +- A command buffer's scheduled handlers run on the submit thread, once it is scheduled and before + its submission goes to the driver (one that ends without a submission: once it ends, before it + retires), with no lock of the runtime's held. In the handler its status is `Scheduled` and its + kernel times are set, and it runs before the command buffer's completed handlers. The queue's + later submissions wait while it runs, and it may run while another command buffer's completed + handler runs on the completion thread. A scheduled handler may read the command buffer's status + and times, enqueue command buffers, make objects that take no upload, and do the consumer's own + work. Each call that may wait for the submit thread is `Refusal::InScheduledHandler` in it, on + every device: `commit`, the waits (`wait_until_scheduled`, `wait_until_completed`, + `wait_until_signaled_value`), the uploads and readbacks (`replace_region`, `upload_region`, + `get_bytes`, `zero_block_range`), and the objects that take an upload (`new_managed_buffer`, and + `new_buffer` zeroing a buffer in a Private block). Metal runs a scheduled handler on a thread of + its own, where those calls run. The submit thread wakes no other thread for a scheduled handler. - The completion thread retires command buffers as the progress semaphore reaches them, a submission's in commit order: the status, the blocks they kept, their recorders and their place - in the queue, then the handlers. Scheduled and completed handlers run on it, every device's in - turn, so no handler waits for a command buffer. A command buffer of a group is seen complete + in the queue, then the completed handlers. Completed handlers and listeners run on it, every + device's in turn, so no completed handler waits for a command buffer. A command buffer of a group is seen complete with the group's last: up to the GPU time of the fifteen after it late. Only a queue already three submissions behind holds a group; one whose submissions have completed sends its next command buffer alone. Without a wait or a hint, the lateness is bounded only while three submissions are @@ -695,8 +709,9 @@ bounded by the timeout, it stops the submit thread (ready work is submitted, hel completion thread retire it and end, and then runs `BlockMappings::unmap` on the calling thread for every block still handed out. It frees nothing: every block's memory and mapping stays valid until the process ends. After it, no runtime thread touches a block; later calls that need a thread -return `Error::Quiesced`. It answers true once the GPU went idle and every thread ended in time. A -second call returns at once. +return `Error::Quiesced`. It answers true once the GPU went idle and every thread ended in time, +and false at once in a handler or a listener, whose thread cannot wait for itself. A second call +returns at once. The consumer quiesces before it calls `exit()`. Quiesce can also run in an `atexit` handler, on whichever thread calls `exit()`: it joins a thread only once that thread has ended, reads no diff --git a/crates/metal2vulkan-rt/src/buffer.rs b/crates/metal2vulkan-rt/src/buffer.rs index 989a4407e..548c86688 100644 --- a/crates/metal2vulkan-rt/src/buffer.rs +++ b/crates/metal2vulkan-rt/src/buffer.rs @@ -112,8 +112,9 @@ impl Device { /// Err: [`Refusal::EmptyBuffer`] for a length of 0, [`Refusal::BufferTooLong`] for a length /// past [`MAX_BUFFER_LENGTH`] and [`Refusal::BufferPastBlock`] for a range that leaves the /// block, where Metal answers nil; [`Error::NoSuchBlock`] for a block the - /// consumer does not hold; for a zeroed Private buffer, [`Error::Quiesced`], and - /// [`Error::Vulkan`] where the upload's command buffer cannot be made. + /// consumer does not hold; for a zeroed Private buffer, [`Refusal::InScheduledHandler`] in a + /// scheduled handler, [`Error::Quiesced`], and [`Error::Vulkan`] where the upload's command + /// buffer cannot be made. pub fn new_buffer( &self, block: BlockId, @@ -131,6 +132,10 @@ impl Device { })); } let block = self.placed(block, offset, length)?; + if block.memory.class == MemoryClass::Private && zero_from.is_some_and(|from| from < length) + { + crate::command::not_in_scheduled_handler()?; + } let end = offset + length; let contents = block.memory.mapping.map(|mapping| { // SAFETY: `offset` is inside the block. @@ -190,7 +195,8 @@ impl Device { /// counted in [`Gauges::managed_spilled_bytes`](crate::Gauges::managed_spilled_bytes) while the /// buffer lives. /// - /// Err: as [`Device::new_buffer`], for either range; [`Refusal::ManagedBlockNotShared`] for + /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler, on every device; as + /// [`Device::new_buffer`], for either range; [`Refusal::ManagedBlockNotShared`] for /// bytes in a block the host does not map; [`Refusal::ManagedCopyMissing`] for no `copy` where /// the device keeps one, [`Refusal::ManagedCopyOnUnified`] for a `copy` where it keeps none /// and [`Refusal::ManagedCopyNotPrivate`] for a `copy` in a Shared block; for a device copy, @@ -203,6 +209,7 @@ impl Device { length: u64, copied: u64, ) -> Result { + crate::command::not_in_scheduled_handler()?; if length == 0 { return Err(Error::Refused(Refusal::EmptyBuffer)); } @@ -296,12 +303,14 @@ impl Device { /// [`Metrics::block_zero_fill_bytes`](crate::Metrics::block_zero_fill_bytes) count the fills /// and their bytes. A length of 0 zeroes nothing. /// - /// Err: [`Error::NoSuchBlock`] for a block the consumer does not hold; - /// [`Refusal::ZeroRangePastBlock`] for a range that leaves the block; + /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler; [`Error::NoSuchBlock`] for a + /// block the consumer does not hold; [`Refusal::ZeroRangePastBlock`] for a range that leaves + /// the block; /// [`Refusal::ZeroRangeShared`] for a Shared block, whose bytes the consumer writes through /// the mapping; [`Error::Quiesced`], and [`Error::Vulkan`] where the upload's command buffer /// cannot be made. pub fn zero_block_range(&self, block: BlockId, offset: u64, length: u64) -> Result<(), Error> { + crate::command::not_in_scheduled_handler()?; let block = self.block(block)?; let block_len = block.memory.len; let end = offset diff --git a/crates/metal2vulkan-rt/src/command.rs b/crates/metal2vulkan-rt/src/command.rs index c143af222..6ad0ab74f 100644 --- a/crates/metal2vulkan-rt/src/command.rs +++ b/crates/metal2vulkan-rt/src/command.rs @@ -397,8 +397,20 @@ impl CommandBuffer { }) } - /// `addScheduledHandler:`: runs on the completion thread once the last segment has passed - /// `vkQueueSubmit2`, or at once there for a command buffer that ends without running. + /// `addScheduledHandler:`: runs on the submit thread once the command buffer is scheduled, + /// before its submission goes to the driver, or for one that ends without running once it + /// ends, before it retires. In the handler the command buffer's status is + /// [`CommandBufferStatus::Scheduled`] and its kernel times are set, and it runs before the + /// command buffer's completed handlers. Its queue's later submissions wait while it runs, and + /// it may run while another command buffer's completed handler runs on the completion thread. + /// + /// A scheduled handler may read the command buffer's status and times, enqueue command + /// buffers, make objects that take no upload, and do the consumer's own work. Each call that + /// may wait for the submit thread is [`Refusal::InScheduledHandler`] in it, on every device: + /// [`commit`](Self::commit), the waits, the uploads and readbacks, and the objects that take + /// an upload. [`Device::quiesce`](crate::Device::quiesce) answers false in it, and a device + /// whose last handle drops in it ends once the handler returns, as in a completed handler. + /// Metal runs a scheduled handler on a thread of its own, where those calls run. /// /// Err: [`Refusal::Committed`]. pub fn add_scheduled_handler( @@ -412,8 +424,8 @@ impl CommandBuffer { } /// `addCompletedHandler:`: runs on the completion thread once the command buffer has - /// completed or ended, after its scheduled handlers. One thread runs every device's handlers - /// in turn, so a handler waits for no command buffer. + /// completed or ended, after its scheduled handlers. One thread runs every device's completed + /// handlers in turn, so a completed handler waits for no command buffer. /// /// Err: [`Refusal::Committed`]. pub fn add_completed_handler( @@ -452,9 +464,10 @@ impl CommandBuffer { /// `vkQueueSubmit2`. A commit after a loss ends at once with /// [`CommandBufferError::DeviceLost`]. /// - /// Err: [`Refusal::Committed`]; [`Error::Quiesced`]; [`Error::Vulkan`] where ending the last - /// segment's commands fails. + /// Err: [`Refusal::Committed`]; [`Refusal::InScheduledHandler`] in a scheduled handler; + /// [`Error::Quiesced`]; [`Error::Vulkan`] where ending the last segment's commands fails. pub fn commit(&self) -> Result<(), Error> { + not_in_scheduled_handler()?; // The core, not a handle: the command buffer gives its handle up before another thread // can complete it, so a handler that drops the consumer's last handle ends the device on // the reaper, never in this call. @@ -532,7 +545,10 @@ impl CommandBuffer { /// `waitUntilScheduled`: returns once the command buffer is scheduled, or has completed or /// ended. It sends nothing: a command buffer held in a group is scheduled already. - pub fn wait_until_scheduled(&self) { + /// + /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler. + pub fn wait_until_scheduled(&self) -> Result<(), Error> { + not_in_scheduled_handler()?; let mut state = self.state(); while !matches!( state.status, @@ -542,17 +558,22 @@ impl CommandBuffer { ) { state = self.wait(state); } + Ok(()) } /// `waitUntilCompleted`: returns once the command buffer has completed or ended and its /// handlers have run. A command buffer held in a group goes at once, as /// [`CommandQueue::send_now`](crate::CommandQueue::send_now) sends it. - pub fn wait_until_completed(&self) { + /// + /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler. + pub fn wait_until_completed(&self) -> Result<(), Error> { + not_in_scheduled_handler()?; self.send(); let mut state = self.state(); while !state.finished { state = self.wait(state); } + Ok(()) } /// Before a host wait for it: where the command buffer is committed and not yet submitted, @@ -1193,12 +1214,38 @@ impl CbInner { } } -/// On the completion thread: runs the scheduled handlers of a command buffer just submitted. +thread_local! { + /// Whether this thread runs a scheduled handler ([`run_scheduled`]). + static IN_SCHEDULED_HANDLER: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// [`Refusal::InScheduledHandler`] where this thread runs a scheduled handler: the calls that may +/// wait for the submit thread, which runs it, refuse there on every device. +pub(crate) fn not_in_scheduled_handler() -> Result<(), Error> { + match IN_SCHEDULED_HANDLER.get() { + true => Err(Error::Refused(Refusal::InScheduledHandler)), + false => Ok(()), + } +} + +/// On the submit thread, with no lock of the runtime's held: runs the scheduled handlers of a +/// command buffer scheduled, before its submission goes to the driver and before it is handed +/// on as ended. pub(crate) fn run_scheduled(inner: Arc, handlers: Vec) { + /// Clears the mark as the handlers end, a panic among them too. + struct Running; + impl Drop for Running { + fn drop(&mut self) { + IN_SCHEDULED_HANDLER.set(false); + } + } let handle = CommandBuffer { inner }; + IN_SCHEDULED_HANDLER.set(true); + let running = Running; for handler in handlers { handler(&handle); } + drop(running); } /// On the completion thread: retires a command buffer that completed (`error` None), with its GPU diff --git a/crates/metal2vulkan-rt/src/complete.rs b/crates/metal2vulkan-rt/src/complete.rs index 891885c0b..5b56033f2 100644 --- a/crates/metal2vulkan-rt/src/complete.rs +++ b/crates/metal2vulkan-rt/src/complete.rs @@ -1,12 +1,12 @@ //! The completion thread: it retires command buffers and uploads as the GPU completes them, runs -//! the handlers, follows the event signals it submitted and runs listeners, and ends the work in +//! their completed handlers, follows the event signals it submitted and runs listeners, and ends the work in //! flight at a loss. -use crate::command::{self, CbInner, CommandBufferError, Gpu, Handler, Handlers, Pending}; +use crate::command::{self, CbInner, CommandBufferError, Gpu, Handlers, Pending}; use crate::device::{lock, Core}; use crate::error::Error; use crate::event::{self, EventInner, Listener}; -use crate::submit::{Ended, Finished, Joined, Upload}; +use crate::submit::{Ended, Finished, Upload}; use crate::times::{self, Calibration}; use ash::vk; use std::collections::VecDeque; @@ -31,8 +31,6 @@ pub(crate) struct Done { } struct DoneState { - /// Command buffers just scheduled, with their scheduled handlers. - scheduled: Vec<(Arc, Vec)>, /// Work submitted, by progress value: each retires once the progress semaphore reaches it. flight: VecDeque, /// Command buffers that ended without anything in flight: they retire at once. @@ -127,7 +125,6 @@ impl Done { })?; Ok(Done { state: Mutex::new(DoneState { - scheduled: Vec::new(), flight: VecDeque::new(), ended: Vec::new(), watched: Vec::new(), @@ -186,17 +183,6 @@ impl Done { state.waiting = Waiting::Not; } - /// From the submit thread: command buffers scheduled as they joined a submission, with their - /// scheduled handlers, ahead of that submission. - pub(crate) fn scheduled(&self, core: &Core, joined: Vec) { - if joined.is_empty() { - return; - } - let mut state = self.lock(); - state.scheduled.extend(joined); - self.wake(&mut state, &core.device, false); - } - /// From the submit thread: a submission passed to `vkQueueSubmit2` with progress `value`. /// Its command buffers retire in order once it completes, each ended one with its error. pub(crate) fn submitted( @@ -345,7 +331,6 @@ pub(crate) fn run(core: Arc) { let mut calibration = Calibration::read(&core); let mut state = done.lock(); loop { - let scheduled = std::mem::take(&mut state.scheduled); let mut retire = std::mem::take(&mut state.ended); let fired = std::mem::take(&mut state.fire); let mut fire: Vec<(Listener, u64)> = Vec::new(); @@ -397,7 +382,7 @@ pub(crate) fn run(core: Arc) { for event in &fired { event.observe(None, &mut fire); } - if newly_lost || !scheduled.is_empty() || !retire.is_empty() || !fire.is_empty() { + if newly_lost || !retire.is_empty() || !fire.is_empty() { state.waiting = Waiting::Not; drop(state); if newly_lost { @@ -408,9 +393,6 @@ pub(crate) fn run(core: Arc) { core.work.completed(); } // Handlers and listeners run with no lock held. - for (cb, handlers) in scheduled { - command::run_scheduled(cb, handlers); - } // Each completed command buffer's timestamps are placed on the host clock by the // last calibration, read again first where the period has passed since it. let stamps: Vec> = diff --git a/crates/metal2vulkan-rt/src/device.rs b/crates/metal2vulkan-rt/src/device.rs index 71f3a54b8..943e4af89 100644 --- a/crates/metal2vulkan-rt/src/device.rs +++ b/crates/metal2vulkan-rt/src/device.rs @@ -41,8 +41,9 @@ use std::time::{Duration, Instant}; /// A cheap handle: clones share one device, and every object made from it holds a clone, except /// a committed command buffer. Blocks the consumer holds do not. /// -/// The runtime runs four threads: the block-maker, the submit thread, the completion thread, -/// which runs every handler and listener, and the reaper, which frees the semaphores and command +/// The runtime runs four threads: the block-maker, the submit thread, which runs every scheduled +/// handler, the completion thread, which runs every completed handler and listener, and the +/// reaper, which frees the semaphores and command /// pools the others give up, one at a time, so no driver free runs on the completion thread. The /// device is torn down when the last handle is dropped: the submit thread submits what is ready /// and ends what it holds with [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun); @@ -87,8 +88,9 @@ enum Role { /// Not a runtime thread. None, Blocks, + /// The submit thread: it runs the consumer's scheduled handlers. Submit, - /// The completion thread: the only one that runs the consumer's code. + /// The completion thread: it runs the consumer's completed handlers and listeners. Complete, Reaper, } @@ -645,17 +647,19 @@ impl Device { /// No Metal counterpart: stops the runtime's threads and its GPU work, for a process about to /// exit with the device still alive. True once the GPU went idle and every thread ended /// within `timeout`; false where the timeout passed first, or the call ran in a handler or a - /// listener (the completion thread cannot wait for itself). + /// listener (the submit thread, which runs the scheduled handlers, and the completion thread, + /// which runs the completed handlers and listeners, cannot wait for themselves). /// /// In order, each wait bounded by `timeout`: the submit thread submits what is ready, ends /// every command buffer it holds or has not yet submitted with /// [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun), and ends; the /// block-maker thread ends; the GPU completes everything submitted; the completion thread - /// retires it, runs the handlers, and ends; then [`BlockMappings::unmap`] runs on this thread - /// for every block still handed out. After it, no runtime thread touches a block, unless the - /// call answered false. A thread past the timeout ends alone: the completion thread once the - /// GPU completed what was submitted and it retired that, running its handlers, so what the - /// work held, the device among it, goes once the device's last handle has dropped. + /// retires it, runs the completed handlers, and ends; then [`BlockMappings::unmap`] runs on + /// this thread for every block still handed out. After it, no runtime thread touches a block, + /// unless the call answered false. A thread past the timeout ends alone: the completion + /// thread once the GPU completed what was submitted and it retired that, running its + /// completed handlers, so what the work held, the device among it, goes once the device's + /// last handle has dropped. /// /// It frees nothing: every block's memory and mapping stays valid until the process ends, or /// until the device's last handle drops, which then frees it without the hook. Later calls @@ -844,13 +848,16 @@ fn halt(core: &Arc, threads: Threads, deadline: Option, quiesce: complete, reaper, } = threads; + // Where a scheduled handler quiesces, on the submit thread, the thread's own submission and + // the completion thread wait for the handler to return: neither is waited for. + let on_submit = role(core) == Role::Submit; // Submission stops: what is ready goes, and what is held ends. core.work.stop(); let submitted = finish(submit, core, deadline); let mut idle = submitted; core.pool.stop(); idle &= finish(blocks, core, deadline); - if quiesce { + if quiesce && !on_submit { idle &= core.wait_progress(core.work.progress(), deadline); } // The submit thread stops the completion thread as it ends; here only where it has ended, or @@ -858,7 +865,9 @@ fn halt(core: &Arc, threads: Threads, deadline: Option, quiesce: if submitted { core.done.stop(core); } - idle &= finish(complete, core, deadline); + if !on_submit { + idle &= finish(complete, core, deadline); + } core.reaper.stop(); idle &= finish(reaper, core, deadline); // The consumer's mappings go here, on the thread that stops the device, whichever thread @@ -871,8 +880,8 @@ fn halt(core: &Arc, threads: Threads, deadline: Option, quiesce: /// Waits for a thread to end, up to `deadline`, and joins it once it has; a thread past the /// deadline is left to end alone. True once it ended. A thread is never waited for by itself: the -/// completion thread where a handler or listener quiesces, the reaper where it runs a teardown; -/// it ends once the call returns. +/// completion thread where a completed handler or a listener quiesces, the submit thread where a +/// scheduled handler does, the reaper where it runs a teardown; it ends once the call returns. fn finish(runner: Option, core: &Arc, deadline: Option) -> bool { let Some(Runner { handle, @@ -1179,9 +1188,9 @@ impl Drop for Shared { // pipelines freed with the core. core.kernels.clear(&core.counters); }; - if role(&self.core) == Role::Complete { + if matches!(role(&self.core), Role::Complete | Role::Submit) { // A handler or listener dropped the last handle: the reaper tears down, once the - // handler returns and the completion thread can end. + // handler returns and its thread can end. self.core.reaper.give(Job::Teardown(Box::new(teardown))); } else { teardown(&self.core); diff --git a/crates/metal2vulkan-rt/src/error.rs b/crates/metal2vulkan-rt/src/error.rs index 670c21d31..54d587a86 100644 --- a/crates/metal2vulkan-rt/src/error.rs +++ b/crates/metal2vulkan-rt/src/error.rs @@ -162,6 +162,26 @@ pub enum Refusal { /// buffer", "Completed handler provided after commit call" and "Scheduled handler provided /// after commit call"). Committed, + /// A call a scheduled handler may not make + /// ([`CommandBuffer::add_scheduled_handler`](crate::CommandBuffer::add_scheduled_handler)): + /// [`CommandBuffer::commit`](crate::CommandBuffer::commit), the waits + /// ([`CommandBuffer::wait_until_scheduled`](crate::CommandBuffer::wait_until_scheduled), + /// [`CommandBuffer::wait_until_completed`](crate::CommandBuffer::wait_until_completed), + /// [`Event::wait_until_signaled_value`](crate::Event::wait_until_signaled_value)), the uploads + /// and readbacks ([`Texture::replace_region`](crate::Texture::replace_region), + /// [`Texture::upload_region`](crate::Texture::upload_region), + /// [`Texture::get_bytes`](crate::Texture::get_bytes), + /// [`Device::zero_block_range`](crate::Device::zero_block_range)), and the objects that take + /// an upload ([`Device::new_managed_buffer`](crate::Device::new_managed_buffer), and + /// [`Device::new_buffer`](crate::Device::new_buffer) zeroing a buffer in a Private block). + /// Refused on every device and whatever the runtime holds: a scheduled handler runs on the + /// submit thread, before its command buffer's submission, and each of these calls may wait + /// for that thread to submit. Metal runs a scheduled handler on a thread of its own, where + /// each of these calls runs. + /// + /// Basis: ours (the consumer's scheduled handlers run on the submit thread, and the one + /// consumer's make none of these calls; a guest's scheduled handler runs in the guest). + InScheduledHandler, /// An event, a buffer, a texture or a pipeline state of another device in an encode call /// ([`CommandBuffer::encode_wait_for_event`](crate::CommandBuffer::encode_wait_for_event), /// [`CommandBuffer::encode_signal_event`](crate::CommandBuffer::encode_signal_event), or a diff --git a/crates/metal2vulkan-rt/src/event.rs b/crates/metal2vulkan-rt/src/event.rs index e08b33924..b55123c1b 100644 --- a/crates/metal2vulkan-rt/src/event.rs +++ b/crates/metal2vulkan-rt/src/event.rs @@ -154,7 +154,11 @@ impl SharedEvent { /// /// Also false once the device is lost while the signals the wait needs are pending. A wait /// that no submitted signal can meet is met only by the host. - pub fn wait_until_signaled_value(&self, value: u64, timeout: Duration) -> bool { + /// + /// Err: [`Refusal::InScheduledHandler`](crate::Refusal::InScheduledHandler) in a scheduled + /// handler. + pub fn wait_until_signaled_value(&self, value: u64, timeout: Duration) -> Result { + crate::command::not_in_scheduled_handler()?; let inner = &self.event.inner; let deadline = Instant::now().checked_add(timeout); let mut state = lock(&inner.state); @@ -162,10 +166,10 @@ impl SharedEvent { if state.floor.max(state.observed) >= value || inner.counter().is_ok_and(|counter| counter >= value) { - return true; + return Ok(true); } if state.lost { - return false; + return Ok(false); } state = match deadline { None => inner @@ -174,7 +178,7 @@ impl SharedEvent { .unwrap_or_else(PoisonError::into_inner), Some(deadline) => { let Some(left) = deadline.checked_duration_since(Instant::now()) else { - return false; + return Ok(false); }; inner .changed diff --git a/crates/metal2vulkan-rt/src/reaper.rs b/crates/metal2vulkan-rt/src/reaper.rs index 7cde02f80..fc5c8b58a 100644 --- a/crates/metal2vulkan-rt/src/reaper.rs +++ b/crates/metal2vulkan-rt/src/reaper.rs @@ -32,7 +32,8 @@ struct State { pub(crate) enum Job { Free(Free), - /// The device's teardown, after its last handle dropped on the completion thread. + /// The device's teardown, after its last handle dropped on the completion thread or the + /// submit thread, in a handler or a listener. Teardown(Teardown), } diff --git a/crates/metal2vulkan-rt/src/submit.rs b/crates/metal2vulkan-rt/src/submit.rs index 71644b1f0..c4b3929a7 100644 --- a/crates/metal2vulkan-rt/src/submit.rs +++ b/crates/metal2vulkan-rt/src/submit.rs @@ -27,7 +27,7 @@ use crate::buffer::{Buffer, DeviceCopy}; use crate::capture::{self, Changes, Chunk, CopyIn, Modified, Named, CAPTURE_LEN}; -use crate::command::{CbInner, CommandBufferError, Handler, Pending, Segment}; +use crate::command::{self, CbInner, CommandBufferError, Handler, Pending, Segment}; use crate::complete; use crate::counters::{Counters, Gauge, Metric}; use crate::device::{lock, Core}; @@ -1802,8 +1802,8 @@ fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard< continue; }; drop(state); - // Scheduled handlers reach the completion thread before the submission they are in. - core.done.scheduled(core, std::mem::take(&mut joined)); + // Scheduled handlers run here, with no lock held, before the submission they are in. + scheduled(&mut joined); core.done.end_all(core, std::mem::take(&mut ended)); submit(core, value, upload, batch); sent = true; @@ -1824,7 +1824,7 @@ fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard< } if !joined.is_empty() || !ended.is_empty() { drop(state); - core.done.scheduled(core, joined); + scheduled(&mut joined); core.done.end_all(core, ended); state = work.lock(); } @@ -1851,6 +1851,14 @@ impl Batch { } } +/// Runs the scheduled handlers of the command buffers `joined` scheduled, in order, with no lock +/// held: before the submission they are in goes, and before any of them is handed on as ended. +fn scheduled(joined: &mut Vec) { + for (cb, handlers) in joined.drain(..) { + command::run_scheduled(cb, handlers); + } +} + /// Submits a group: the upload first, then each segment in order, the last signalling the /// progress `value`. Whatever was passed to `vkQueueSubmit2` goes to the completion thread as in /// flight; a failed submission is taken as a loss. diff --git a/crates/metal2vulkan-rt/src/tests/command.rs b/crates/metal2vulkan-rt/src/tests/command.rs index f267cb7ca..35dfe163d 100644 --- a/crates/metal2vulkan-rt/src/tests/command.rs +++ b/crates/metal2vulkan-rt/src/tests/command.rs @@ -145,7 +145,9 @@ pub(crate) mod on_device { CommandBufferStatus::Completed | CommandBufferStatus::Error ) }); - command_buffer.wait_until_completed(); + command_buffer + .wait_until_completed() + .expect("a wait outside a scheduled handler"); } /// A log the handlers write to. @@ -176,8 +178,9 @@ pub(crate) mod on_device { } } - /// A command buffer goes through Metal's states, runs its handlers in order on the completion - /// thread, and runs its commands; a queue keeps enqueue order and bounds its command buffers; + /// A command buffer goes through Metal's states, runs its handlers in order (its scheduled + /// handlers on the submit thread, its completed handlers on the completion thread), and runs + /// its commands; a queue keeps enqueue order and bounds its command buffers; /// Metal's refusals. #[test] fn every_device_runs_command_buffers_through_their_states_and_handlers() { @@ -386,7 +389,8 @@ pub(crate) mod on_device { behind.commit().expect("a commit"); assert!( - e.wait_until_signaled_value(1, PATIENCE), + e.wait_until_signaled_value(1, PATIENCE) + .expect("a wait outside a scheduled handler"), "{name}: E reached" ); assert_eq!(e.signaled_value(), 1); @@ -487,7 +491,9 @@ pub(crate) mod on_device { let (returned, waited) = mpsc::channel(); thread::spawn(move || { for command_buffer in &command_buffers { - command_buffer.wait_until_completed(); + command_buffer + .wait_until_completed() + .expect("a wait outside a scheduled handler"); } let _ = returned.send(command_buffers); }); @@ -1123,7 +1129,9 @@ pub(crate) mod on_device { fn drop(&mut self) { self.open(); for command_buffer in &self.running { - command_buffer.wait_until_completed(); + command_buffer + .wait_until_completed() + .expect("a wait outside a scheduled handler"); } let device = &self.device.core().device; // SAFETY: the gate's batch, the only one that names the semaphore, completed once the @@ -1834,7 +1842,8 @@ pub(crate) mod on_device { "{name}: at once" ); assert_eq!(held.error(), Some(CommandBufferError::NotRun), "{name}"); - held.wait_until_completed(); + held.wait_until_completed() + .expect("a wait outside a scheduled handler"); let mut unmapped = lock(&hook.0).clone(); unmapped.sort(); @@ -1913,6 +1922,236 @@ pub(crate) mod on_device { } } + /// The last handle dropped in a scheduled handler, on the submit thread: the reaper runs the + /// teardown once the handler returns, the command buffer still completes, and every gauge + /// reads zero once the device is destroyed. + #[test] + fn every_device_tears_down_from_a_scheduled_handler() { + let instance = crate::tests::validation::instance(&[]); + let devices = devices_of_the_cfgs_kind(&instance); + assert!(!devices.is_empty(), "no device of this cfg's kind"); + for (name, physical) in &devices { + let hook = Arc::new(Hook::default()); + let options = DeviceOptions { + block_mappings: Some(hook.clone() as Arc), + ..DeviceOptions::default() + }; + let device = Device::new(physical, options).expect("a device"); + let counters = device.counters(); + let block = device + .take_block(MemoryClass::Shared, 1) + .expect("a Shared block"); + let queue = queue(&device); + let command_buffer = queue.command_buffer().expect("a command buffer"); + drop(queue); + let handles = Arc::new(AtomicUsize::new(0)); + let seen = Arc::clone(&handles); + command_buffer + .add_scheduled_handler(move |_| { + seen.store(device.handles(), Ordering::SeqCst); + drop(device); + }) + .expect("a handler"); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!( + handles.load(Ordering::SeqCst), + 1, + "{name}: the handler held the last handle" + ); + assert_eq!(command_buffer.error(), None, "{name}: it ran"); + within("the teardown", || counters.gauges() == Gauges::default()); + print_gauges_at_drop("scheduled_teardown", counters.gauges()); + assert_eq!( + *lock(&hook.0), + [(block.id, Some("m2v-reaper".to_string()))], + "{name}: unmapped once, by the reaper" + ); + } + } + + /// Quiesce in a scheduled handler answers false at once: the submit thread, which runs the + /// handler, is not waited for, nor is the completion thread, which it stops as it ends. The + /// command buffer still completes, and the device then tears down. + #[test] + fn every_device_answers_false_to_a_quiesce_in_a_scheduled_handler() { + each_device("scheduled_quiesce", |name, _, device| { + let counters = device.counters(); + let mut arena = Arena::new(&device); + let a = arena.buffer(); + let queue = queue(&device); + let command_buffer = queue.command_buffer().expect("a command buffer"); + fill(&command_buffer, &a, 9); + let (answered, answer) = mpsc::channel(); + let quiescing = device.clone(); + command_buffer + .add_scheduled_handler(move |_| { + let began = Instant::now(); + let idle = quiescing.quiesce(PATIENCE); + let _ = answered.send((idle, began.elapsed())); + }) + .expect("a handler"); + command_buffer.commit().expect("a commit"); + let (idle, took) = answer.recv_timeout(PATIENCE).expect("the handler's answer"); + assert!(!idle, "{name}: false in a scheduled handler"); + assert!( + took < Duration::from_secs(1), + "{name}: at once, took {took:?}" + ); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}: it ran"); + assert_eq!(word(&a), 9, "{name}"); + assert!(!device.quiesce(PATIENCE), "{name}: a later call's answer"); + drop((a, arena, queue, command_buffer, device)); + within("the teardown", || counters.gauges() == Gauges::default()); + }); + } + + /// In a scheduled handler, on the submit thread: the command buffer reads Scheduled with its + /// kernel times set; each call that may wait for that thread is refused, on every device and + /// whatever the runtime holds, and answers as before once the handler has returned; what the + /// handler may do, enqueueing and making objects that take no upload, it does. + #[test] + fn every_device_refuses_each_call_that_waits_for_the_submit_thread_in_a_scheduled_handler() { + use crate::{PixelFormat, Region, TextureDescriptor, TextureType, TextureUsage}; + each_device("scheduled_refusals", |name, _, device| { + let mut arena = Arena::new(&device); + let (a, b) = (arena.buffer(), arena.buffer()); + let private = device + .take_block(MemoryClass::Private, 4096) + .expect("a Private block"); + let shared = device + .take_block(MemoryClass::Shared, 4096) + .expect("a Shared block"); + let event = shared_event(&device); + let mut d = TextureDescriptor::new(TextureType::Type2D, PixelFormat::RGBA8Unorm, 4, 4); + d.usage = TextureUsage::RENDER_TARGET; + let texture = device.new_texture(&d, None).expect("a texture"); + let queue = queue(&device); + let command_buffer = queue.command_buffer().expect("a command buffer"); + fill(&command_buffer, &a, 3); + let other = queue.command_buffer().expect("a command buffer"); + fill(&other, &b, 4); + let later = queue.command_buffer().expect("a command buffer"); + let (answered, answers) = mpsc::channel(); + let (in_device, in_other, in_later, in_event, in_texture) = ( + device.clone(), + other.clone(), + later.clone(), + event.clone(), + texture.clone(), + ); + let private_id = private.id; + let shared_id = shared.id; + command_buffer + .add_scheduled_handler(move |own| { + let refused = |result: Result<(), Error>| -> String { format!("{result:?}") }; + let region = Region { + origin: [0, 0, 0], + size: [1, 1, 1], + }; + let mut bytes = [0_u8; 4]; + let lines = vec![ + ("status", format!("{:?}", own.status())), + ( + "kernel times", + format!( + "{}", + own.kernel_start_time() > 0 + && own.kernel_end_time() >= own.kernel_start_time() + ), + ), + ("commit", refused(in_other.commit())), + ("wait_until_scheduled", refused(own.wait_until_scheduled())), + ("wait_until_completed", refused(own.wait_until_completed())), + ( + "wait_until_signaled_value", + refused( + in_event + .wait_until_signaled_value(1, Duration::ZERO) + .map(drop), + ), + ), + ( + "replace_region", + refused(in_texture.replace_region(region, 0, 0, &[0; 4], 4, 4)), + ), + ( + "upload_region", + refused(in_texture.upload_region(region, 0, 0)), + ), + ( + "get_bytes", + refused(in_texture.get_bytes(&mut bytes, 4, 4, region, 0, 0)), + ), + ( + "zero_block_range", + refused(in_device.zero_block_range(private_id, 0, 0)), + ), + ( + "new_managed_buffer", + refused( + (in_device.new_managed_buffer((shared_id, 1024), None, 64, 0)) + .map(drop), + ), + ), + ( + "new_buffer zeroed in a Private block", + refused(in_device.new_buffer(private_id, 0, 64, Some(0)).map(drop)), + ), + ( + "new_buffer in a Private block, not zeroed", + refused(in_device.new_buffer(private_id, 64, 64, None).map(drop)), + ), + ( + "new_buffer zeroed in a Shared block", + refused(in_device.new_buffer(shared_id, 0, 64, Some(0)).map(drop)), + ), + ("enqueue", refused(in_later.enqueue())), + ( + "new_texture", + refused(in_device.new_texture(&d, None).map(drop)), + ), + ]; + let _ = answered.send(lines); + }) + .expect("a handler"); + command_buffer.commit().expect("a commit"); + let lines = answers + .recv_timeout(PATIENCE) + .expect("the handler's answers"); + let refusal = format!( + "{:?}", + Err::<(), Error>(Error::Refused(Refusal::InScheduledHandler)) + ); + for (call, answer) in &lines { + let want = match *call { + "status" => format!("{:?}", CommandBufferStatus::Scheduled), + "kernel times" => "true".to_string(), + "new_buffer in a Private block, not zeroed" + | "new_buffer zeroed in a Shared block" + | "enqueue" + | "new_texture" => "Ok(())".to_string(), + _ => refusal.clone(), + }; + assert_eq!(*answer, want, "{name}: {call}"); + } + assert_eq!(lines.len(), 16, "{name}: {lines:?}"); + finished(name, &command_buffer); + assert_eq!(later.status(), CommandBufferStatus::Enqueued, "{name}"); + // Outside a handler the same calls answer as before. The one the handler enqueued + // goes first: the other is enqueued behind it as it commits. + later.commit().expect("a commit outside a handler"); + other.commit().expect("a commit outside a handler"); + finished(name, &later); + finished(name, &other); + assert_eq!((word(&a), word(&b)), (3, 4), "{name}"); + assert!(event + .wait_until_signaled_value(0, Duration::ZERO) + .expect("a wait outside a scheduled handler")); + }); + } + /// At a loss: a host wait for a pending signal ends false; the command buffer in flight ends /// DeviceLost in flight, the held one and every later commit DeviceLost not in flight; the /// device tears down, and a new device opens and runs work. @@ -1944,7 +2183,10 @@ pub(crate) mod on_device { in_flight.status() == CommandBufferStatus::Scheduled }); let waiting = thread::scope(|scope| { - let waiter = scope.spawn(|| g.wait_until_signaled_value(1, PATIENCE)); + let waiter = scope.spawn(|| { + g.wait_until_signaled_value(1, PATIENCE) + .expect("a wait outside a scheduled handler") + }); thread::sleep(Duration::from_millis(20)); device.lose_for_test(); waiter.join().expect("the waiter") diff --git a/crates/metal2vulkan-rt/src/tests/compute.rs b/crates/metal2vulkan-rt/src/tests/compute.rs index d2ebe47af..7cf2131ad 100644 --- a/crates/metal2vulkan-rt/src/tests/compute.rs +++ b/crates/metal2vulkan-rt/src/tests/compute.rs @@ -533,7 +533,12 @@ pub(crate) mod on_device { .expect("a signal"); encode_add(&command_buffer, &o); run(name, &command_buffer); - assert!(signaled.wait_until_signaled_value(1, PATIENCE), "{name}"); + assert!( + signaled + .wait_until_signaled_value(1, PATIENCE) + .expect("a wait outside a scheduled handler"), + "{name}" + ); assert_eq!(counters.host_reaches(), before + 2, "{name}: signal"); let expected: Vec = (0..WORDS as u32).map(|index| 103 + index).collect(); assert_eq!(words(&o), expected, "{name}: after a signal"); @@ -553,7 +558,12 @@ pub(crate) mod on_device { .encode_wait_for_event(release.as_event(), 1) .expect("a wait"); command_buffer.commit().expect("a commit"); - assert!(signaled.wait_until_signaled_value(1, PATIENCE), "{name}"); + assert!( + signaled + .wait_until_signaled_value(1, PATIENCE) + .expect("a wait outside a scheduled handler"), + "{name}" + ); let expected: Vec = (0..WORDS as u32).map(|index| 2 * index + 1).collect(); assert_eq!(words(&x), expected, "{name}: at the signal"); release.set_signaled_value(1); diff --git a/crates/metal2vulkan-rt/src/tests/heap.rs b/crates/metal2vulkan-rt/src/tests/heap.rs index e9a88583f..1c8b50bc0 100644 --- a/crates/metal2vulkan-rt/src/tests/heap.rs +++ b/crates/metal2vulkan-rt/src/tests/heap.rs @@ -196,7 +196,9 @@ mod on_device { ); encoder.end_encoding(); (command_buffer.commit()).unwrap_or_else(|error| panic!("{name}: {error}")); - command_buffer.wait_until_completed(); + command_buffer + .wait_until_completed() + .expect("a wait outside a scheduled handler"); wait_until("the command buffer to retire", || { memory.strong_count() == 0 }); diff --git a/crates/metal2vulkan-rt/src/tests/managed.rs b/crates/metal2vulkan-rt/src/tests/managed.rs index 41f7ae89b..67adb8fb4 100644 --- a/crates/metal2vulkan-rt/src/tests/managed.rs +++ b/crates/metal2vulkan-rt/src/tests/managed.rs @@ -778,7 +778,9 @@ pub(crate) mod on_device { part as f64 / took.as_secs_f64() / 1e9, counters.metrics().capture_waits ); - command_buffer.wait_until_scheduled(); + command_buffer + .wait_until_scheduled() + .expect("a wait outside a scheduled handler"); commits.push(command_buffer); } for command_buffer in &commits { diff --git a/crates/metal2vulkan-rt/src/tests/memory.rs b/crates/metal2vulkan-rt/src/tests/memory.rs index 89e1c0cfb..425e54d67 100644 --- a/crates/metal2vulkan-rt/src/tests/memory.rs +++ b/crates/metal2vulkan-rt/src/tests/memory.rs @@ -526,7 +526,8 @@ mod on_device { }) .expect("a copy"); copy.commit().expect("a commit"); - copy.wait_until_completed(); + copy.wait_until_completed() + .expect("a wait outside a scheduled handler"); assert_eq!(copy.status(), CommandBufferStatus::Completed, "{name}"); let range = (offset + zero_from) as usize..(offset + length) as usize; for (index, &byte) in host[..8192].iter().enumerate() { @@ -819,7 +820,8 @@ mod on_device { }) .expect("a copy"); copy.commit().expect("a commit"); - copy.wait_until_completed(); + copy.wait_until_completed() + .expect("a wait outside a scheduled handler"); assert_eq!(copy.status(), CommandBufferStatus::Completed, "{name}"); for (index, &byte) in host[..3 * 4096].iter().enumerate() { let expected = if (4096..8192).contains(&index) { @@ -1262,7 +1264,9 @@ mod on_device { let buffer = (device.new_buffer(target.id, 0, 256, None)).expect("a buffer"); let command_buffer = queue.command_buffer().expect("a command buffer"); command_buffer.commit().expect("a commit"); - command_buffer.wait_until_completed(); + command_buffer + .wait_until_completed() + .expect("a wait outside a scheduled handler"); let mut blocks: Vec = (0..3) .map(|_| { (device.take_block(MemoryClass::Shared, len)) @@ -1328,7 +1332,9 @@ mod on_device { }) .expect("a fill"); command_buffer.commit().expect("a commit"); - command_buffer.wait_until_completed(); + command_buffer + .wait_until_completed() + .expect("a wait outside a scheduled handler"); }; core.pool.hold_frees(true); device.release_block(blocks.remove(0)).expect("a release"); @@ -1621,7 +1627,9 @@ mod on_device { }) .expect("the copies"); command_buffer.commit().expect("a commit"); - command_buffer.wait_until_completed(); + command_buffer + .wait_until_completed() + .expect("a wait outside a scheduled handler"); assert_eq!( command_buffer.status(), CommandBufferStatus::Completed, diff --git a/crates/metal2vulkan-rt/src/tests/sampling.rs b/crates/metal2vulkan-rt/src/tests/sampling.rs index dbb914c26..0ef134d5d 100644 --- a/crates/metal2vulkan-rt/src/tests/sampling.rs +++ b/crates/metal2vulkan-rt/src/tests/sampling.rs @@ -669,7 +669,12 @@ mod on_device { (pending.encode_signal_event(signaled.as_event(), 1)).expect("a signal"); (pending.encode_wait_for_event(release.as_event(), 1)).expect("a wait"); pending.commit().expect("a commit"); - assert!(signaled.wait_until_signaled_value(1, PATIENCE), "{name}"); + assert!( + signaled + .wait_until_signaled_value(1, PATIENCE) + .expect("a wait outside a scheduled handler"), + "{name}" + ); drop((a, sa)); let b = texture(&device, SIDE, read, AT); fill(name, &b); diff --git a/crates/metal2vulkan-rt/src/texture.rs b/crates/metal2vulkan-rt/src/texture.rs index 921150989..a6ab45066 100644 --- a/crates/metal2vulkan-rt/src/texture.rs +++ b/crates/metal2vulkan-rt/src/texture.rs @@ -2799,7 +2799,8 @@ impl Texture { /// texture over a buffer ([`Buffer::new_texture`]) takes them in the buffer, which is its /// image's memory; nothing is staged, copied or counted. /// - /// Err: [`Refusal::TextureBytesPrivate`]; [`Refusal::TextureRegion`] for a level, slice or + /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler; + /// [`Refusal::TextureBytesPrivate`]; [`Refusal::TextureRegion`] for a level, slice or /// region outside the texture or off its format's block grid; /// [`Refusal::TextureBytesLayout`]; [`Gap::TextureBytes`]; [`Gap::FloatDepthUpload`] for a /// 32-bit float depth; [`Limit::MemoryAllocations`] where the region's block or a staging @@ -2818,6 +2819,7 @@ impl Texture { bytes_per_row: u64, bytes_per_image: u64, ) -> Result<(), Error> { + crate::command::not_in_scheduled_handler()?; let inner = &self.inner; let len = bytes.len() as u64; let Some(copy) = inner.copy(region, level, slice, len, bytes_per_row, bytes_per_image)? @@ -2886,13 +2888,15 @@ impl Texture { /// bytes when the GPU reaches it. [`Texture::replace_region`] on such a texture writes the named bytes, /// then calls this. An empty region copies nothing. /// - /// Err: [`Refusal::ManagedTextureBytes`] for a texture without named bytes, or a depth or + /// Err: [`Refusal::InScheduledHandler`] in a scheduled handler; + /// [`Refusal::ManagedTextureBytes`] for a texture without named bytes, or a depth or /// stencil region whose first byte is not a multiple of 4 in the buffer; /// [`Refusal::TextureRegion`] for a level, slice or region outside the texture or off its /// format's block grid; [`Gap::FloatDepthUpload`] for a 32-bit float depth; /// [`Error::Quiesced`], and [`Error::Vulkan`] where the upload's command buffer cannot be /// made. pub fn upload_region(&self, region: Region, level: u32, slice: u32) -> Result<(), Error> { + crate::command::not_in_scheduled_handler()?; let inner = &self.inner; if inner .named @@ -2964,6 +2968,7 @@ impl Texture { level: u32, slice: u32, ) -> Result<(), Error> { + crate::command::not_in_scheduled_handler()?; let inner = &self.inner; let len = bytes.len() as u64; let Some(copy) = inner.copy(region, level, slice, len, bytes_per_row, bytes_per_image)? @@ -2998,7 +3003,7 @@ impl Texture { let command_buffer = queue.command_buffer()?; command_buffer.record_for_test(&[], |_, _| {})?; command_buffer.commit()?; - command_buffer.wait_until_completed(); + command_buffer.wait_until_completed()?; drop((command_buffer, queue)); let value = core.work.flush(); core.done.wait(core, value)?; diff --git a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs index e07699dd3..3cf4343d0 100644 --- a/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs +++ b/crates/metal2vulkan-validation/src/replay/new_runtime/mod.rs @@ -691,8 +691,8 @@ impl NewRuntime { let Some((_, front, retired)) = self.in_flight.front() else { return; }; - front.wait_until_completed(); - if !retired.load(Ordering::Acquire) { + // Refused only in a scheduled handler, where the player never runs. + if front.wait_until_completed().is_err() || !retired.load(Ordering::Acquire) { return; } } @@ -1849,7 +1849,12 @@ impl Backend for NewRuntime { fn wait(&mut self, command_buffer: u64) -> Result<(), PlayError> { match self.objects.get(&command_buffer) { Some(Object::CommandBuffer(waited)) => { - waited.wait_until_completed(); + waited + .wait_until_completed() + .map_err(|error| PlayError::Runtime { + selector: "waitUntilCompleted".into(), + error: error.to_string(), + })?; match waited.error() { None => Ok(()), Some(error) => Err(PlayError::Runtime { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index b5d230153..1d26dfacf 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9478,8 +9478,8 @@ method metal2vulkan-rt::CommandBuffer::kernel_end_time pub fn kernel_end_time(&s method metal2vulkan-rt::CommandBuffer::kernel_start_time pub fn kernel_start_time(&self) -> u64 method metal2vulkan-rt::CommandBuffer::render_command_encoder pub fn render_command_encoder(&self, descriptor: &RenderPassDescriptor) -> Result method metal2vulkan-rt::CommandBuffer::status pub fn status(&self) -> CommandBufferStatus -method metal2vulkan-rt::CommandBuffer::wait_until_completed pub fn wait_until_completed(&self) -method metal2vulkan-rt::CommandBuffer::wait_until_scheduled pub fn wait_until_scheduled(&self) +method metal2vulkan-rt::CommandBuffer::wait_until_completed pub fn wait_until_completed(&self) -> Result<(), Error> +method metal2vulkan-rt::CommandBuffer::wait_until_scheduled pub fn wait_until_scheduled(&self) -> Result<(), Error> method metal2vulkan-rt::CommandQueue::abandon pub fn abandon(&self) method metal2vulkan-rt::CommandQueue::command_buffer pub fn command_buffer(&self) -> Result method metal2vulkan-rt::CommandQueue::device pub fn device(&self) -> &Device @@ -9612,7 +9612,7 @@ method metal2vulkan-rt::SharedEvent::as_event pub fn as_event(&self) -> &Event method metal2vulkan-rt::SharedEvent::notify_listener pub fn notify_listener(&self, value: u64, listener: impl FnOnce(u64) + Send + 'static) -> Result<(), Error> method metal2vulkan-rt::SharedEvent::set_signaled_value pub fn set_signaled_value(&self, value: u64) method metal2vulkan-rt::SharedEvent::signaled_value pub fn signaled_value(&self) -> u64 -method metal2vulkan-rt::SharedEvent::wait_until_signaled_value pub fn wait_until_signaled_value(&self, value: u64, timeout: Duration) -> bool +method metal2vulkan-rt::SharedEvent::wait_until_signaled_value pub fn wait_until_signaled_value(&self, value: u64, timeout: Duration) -> Result method metal2vulkan-rt::Texture::descriptor pub fn descriptor(&self) -> &TextureDescriptor method metal2vulkan-rt::Texture::get_bytes pub fn get_bytes(&self, bytes: &mut [u8], bytes_per_row: u64, bytes_per_image: u64, region: Region, level: u32, slice: u32) -> Result<(), Error> method metal2vulkan-rt::Texture::gpu_resource_id pub fn gpu_resource_id(&self) -> ResourceId @@ -13744,6 +13744,7 @@ variant metal2vulkan-rt::Refusal::EmptyBuffer EmptyBuffer variant metal2vulkan-rt::Refusal::EncoderOpen EncoderOpen variant metal2vulkan-rt::Refusal::FillRange FillRange { start: u64, end: u64, len: u64 } variant metal2vulkan-rt::Refusal::HeapTexturePlace HeapTexturePlace { offset: u64, size: u64, align: u64, heap_len: u64 } +variant metal2vulkan-rt::Refusal::InScheduledHandler InScheduledHandler variant metal2vulkan-rt::Refusal::IndexBufferOffset IndexBufferOffset { offset: u64, length: u64 } variant metal2vulkan-rt::Refusal::IndicesGranted IndicesGranted { class: IndexClass, index: u32 } variant metal2vulkan-rt::Refusal::IndicesInUse IndicesInUse { class: IndexClass, index: u32 } diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 12e38997f..3d71d43c0 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -37,7 +37,7 @@ Columns: | What a call did wrong | 73 | 73 | 0 | 0 | 0 | 0 | 0 | | What a call did wrong, in detail | 174 | 157 | 0 | 0 | 0 | 0 | 0 | | Devices below the new runtime's floor | 8 | 8 | 0 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 56 | 56 | 0 | 0 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 57 | 57 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Limit` | 10 | 10 | 0 | 0 | 0 | 0 | 0 | | The new runtime's `Gap` | 20 | 20 | 0 | 0 | 0 | 0 | 0 | @@ -55,7 +55,7 @@ Columns: | What a call did wrong | 22 | 3 | 5 | 0 | 18 | 8 | 17 | 0 | | What a call did wrong, in detail | 60 | 26 | 23 | 0 | 39 | 26 | 0 | 0 | | Devices below the new runtime's floor | 0 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | -| The new runtime's `Refusal` | 16 | 15 | 0 | 0 | 25 | 0 | 0 | 0 | +| The new runtime's `Refusal` | 16 | 15 | 0 | 0 | 26 | 0 | 0 | 0 | | The new runtime's `Limit` | 0 | 0 | 0 | 7 | 3 | 0 | 0 | 0 | | The new runtime's `Gap` | 0 | 0 | 0 | 0 | 20 | 0 | 0 | 0 | @@ -627,6 +627,7 @@ Columns: | `ZeroRangeShared` | A zero fill of a Shared block (`Device::zero_block_range`) | every device (a public call's own check of its arguments) | `ours`: the host maps a Shared block, and its bytes are zeroed through the mapping, as a zeroed Shared buffer's are; the fill is for the memory the host does not map | 1: `crates/metal2vulkan-rt/src/buffer.rs (zero_block_range)` | `-` | | `ModifiedRange` | A changed range that leaves its buffer (`Buffer::did_modify_range`) | every device (a public call's own check of its arguments) | `ours`: the copy of such a range would write past the buffer's device copy | 1: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` | `-` | | `Committed` | A call on a command buffer already committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal's validation asserts "commit an already committed command buffer", "Completed handler provided after commit call" and "Scheduled handler provided after commit call" | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | +| `InScheduledHandler` | A call a scheduled handler may not make (`CommandBuffer::add_scheduled_handler`) | every device (a public call's own check of its arguments) | `ours`: the consumer's scheduled handlers run on the submit thread, and the one consumer's make none of these calls; a guest's scheduled handler runs in the guest | 1: `crates/metal2vulkan-rt/src/command.rs (not_in_scheduled_handler)` | `-` | | `OtherDevice` | An event, a buffer, a texture or a pipeline state of another device in an encode call (`CommandBuffer::encode_wait_for_event`,... | every device (a public call's own check of its arguments) | `ours`: an event's semaphore, a buffer's block, a texture's image, a pipeline and a block belong to the `VkDevice` that made them | 23: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`, `crates/metal2vulkan-rt/src/blit.rs (copy_from_buffer_to_buffer)` (+20) | `-` | | `NoCommandBuffers` | A queue that may hold no command buffer (`Device::new_command_queue` with a count of 0) | every device (a public call's own check of its arguments) | `ours`: its first `commandBuffer` call would wait forever | 1: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` | `-` | | `EncoderOpen` | A second encoder, an encode call, or a commit or enqueue, while an encoder of the command buffer is open | every device (a public call's own check of its arguments) | `metal-documented`: a command buffer has one active encoder at a time, ended by `endEncoding` before another is made or the command buffer is committed | 1: `crates/metal2vulkan-rt/src/command.rs (open)` | `-` | @@ -1214,6 +1215,7 @@ Each refusal's sites, with the function that builds it. - `rt:Refusal::ZeroRangeShared`: `crates/metal2vulkan-rt/src/buffer.rs (zero_block_range)` - `rt:Refusal::ModifiedRange`: `crates/metal2vulkan-rt/src/buffer.rs (did_modify_range)` - `rt:Refusal::Committed`: `crates/metal2vulkan-rt/src/command.rs (open)` +- `rt:Refusal::InScheduledHandler`: `crates/metal2vulkan-rt/src/command.rs (not_in_scheduled_handler)` - `rt:Refusal::OtherDevice`: `crates/metal2vulkan-rt/src/blit.rs (buffer_copy)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_buffer_to_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (copy_from_texture)`; `crates/metal2vulkan-rt/src/blit.rs (fill_buffer)`; `crates/metal2vulkan-rt/src/blit.rs (synchronize_resource)`; `crates/metal2vulkan-rt/src/command.rs (check)`; `crates/metal2vulkan-rt/src/device.rs (release_block)`; `crates/metal2vulkan-rt/src/encoder.rs (dispatch_threadgroups_with_indirect_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/encoder.rs (set_compute_pipeline_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/encoder.rs (use_resource, 2 sites)`; `crates/metal2vulkan-rt/src/fence.rs (used_on)`; `crates/metal2vulkan-rt/src/pass.rs (check)`; `crates/metal2vulkan-rt/src/render_encoder.rs (draw)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_buffer)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_depth_stencil_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_render_pipeline_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_sampler_state)`; `crates/metal2vulkan-rt/src/render_encoder.rs (set_texture)`; `crates/metal2vulkan-rt/src/texture.rs (new_managed_texture)` - `rt:Refusal::NoCommandBuffers`: `crates/metal2vulkan-rt/src/queue.rs (new_command_queue)` - `rt:Refusal::EncoderOpen`: `crates/metal2vulkan-rt/src/command.rs (open)`