diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index ea75673eb..e70d43775 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -331,6 +331,30 @@ runtime failed it. What a translated shader reports (a resident-set miss, for on the run, not an error: `CommandBuffer::execution_report` reads it once the command buffer completed. +A draw whose pipeline the driver did not make after the draw returned (the runtime makes a draw's +pipeline while the draw goes on) runs nothing, and its command buffer runs on without error: +`CommandBuffer::dropped_draw` names the first, counted: `WorkCounts::draws_dropped_unmade`. A +dispatch's such failure fails its command buffer (`CommandBufferError::PipelineCreation`, +`CommandBuffer::failed_pipeline`). + +A draw or dispatch (a compute encoder's, a render pass's tile dispatch, an execution replay's +draw) whose pipeline the driver is still making `DevicePolicy::pipeline_commit_wait` (4.5 s by +default) after its command buffer's commit runs nothing too (`PipelineWaitPolicy::Bounded`, the +default; a render or compute state's creation likewise waits `DevicePolicy::pipeline_creation_wait`, +4.5 s by default, at most for the pipeline it hands to the runtime's pool), its command buffer +running on, and the command buffers after it draw and dispatch with the pipeline once made. One +call so waits for the driver's makings at most: a state's creation, its creation wait; a `commit`, +until its commit plus its commit wait (its commands share that one deadline, and the commit records +there only what it can, an execution of render commands the CPU writes among them); neither waits +on the other's bound, so a host step that creates a state and commits waits 9 s at most by default, +under a guest's 10 s FIFO check. Made until made under either value, in the call that makes them: a +draw that records nothing, a draw in a pass of custom sample positions or recorded again into +another instance of its pass (in the draw's call or an execution's replay), a device replay's draws +(in its `commit`), and a making that failed, made again by its command's recording. `dropped_draw` +names the first with the error `VK_TIMEOUT`, counted: `WorkCounts::draws_dropped_still_making` and +`dispatches_dropped_still_making`, announced `draw-dropped-still-making` and +`dispatch-dropped-still-making`. `PipelineWaitPolicy::Exact` waits until the pipeline is made. + ## Degrade notices Where the runtime gives Metal's answer only at a cost Metal does not pay (a copy, a scratch diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index aa30032a0..f5812e4e7 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -71,7 +71,7 @@ use super::dirty_pages::DirtyCommit; use super::encoder::{Recorded, Segment}; use super::error::{ internal, invalid, vulkan, CommandBufferError, DeadlockCause, EncoderCall, Error, - FailedPipeline, MeshRecordsOverflow, PipelineCreationCause, Problem, + FailedPipeline, FailedState, MeshRecordsOverflow, PipelineCreationCause, Problem, TessellationRecordsOverflow, TimedOut, }; use super::event::{EventRef, EventShared, SharedEvent}; @@ -119,6 +119,7 @@ use metal2vulkan::bind::{ ExecutionStatus, IndexBoundsPass, ReplayFaults, ResidentRange, ResidentSet, RootTable, StatusReport, }; +use metal2vulkan::device::PipelineWaitPolicy; use metal2vulkan::error::{Feature, Unsupported}; use metal2vulkan::metal::DispatchType; use own::{ @@ -224,6 +225,14 @@ pub(super) struct CommandBufferShared { /// The numbers its host steps give the variant instances they make, drawn at its commit in /// the program's call (`pipeline/kept.rs`). step_numbers: OnceLock, + /// Until when its recordings wait for its draws' and dispatches' pipelines still being made: + /// its commit plus the policy's `pipeline_commit_wait`, set at the commit under + /// `PipelineWaitPolicy::Bounded`; none under `PipelineWaitPolicy::Exact`, where they wait + /// until each is made (`render/pending.rs`, `pending_dispatch.rs`). A cold compile of + /// MoltenVK's on a cold Metal compiler service was measured at 11.6 s inside a state creation + /// a guest's command buffer encoding made (the guest's 10 s FIFO check ended its task); + /// docs/FAST-PATHS.md holds the row. + making_deadline: OnceLock, /// The textures its encoders made for their own commands (`Device::new_planned_texture`), /// held from their making until it completes, whichever of its commands use them (its /// first batch takes them, `submit.rs`). The device's next submission moves each one's image @@ -508,6 +517,10 @@ pub(super) struct State { /// memory, `tests::deferred_calls`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] failures_injected: u32, + /// The error the making of the next draw's pipeline its recording waits for answers, in place + /// of the making's own (a device test's injection, `tests::deferred_calls`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + making_failure_injected: Option, /// `commit` returned with its own work left to run once a render encoder's end is lowered /// (`render/queued_commits.rs`), which has not run: to the program, the command buffer is /// committed. @@ -652,9 +665,12 @@ pub(super) struct State { step_failure: Option, /// The refusal of a host step that failed so (`CommandBufferError::Refused`). refusal: Option, - /// The first draw's pipeline whose making failed, which a host step met + /// The first dispatch's pipeline whose making failed, which a host step met /// (`CommandBufferError::PipelineCreation`). failed_pipeline: Option, + /// The first draw's pipeline whose making failed, which its recording dropped + /// (`render/pending.rs`). + dropped_draw: Option, /// Metal's description of the failure the driver relayed, where the command buffer failed /// with it (`CommandBuffer::error_description`). relayed_description: Option, @@ -1199,6 +1215,13 @@ impl State { .enter(place, self.batches.events(), dispatch_type) } + /// The failure of the making of a draw's pipeline a device test injected + /// ([`CommandBuffer::fail_draw_making`]), taken here. + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn injected_making_failure(&mut self) -> Option { + self.making_failure_injected.take() + } + /// Keep `error`, a render encoder's call's refused as it was lowered /// (`CommandBufferError::CallRefused`): the first such call's. pub(super) fn refuse_call(&mut self, error: Error) { @@ -1781,6 +1804,8 @@ impl CommandBuffer { end_lowered: false, #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] failures_injected: 0, + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + making_failure_injected: None, queued_commit: false, called_over_mutable_map: false, committing: false, @@ -1828,6 +1853,7 @@ impl CommandBuffer { step_failure: None, refusal: None, failed_pipeline: None, + dropped_draw: None, relayed_description: None, report: None, times: Times::default(), @@ -1862,6 +1888,7 @@ impl CommandBuffer { gate: Arc::default(), relayed: Arc::default(), step_numbers: OnceLock::new(), + making_deadline: OnceLock::new(), own_textures: Mutex::new(Vec::new()), fill_slot: Mutex::new([0; 16]), reencode: AtomicU64::new(0), @@ -1960,6 +1987,14 @@ impl CommandBuffer { self.state().failures_injected = count; } + /// Answer the making of the next draw's pipeline its recording waits for + /// (`render/pending.rs`) with `error`, as the driver's failure: a device test's injection + /// (`tests::deferred_calls`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + pub(crate) fn fail_draw_making(&self, error: Error) { + self.state().making_failure_injected = Some(error); + } + /// The bytes its upload arena's regions took: a device test's measure (`tests::rerun_arenas`). #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn upload_bytes(&self) -> u64 { @@ -2535,6 +2570,15 @@ impl CommandBuffer { ) -> Result<(), Error> { let device = &self.0.device; let committed = Instant::now(); + // From here its draws' pipelines still being made are waited for a bound at most: a + // driver's cold compile can outlast a guest's watchdog (`PipelineWaitPolicy`). + let policy = device.compile_device().policy(); + if policy.pipeline_waits == PipelineWaitPolicy::Bounded { + let _ = self + .0 + .making_deadline + .set(committed + policy.pipeline_commit_wait); + } // Textures' host shadows hold their images' texels only until the program gives the device // GPU work of its own, which is what a commit is: raised here, before anything of this // command buffer can run, so a `getBytes` after the commit reads the image and not a @@ -2982,19 +3026,35 @@ impl CommandBuffer { self.state().refusal.clone() } - /// Once the command buffer failed with [`CommandBufferError::PipelineCreation`]: the draw - /// whose `VkPipeline` the driver did not make, by its encoder and its order there, the state - /// and the variant it drew, and the driver's error, which the draw returned where the runtime - /// made the pipeline at the draw (`FailedPipeline`). The first such draw, in encoding order: - /// Metal reports one error per command buffer. No Metal counterpart. + /// Once the command buffer failed with [`CommandBufferError::PipelineCreation`]: the + /// dispatch whose `VkPipeline` the driver did not make, by its encoder and its order there, + /// the state and the variant it ran, and the driver's error, which the dispatch returned + /// where the runtime made the pipeline at the dispatch (`FailedPipeline`). The first such + /// dispatch, in encoding order: Metal reports one error per command buffer. No Metal + /// counterpart. pub fn failed_pipeline(&self) -> Option { self.settle_end(); self.state().failed_pipeline.clone() } - /// Keep `failed`, a draw's pipeline whose making failed, which a host step met - /// (`render/pending.rs`), unless one was kept already: the steps record in encoding order - /// and stop at the first failure, so the one kept is the first. + /// The first draw, in encoding order, whose `VkPipeline` the driver did not make after the + /// draw returned (the runtime makes a draw's pipeline while the draw goes on, + /// `render/pending.rs`): the draw ran nothing, the command buffer running on, without error. + /// Named as [`failed_pipeline`](Self::failed_pipeline) names a dispatch. Counted, each such + /// draw: `WorkCounts::draws_dropped_unmade`. Under `PipelineWaitPolicy::Bounded` (the + /// default), also the first draw or dispatch (a compute dispatch, a render pass's tile + /// dispatch) whose `VkPipeline` was still being made once the command buffer's bound passed, + /// with the error `VK_TIMEOUT`: `WorkCounts::draws_dropped_still_making` and + /// `dispatches_dropped_still_making`. No Metal counterpart: Metal makes a state's pipelines as + /// it makes the state. + pub fn dropped_draw(&self) -> Option { + self.settle_end(); + self.state().dropped_draw.clone() + } + + /// Keep `failed`, a dispatch's pipeline whose making failed, which a host step met + /// (`pending_dispatch.rs`, `render/pending_tile.rs`), unless one was kept already: the steps + /// record in encoding order and stop at the first failure, so the one kept is the first. pub(super) fn fail_pipeline(&self, failed: FailedPipeline) { let mut held = self.state(); if held.failed_pipeline.is_none() { @@ -3002,6 +3062,122 @@ impl CommandBuffer { } } + /// Note `failed`, a draw's pipeline whose making failed, whose recording drops the draw + /// (`render/pending.rs`): kept where it is the first, counted + /// (`WorkCounts::draws_dropped_unmade`). + pub(super) fn drop_draw(&self, failed: FailedPipeline) { + let device = self.device(); + device.shared().counts.draw_dropped_unmade(); + device.degrade(Degradation::DrawDroppedUnmade, || { + let state = match &failed.state { + FailedState::Render(state) => format!( + "render pipeline state {}{}", + state.unique_identifier(), + state + .label() + .map(|label| format!(" `{label}`")) + .unwrap_or_default() + ), + FailedState::Compute(state) => { + format!("compute pipeline state {}", state.unique_identifier()) + } + }; + let variant = { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + failed.variant.hash(&mut hasher); + failed.specialization.hash(&mut hasher); + hasher.finish() + }; + ( + format!( + "draw {} of render encoder {} of a command buffer, of {state}, variant and \ + specialization {variant:016x}", + failed.draw, failed.encoder + ), + format!("the driver failed to make its pipeline: {}", failed.error), + ) + }); + self.keep_dropped(failed); + } + + /// Note `late`, a draw whose pipeline was still being made once the command buffer's bound + /// passed ([`making_deadline`](Self::making_deadline)), whose recording drops the draw + /// (`render/pending.rs`): kept where it is the first, its error `VK_TIMEOUT`, which no + /// driver's creation returns; counted (`WorkCounts::draws_dropped_still_making`), and + /// announced (`draw-dropped-still-making`) where its recording runs, in the program's + /// `commit` or a host step. + pub(super) fn drop_late_draw(&self, late: FailedPipeline) { + let device = self.device(); + device.shared().counts.draw_dropped_still_making(); + let (encoder, draw) = (late.encoder, late.draw); + device.degrade(Degradation::DrawDroppedStillMaking, || { + ( + format!("draw {draw} of render encoder {encoder} of a command buffer"), + format!( + "its pipeline was still being made {} ms after the command buffer's commit", + device + .compile_device() + .policy() + .pipeline_commit_wait + .as_millis() + ), + ) + }); + self.keep_dropped(late); + } + + /// Note `late`, a dispatch whose pipeline was still being made once the command buffer's + /// bound passed ([`making_deadline`](Self::making_deadline)): a compute encoder's + /// (`pending_dispatch.rs`), or a render pass's tile dispatch where `tile` + /// (`render/pending_tile.rs`), whose recording records no dispatch. Kept as + /// [`drop_late_draw`](Self::drop_late_draw) keeps a draw, its error `VK_TIMEOUT`; counted + /// (`WorkCounts::dispatches_dropped_still_making`), and announced + /// (`dispatch-dropped-still-making`) where its recording runs, in the program's `commit` or a + /// host step. + pub(crate) fn drop_late_dispatch(&self, late: FailedPipeline, tile: bool) { + let device = self.device(); + device.shared().counts.dispatch_dropped_still_making(); + let (encoder, dispatch) = (late.encoder, late.draw); + device.degrade(Degradation::DispatchDroppedStillMaking, || { + let what = match tile { + true => "tile dispatch", + false => "dispatch", + }; + let of = match tile { + true => "render encoder", + false => "compute encoder", + }; + ( + format!("{what} {dispatch} of {of} {encoder} of a command buffer"), + format!( + "its pipeline was still being made {} ms after the command buffer's commit", + device + .compile_device() + .policy() + .pipeline_commit_wait + .as_millis() + ), + ) + }); + self.keep_dropped(late); + } + + /// Keep `dropped` as the command buffer's first draw or dispatch that ran nothing, unless one + /// was kept already: the recordings run in encoding order. + fn keep_dropped(&self, dropped: FailedPipeline) { + let mut held = self.state(); + if held.dropped_draw.is_none() { + held.dropped_draw = Some(dropped); + } + } + + /// Until when its recordings wait for its draws' and dispatches' pipelines still being made: + /// set at its commit under `PipelineWaitPolicy::Bounded`, none before it or under `Exact`. + pub(crate) fn making_deadline(&self) -> Option { + self.0.making_deadline.get().copied() + } + /// What the command buffer's execution status words report, once it completed: resident-set /// misses of argument-buffer pointers, and the other conditions [`StatusReport`] names. They /// are facts of the run, not errors; `None` before completion and when the command buffer @@ -3393,10 +3569,20 @@ impl CommandBufferShared { && segments() .filter(|segment| segment.steps_after_the_gpu()) .all(|segment| matches!(segment.work, Deferred::Loop(_))); + // Past its bound its step records the draws and dispatches whose pipelines are still + // being made as nothing (`render/pending.rs`, `pending_dispatch.rs`), waiting for no + // making. + let deadline = self.making_deadline.get().copied(); + let late = deadline.is_some_and(|at| Instant::now() >= at); + let pipelines = match late { + false => segments().any(Segment::steps_after_pipelines), + true => segments().any(Segment::holds), + }; StepWaits { gpu: segments().any(Segment::steps_after_the_gpu) || sparse, queue_alone: checks_alone.then(|| self.queue.vk_queue()), - pipelines: segments().any(Segment::steps_after_pipelines), + pipelines, + until: deadline.filter(|_| pipelines && !late), } } diff --git a/crates/metal2vulkan-runtime/src/deferred.rs b/crates/metal2vulkan-runtime/src/deferred.rs index a9608a10c..4874bb94f 100644 --- a/crates/metal2vulkan-runtime/src/deferred.rs +++ b/crates/metal2vulkan-runtime/src/deferred.rs @@ -254,12 +254,12 @@ impl Deferred { }) } // A pass of draws whose pipelines are being made, or one of which failed, is - // recorded by a host step once they are made, which fails the command buffer for a - // failed one (`render/pending.rs`). One whose executions read the CPU's records as + // recorded by a host step once they are made, which drops the draw of a failed one + // (`render/pending.rs`). One whose executions read the CPU's records as // they stand now waits for them first. Deferred::RenderPass(pass) => { if pass.reads_at_commit() { - pass.wait_made(); + pass.wait_made(command_buffer.making_deadline()); } if pass.making() || pass.failed() { return Ok(Prepared { @@ -464,9 +464,11 @@ impl Deferred { } } - /// Whether the making of a pipeline the work records failed, which its recording makes again, - /// on the thread that records it (`DeferredPass::failed`, `PendingDispatch::failed`): where - /// that fails too the command buffer completes with `CommandBufferError::PipelineCreation`. + /// Whether the making of a pipeline the work records failed (`DeferredPass::failed`, + /// `PendingDispatch::failed`): a dispatch's, which its recording makes again, on the thread + /// that records it, the command buffer completing with + /// `CommandBufferError::PipelineCreation` where that fails too; a draw's, which its + /// recording drops (`render/pending.rs`). pub(super) fn failed(&self) -> bool { match self { Deferred::RenderPass(pass) => pass.failed(), diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 1ee58631e..825d8a2d6 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1859,6 +1859,48 @@ degradations! { a queue's next one run with its own, before the batch before them is submitted; \ their commands, barriers and GPU times are unchanged; CompletionPolicy::Exact \ submits and checks each batch alone"; + /// A draw whose `VkPipeline` the driver was still making once its command buffer's bound + /// passed (`PipelineWaitPolicy::Bounded`, the default: its commit plus the policy's + /// `pipeline_commit_wait`, 4.5 s by default, `render/pending.rs`) ran nothing: its recording records the barriers and the + /// visibility query around it and no draw, and the command buffer runs on without error. + /// Metal makes a render state's pipelines inside `newRenderPipelineState`, so none of its + /// draws waits for a compile; the runtime makes them on its pool, a state's predicted one + /// among them, so a driver's cold compile (seconds on MoltenVK with a cold Metal compiler + /// service) cannot hold the command buffer past a guest's watchdog. Announced where the + /// draw is recorded: in the program's `commit`, or the command buffer's host step. + DrawDroppedStillMaking = "draw-dropped-still-making", Precision, + "the draw's commands ran nothing, where Metal's draw renders; the command buffers \ + committed after the pipeline is made draw with it; CommandBuffer::dropped_draw \ + names the first such draw with the error VK_TIMEOUT; PipelineWaitPolicy::Exact \ + waits until the pipeline is made"; + /// A draw whose `VkPipeline` the driver failed to make after the draw returned (the + /// runtime makes a draw's pipeline while the draw goes on, `render/pending.rs`) ran + /// nothing: its recording records the barriers and the visibility query around it and no + /// draw, and the command buffer runs on without error. Metal makes a render state's + /// pipelines inside `newRenderPipelineState`, which fails there, so none of its draws + /// meets such a failure. The notice names the draw, its state, the variant and the + /// driver's error. Announced where the draw is recorded: in the program's `commit`, or + /// the command buffer's host step. + DrawDroppedUnmade = "draw-dropped-unmade", Precision, + "the draw's commands ran nothing, where Metal's draw renders; the draws after it that \ + need the same pipeline make it again; CommandBuffer::dropped_draw names the first \ + such draw with the driver's error, and WorkCounts::draws_dropped_unmade counts \ + them"; + /// A compute dispatch, or a render pass's tile dispatch, whose `VkPipeline` the driver was + /// still making once its command buffer's bound passed (`PipelineWaitPolicy::Bounded`, + /// the default: its commit plus the policy's `pipeline_commit_wait`, 4.5 s by default, + /// `pending_dispatch.rs`, `render/pending_tile.rs`) ran nothing: its recording records its barriers (a tile dispatch's copies into its + /// scratch and back) and no dispatch, and the command buffer runs on without error. + /// Metal makes a compute state's pipeline inside `newComputePipelineState`, so none of + /// its dispatches waits for a compile; the runtime makes a dispatch's on its pool, so a + /// driver's cold compile cannot hold the command buffer past a guest's watchdog. + /// Announced where the dispatch is recorded: in the program's `commit`, or the command + /// buffer's host step. + DispatchDroppedStillMaking = "dispatch-dropped-still-making", Precision, + "the dispatch ran nothing and wrote nothing, where Metal's dispatch runs; the command \ + buffers committed after the pipeline is made dispatch with it; \ + CommandBuffer::dropped_draw names the first such dispatch with the error \ + VK_TIMEOUT; PipelineWaitPolicy::Exact waits until the pipeline is made"; /// In a build without debug assertions, a notice announced where the runtime's rule /// announces none ([`DegradeNotice::misplaced`] names its kind and [`NoticePlace`]): /// inside a pipeline pool's piece, or, for a kind announced at every occurrence, outside diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 4267c51bf..d555c1541 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -161,6 +161,14 @@ impl Segment { (!self.stepped && self.work.making()) || self.work.holds() } + /// [`steps_after_pipelines`](Self::steps_after_pipelines) once its command buffer's bound + /// passed (`CommandBuffer::making_deadline`): its step records a draw or dispatch whose + /// pipeline is still being made as nothing, so its batch waits only for what its step left + /// (`Deferred::holds`). + pub(super) fn holds(&self) -> bool { + self.work.holds() + } + /// Whether it is a dispatch whose pipelines were being made (`pending_dispatch.rs`): an /// encoder encoded again (`replay.rs`) leaves one of its own in its place, prepared as the /// commit prepared this one, and waits for no making. diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index c6e6ed2a0..d39858b5a 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -2020,13 +2020,16 @@ pub enum CommandBufferError { /// `PageFault` on an M3 Max with 26.7 (the consumer's). Code 3 is /// [`CommandBufferError::PageFault`], and 11 [`CommandBufferError::DeviceLost`]. Execution(u64), - /// The driver did not make the `VkPipeline` of a draw the command buffer recorded, which - /// its submission waited for: the runtime makes a draw's pipeline while the draw goes on - /// and the command buffer's batch waits for it, so the failure surfaces here, not at the - /// draw. The batch that records the draw, and those after it, did not run. + /// The driver did not make the `VkPipeline` of a dispatch the command buffer recorded (a + /// compute encoder's, or a render encoder's tile dispatch), which its submission waited + /// for: the runtime makes a dispatch's pipeline while the dispatch goes on and the command + /// buffer's batch waits for it, so the failure surfaces here, not at the dispatch. The batch + /// that records the dispatch, and those after it, did not run. /// [`CommandBuffer::failed_pipeline`](crate::CommandBuffer::failed_pipeline) names the - /// state and gives the driver's error. Metal makes a state's pipelines as it makes the state, - /// and has no such failure. + /// state and gives the driver's error. A draw's such failure drops the draw alone, the + /// command buffer running on + /// ([`CommandBuffer::dropped_draw`](crate::CommandBuffer::dropped_draw)). Metal makes a + /// state's pipelines as it makes the state, and has no such failure. PipelineCreation(PipelineCreationCause), /// A command of the command buffer named a buffer over the caller's host pages (a no-copy /// buffer, a heap over the caller's memory, or a resource placed in one) that was rebound @@ -2200,8 +2203,10 @@ impl PipelineCreationCause { } } -/// A draw's or a dispatch's `VkPipeline` the driver did not make -/// ([`CommandBufferError::PipelineCreation`]): the command, by its encoder and its order there; +/// A draw's or a dispatch's `VkPipeline` the driver did not make (a dispatch's failing its +/// command buffer, [`CommandBufferError::PipelineCreation`]; a draw's dropping the draw, +/// [`CommandBuffer::dropped_draw`](crate::CommandBuffer::dropped_draw)): the command, by its +/// encoder and its order there; /// the pipeline state it ran, and the variant of that state and the specialization its pipeline /// took; and the error the making returned, which the command returned where the runtime made /// the pipeline at the command. A command buffer keeps the first, in encoding order, as Metal diff --git a/crates/metal2vulkan-runtime/src/pending_dispatch.rs b/crates/metal2vulkan-runtime/src/pending_dispatch.rs index b79bb1deb..f16430b9c 100644 --- a/crates/metal2vulkan-runtime/src/pending_dispatch.rs +++ b/crates/metal2vulkan-runtime/src/pending_dispatch.rs @@ -24,11 +24,19 @@ //! with `CommandBufferError::PipelineCreation`, its batch and those after it unrun, and //! `CommandBuffer::failed_pipeline` names the dispatch: its encoder's place and its order among //! the encoder's dispatches, the state, its variant and specialization, and the driver's error. +//! - **A making past its bound.** Under `PipelineWaitPolicy::Bounded` (the default) the recording +//! waits for a making until its command buffer's bound at most, its commit plus the policy's +//! `pipeline_commit_wait` (4.5 s by default), as a draw's does (`render/pending.rs`): a dispatch +//! whose making is still in flight then records its barrier and no dispatch, so writes nothing, +//! the command buffer running on without error. `CommandBuffer::dropped_draw` names the first +//! such command with the error `VK_TIMEOUT`; counted, +//! `WorkCounts::dispatches_dropped_still_making`; announced `dispatch-dropped-still-making`. +//! Under `PipelineWaitPolicy::Exact` it waits until each is made. use super::binding::{self, PushWrite, SetWrite}; use super::command_buffer::CommandBuffer; use super::encoder::{EncoderCore, RecordedSegment}; -use super::error::{Error, FailedPipeline, FailedState}; +use super::error::{vulkan, Error, FailedPipeline, FailedState}; use super::indirect_dispatch::FlatPreprocess; use super::pipeline::{ComputePipelineState, RawPipeline, RegionKey, RegionPipeline, Variant}; use super::resource::ResourceKey; @@ -202,33 +210,49 @@ impl PendingDispatch { EncoderUses::new(false).finish() } - /// Its regions' `VkPipeline`s, waiting for each making: one whose making failed made again - /// here. Where that fails, `command_buffer` fails so (`CommandBuffer::fail_pipeline`). - fn made(&self, command_buffer: &CommandBuffer) -> Result>, Error> { + /// Its regions' `VkPipeline`s, waiting for each making until `command_buffer`'s bound at + /// most, where it has one: one whose making failed made again here. Where that fails, + /// `command_buffer` fails so (`CommandBuffer::fail_pipeline`). `None` where a making is still + /// in flight at the bound: the dispatch is dropped (`CommandBuffer::drop_late_dispatch`, the + /// module docs). + fn made(&self, command_buffer: &CommandBuffer) -> Result>>, Error> { + let deadline = command_buffer.making_deadline(); + let failed = |key: &RegionKey, error| FailedPipeline { + encoder: self.encoder, + draw: self.dispatch, + state: FailedState::Compute(self.state.clone()), + variant: self.variant.key().clone(), + specialization: self.variant.constants(key), + error, + }; let mut made = Vec::with_capacity(self.pipelines.len()); for (key, pipeline) in &self.pipelines { let outcome = match pipeline { RegionPipeline::Made(pipeline) => Ok(Arc::clone(pipeline)), RegionPipeline::Making(pending) => { - pending.wait().or_else(|_| self.variant.make_region(key)) + let waited = match deadline { + Some(deadline) => pending.wait_until(deadline), + None => Some(pending.wait()), + }; + let Some(waited) = waited else { + // Still being made at the bound: the dispatch runs nothing, and a later + // command buffer dispatches with the pipeline once it is made. + let late = failed(key, vulkan(vk::Result::TIMEOUT)); + command_buffer.drop_late_dispatch(late, false); + return Ok(None); + }; + waited.or_else(|_| self.variant.make_region(key)) } }; match outcome { Ok(pipeline) => made.push(pipeline), Err(error) => { - command_buffer.fail_pipeline(FailedPipeline { - encoder: self.encoder, - draw: self.dispatch, - state: FailedState::Compute(self.state.clone()), - variant: self.variant.key().clone(), - specialization: self.variant.constants(key), - error: error.clone(), - }); + command_buffer.fail_pipeline(failed(key, error.clone())); return Err(error); } } } - Ok(made) + Ok(Some(made)) } /// Its segment of `command_buffer`, recorded once its pipelines are made: its barrier, then @@ -248,7 +272,7 @@ impl PendingDispatch { /// failed fails the command buffer as it does where the dispatch records. pub(super) fn record(&self, command_buffer: &CommandBuffer) -> Result { let pipelines = self.made(command_buffer)?; - if let Some(creation) = &self.creation { + if let (Some(creation), Some(pipelines)) = (&self.creation, &pipelines) { creation.get_or_init(|| pipelines.iter().map(|made| made.created_in).collect()); } if command_buffer.encoder_rebound(self.encoder) { @@ -258,14 +282,18 @@ impl PendingDispatch { let record = |raw: &Vk, cb: vk::CommandBuffer| { // SAFETY: the segment's command buffer is recording outside a render pass, by this // call alone; what the dispatch records was retained at the dispatch, its pipelines - // with the segment, and they are its variant's, one per region. + // with the segment, and they are its variant's, one per region. A dropped dispatch + // (none) records its barrier alone, which the encoder's later commands count on. unsafe { if let Some(barrier) = barrier { barrier.record(raw, cb); } - recording.record(raw, cb, made); + if let Some(made) = made { + recording.record(raw, cb, made); + } } }; - EncoderCore::untracked_segment(command_buffer, record, Box::new(pipelines.clone())) + let retained = pipelines.clone().unwrap_or_default(); + EncoderCore::untracked_segment(command_buffer, record, Box::new(retained)) } } diff --git a/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs b/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs index 38ece331d..662bcf7c9 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/dispatch_making.rs @@ -27,11 +27,20 @@ //! takes its key's residual form (`render/residual.rs`); any other hands its own making to the //! pool, as before (on MoltenVK the kernel's MSL library is then compiled already, so that //! making is its specialization and Metal's pipeline compile). -//! The making runs on the creating thread and ends before the creation returns: none runs past -//! the state's release, which would hold the variant and the device past the program's last -//! drop, which Metal's never does. Its specialized notices wait for the first dispatch that -//! takes it, which announces them naming what it binds. A creation inside a host step, a tile -//! function's state and a stand-in compile make nothing here. +//! Under `PipelineWaitPolicy::Bounded` (the default) the making is handed to the device's pool, +//! kept by the state's piece holds as a dispatch's is, and the creation waits for it the +//! policy's `pipeline_creation_wait` (4.5 s by default) at most, as a render state's does +//! (`render.rs`): a driver's cold +//! compile holds the thread creating the state, which a host may create inside a command +//! buffer's encoding, no longer, and a dispatch that finds the making in flight takes it, its +//! command buffer waiting a bound for it in turn (`WorkCounts::creations_left_making`). A +//! making still running then may run past the state's release, holding the variant and the +//! device until it ends. Under `PipelineWaitPolicy::Exact` it runs on the creating thread and +//! ends before the creation returns: none runs past the state's release, which would hold the +//! variant and the device past the program's last drop, which Metal's never does. Its +//! specialized notices wait for the first dispatch that takes it, which announces them naming +//! what it binds. A creation inside a host step, a tile function's state and a stand-in compile +//! make nothing here. //! - **Where the request states no threadgroup, the creation predicts nothing**, because nothing //! in the request answers what the dispatch will ask for. The local size is the dispatch's own //! call, and a size guessed from the state instead -- Apple's guide to threadgroup sizes @@ -70,8 +79,10 @@ use crate::degradation::{BoundFormats, Occurrence}; use crate::error::Error; use crate::Device; use metal2vulkan::bind::{BindState, BoundSampler, Dispatch, DispatchRegion, SamplerDescriptor}; +use metal2vulkan::device::PipelineWaitPolicy; use metal2vulkan::pipeline::{ComputePipeline, ComputePipelineDescriptor, SlotInterface}; use std::sync::Arc; +use std::time::Instant; /// A region's `VkPipeline` for a dispatch that records it later /// ([`Variant::begin_region_pipeline`]). @@ -150,7 +161,7 @@ impl Variant { self.announce(&key, formats); let residual = self.residual_made(&key, formats); let pending = ticket.pending(); - pending.queued_at(self.pooled(holds, key, ticket)); + pending.queued_at(self.pooled(holds, key, ticket, false)); match residual { // Handed to the pool: nothing waits for the making. Some(made) => { @@ -212,13 +223,21 @@ impl Variant { } } - /// Make, on this thread, the `VkPipeline` of the region a first dispatch of a state of - /// `descriptor` on this variant, its base, is predicted to take (the module docs), where no - /// caller made or began it: its notices wait for the first dispatch that takes it. A + /// Make the `VkPipeline` of the region a first dispatch of a state of `descriptor` on this + /// variant, its base, is predicted to take (the module docs), where no caller made or began + /// it: its notices wait for the first dispatch that takes it. Under + /// `PipelineWaitPolicy::Bounded` handed to the device's pool, kept by `holds`, the state's, + /// and waited for the policy's `pipeline_creation_wait` at most; under `Exact` made on this + /// thread. A /// descriptor that requires no threadgroup size predicts no region at all, and a prediction /// the plan refuses or that runs on another variant makes nothing; a failed making is not /// kept and refuses nothing, its dispatch meeting it as before. - pub(super) fn make_at_creation(&self, device: &Device, descriptor: &ComputePipelineDescriptor) { + pub(super) fn make_at_creation( + self: &Arc, + device: &Device, + descriptor: &ComputePipelineDescriptor, + holds: &Arc>, + ) { if crate::exit_guard::in_host_step() { return; } @@ -228,6 +247,19 @@ impl Variant { let Begun::Yours(ticket) = self.pipelines.begin(&key) else { return; }; + let policy = device.compile_device().policy(); + if policy.pipeline_waits == PipelineWaitPolicy::Bounded { + let pending = ticket.pending(); + pending.queued_at(self.pooled(holds, key, ticket, true)); + // A making still running at the bound goes on for the dispatches that take it. + if pending + .wait_until(Instant::now() + policy.pipeline_creation_wait) + .is_none() + { + device.shared().counts.creation_left_making(); + } + return; + } let made = self .objects .pipeline(&key, Notices::FirstDraw) @@ -269,12 +301,15 @@ impl Variant { } /// Hand the making of `key`, `ticket`'s, to the device's pool, kept by `holds`: a - /// dispatch's, which announced its notices. Where it waits there. + /// dispatch's, which announced its notices, or the creation's where `at_creation`, whose + /// notices wait for the first dispatch that takes it, counted as the creation's making. Where + /// it waits there. fn pooled( self: &Arc, holds: &Arc>, key: RegionKey, ticket: Ticket, + at_creation: bool, ) -> Place { let keeping = holds.keep(RegionHeld::Making(Arc::clone(self), key, Box::new(ticket))); let device = self.objects.device.clone(); @@ -288,10 +323,18 @@ impl Variant { RegionHeld::Making(variant, key, ticket) => (variant, key, *ticket), other => return lease.give_back(other, None), }; + let notices = match at_creation { + true => Notices::FirstDraw, + false => Notices::Announced, + }; let made = variant .objects - .pipeline(&key, Notices::Announced) + .pipeline(&key, notices) .map(|made| made.kept_at(&variant.objects, kept::Place::Region(key.clone()))); + if at_creation && made.is_ok() { + let counts = &variant.objects.device.shared().counts; + counts.creation_pipeline_made(crate::work_counts::Predicted::Dispatch); + } // Its callers take it from the making: from the settle, the batches that wait for it // may run and complete while this piece still holds the variant, and the device with // it, until it gave it back. A trail spans that (`trails.rs`). diff --git a/crates/metal2vulkan-runtime/src/pipeline/making.rs b/crates/metal2vulkan-runtime/src/pipeline/making.rs index 92eab41b5..5cf21c656 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/making.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/making.rs @@ -32,6 +32,7 @@ use crate::device::lock; use crate::error::{internal, Error}; use std::hash::Hash; use std::sync::{Arc, Condvar, Mutex}; +use std::time::Instant; /// A memo of objects made on demand, each made once at a time (the module docs). pub(crate) struct Making { @@ -141,6 +142,31 @@ impl Turn { } } + /// [`wait`](Self::wait), but no later than `deadline`: `None` where the making had not + /// finished by then. + fn wait_until(&self, deadline: Instant) -> Option> { + debug_assert!( + !super::budget::holds_turn(), + "a making waited for another while holding a budget turn" + ); + self.hasten(match crate::exit_guard::in_host_step() { + true => Urgency::HostStep, + false => Urgency::Program, + }); + let mut state = lock(&self.state); + loop { + if let TurnState::Finished(outcome) = &*state { + return Some(outcome.clone()); + } + let left = deadline.checked_duration_since(Instant::now())?; + state = self + .done + .wait_timeout(state, left) + .unwrap_or_else(std::sync::PoisonError::into_inner) + .0; + } + } + /// Its outcome, once it finished. fn outcome(&self) -> Option> { match &*lock(&self.state) { @@ -291,6 +317,12 @@ impl Pending { self.turn.wait() } + /// [`wait`](Self::wait), but no later than `deadline`: `None` where it had not finished by + /// then (a command buffer's bound for the pipelines it draws with, `render/pending.rs`). + pub(crate) fn wait_until(&self, deadline: Instant) -> Option, Error>> { + self.turn.wait_until(deadline) + } + /// It waits at `place` in the device's pool. pub(crate) fn queued_at(&self, place: Place) { self.turn.queued_at(place); diff --git a/crates/metal2vulkan-runtime/src/pipeline/mod.rs b/crates/metal2vulkan-runtime/src/pipeline/mod.rs index 0973fff91..0f549a8f4 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/mod.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/mod.rs @@ -748,9 +748,11 @@ impl ComputePipelineState { device.keep_room(); } // Its first dispatch's predicted `VkPipeline`, made where Metal compiles - // (`dispatch_making.rs`). A stand-in compile is never dispatched. + // (`dispatch_making.rs`), a making the pool runs kept by the state's piece holds. A + // stand-in compile is never dispatched. + let pieces = piece_holds::PieceHolds::new(); if let (Kernel::Compute(descriptor), false) = (&kernel, stand_in) { - base.make_at_creation(device, descriptor); + base.make_at_creation(device, descriptor, &pieces); } device.degrade_absent_reads(&base.shared_pipeline().dependencies, |_| { function.function.info().name.to_string() @@ -795,7 +797,7 @@ impl ComputePipelineState { folded_refused: AtomicBool::new(false), added_unsupported, label: options.label.clone(), - pieces: piece_holds::PieceHolds::new(), + pieces, at_bind_views, planned: Mutex::new(None), }; diff --git a/crates/metal2vulkan-runtime/src/pipeline/predicted.rs b/crates/metal2vulkan-runtime/src/pipeline/predicted.rs index 45d8a3d7b..f15d951a7 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/predicted.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/predicted.rs @@ -1,11 +1,11 @@ -//! The `VkPipeline` a render state's first draw is predicted to take, made inside its creation, +//! The `VkPipeline` a render state's first draw is predicted to take, begun inside its creation, //! where Metal compiles. //! //! Metal pays a render state's compile inside `newRenderPipelineState`, outside any command //! buffer. The runtime made a state's `VkPipeline`s at its draws, so on MoltenVK a cold making of //! seconds sat inside a command buffer's execution, past a guest's GPU watchdog. A state's -//! creation now makes, synchronously, the `VkPipeline` of the key a first draw takes under -//! Metal's defaults, built from the state alone: +//! creation now begins the making of the `VkPipeline` of the key a first draw takes under Metal's +//! defaults, built from the state alone (where it runs: the end of these docs): //! //! - **The variant** the base, where the plan of a draw binding the vertex buffers alone (below) //! runs on it (a variant only a draw needs is made by that draw, as before); **the @@ -68,9 +68,15 @@ //! state. A draw whose key the creation did not make makes its own, as before's records of the //! driver's data still serve that making where the same pipeline was made before. //! -//! The predicted key's making runs on the creating thread, joined before the creation returns -//! (`RenderVariant::make_at_creation`), at the rank of a making the program waits for. A key -//! predicted on the early-tests variant (above) is made there, on that variant. +//! Under `PipelineWaitPolicy::Exact` the predicted key's making runs on the creating thread, +//! joined before the creation returns (`RenderVariant::make_at_creation`), at the rank of a +//! making the program waits for. Under `PipelineWaitPolicy::Bounded` (the default) it is handed to +//! the device's pool, kept by the state as a draw's making is, and the creation returns: a host +//! that creates a state inside a command buffer's encoding (a guest's state looked up there +//! first) is not held by a driver's cold compile, measured at 11.6 s on MoltenVK with a cold +//! Metal compiler service. The first draw takes the making in flight, and its command buffer +//! waits a bound for it (`render/pending.rs`). A key predicted on the early-tests variant (above) +//! is made there, on that variant. use super::graphics::{FixedState, GraphicsKey}; use super::render::{GraphicsState, RenderVariant, StateDescriptor}; diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 6ecdfcf33..ddf7314e2 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -69,6 +69,7 @@ use crate::values::Size; use crate::Device; use metal2vulkan::bind::{BindShape, BindState, BindingPlan, FragmentTests}; use metal2vulkan::cache::{Hash256, PipelineKey, SpecializationKey, VariantKey}; +use metal2vulkan::device::PipelineWaitPolicy; use metal2vulkan::library::{CompiledFunction, FunctionCompileKey}; use metal2vulkan::metal::{BindingAccess, PixelFormat, PrimitiveTopologyClass, RenderStages}; use metal2vulkan::pipeline::{ @@ -80,6 +81,7 @@ use metal2vulkan::reflection::{LinkedUseAnswers, RenderPipelineReflection}; use std::any::Any; use std::collections::VecDeque; use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::time::Instant; mod residual; @@ -2663,6 +2665,35 @@ impl RenderVariant { self.made_or_make(key, render_pass, (state, formats)) } + /// The `VkPipeline` of `key` for an execution's settle at commit, which records nothing + /// (`render/executions.rs`), against `render_pass`: from the memo, the making in flight for + /// it, or begun now as a draw's is ([`begin_graphics_pipeline`](Self::begin_graphics_pipeline): + /// linked here where its shaders' libraries are made, else handed to `device`'s pool), so the + /// commit compiles nothing on the program's thread; the host step's draw of the key waits for + /// it until its command buffer's bound at most (`render.rs`). Under + /// `PipelineWaitPolicy::Exact` made now ([`graphics_pipeline`](Self::graphics_pipeline)). + pub(crate) fn settle_graphics_pipeline( + self: &Arc, + device: &Device, + key: &GraphicsKey, + render_pass: &Arc, + (state, formats): (&GraphicsState, crate::degradation::BoundFormats<'_>), + ) -> Result { + if device.compile_device().policy().pipeline_waits == PipelineWaitPolicy::Exact { + return self + .graphics_pipeline(key, render_pass, (state, formats)) + .map(DrawPipeline::Made); + } + device.shared().counts.graphics_pipeline_looked_up(); + Ok(match self.pipelines.begin_at(key) { + (Begun::Made(made), _) => DrawPipeline::Made(made), + (Begun::Pending(pending), _) => DrawPipeline::Making(pending), + (Begun::Yours(ticket), _) => { + self.make_drawn(device, key, render_pass, (state, formats), ticket) + } + }) + } + /// [`graphics_pipeline`](Self::graphics_pipeline)'s finding or making, uncounted. fn made_or_make( self: &Arc, @@ -2706,20 +2737,31 @@ impl RenderVariant { .then(|| libraries.claim(shared, &content.names(&self.objects, &self.pipeline, key))) } - /// The `VkPipeline`s of `keys`, each against its pass (a pass of the key's `pass`), made at - /// the creation of `state`, before any draw, at once: the first on this thread, the others - /// on the device's pool, joined before this returns (`Pool::join_all`, the owner's HITCH - /// rules 1 and 3). What the program or host sees is decided on this thread, in `keys`' order: - /// each key's memo entry begun before (a key made already, or being made by another caller, - /// is not this creation's), and its creation log line numbered before. Each piece settles its - /// own key's memo entry as its pipeline is made, a failed one not kept, and the join returns - /// once every piece settled. The concurrent part only calls the driver and settles its - /// entries. Their specialized notices wait for their first draws + /// The `VkPipeline`s of `keys`, each against its pass (a pass of the key's `pass`), begun at + /// the creation of `state`, before any draw. What the program or host sees is decided on this + /// thread, in `keys`' order: each key's memo entry begun before (a key made already, or being + /// made by another caller, is not this creation's), and its creation log line numbered + /// before. Under `PipelineWaitPolicy::Bounded` (the default) each making is handed to the + /// device's pool, kept by the state's piece holds as a draw's is ([`pooled`](Self::pooled)), + /// and the creation waits for them the policy's `pipeline_creation_wait` (4.5 s by default) at + /// most, one deadline for all of them, as Metal compiles in its creation: a driver's cold + /// compile (seconds on MoltenVK with a cold Metal compiler service) holds the thread creating + /// the state, which a host may create inside a command buffer's encoding, no longer; a draw + /// that finds the making in flight takes it (`render/pending.rs`), its command buffer waiting a + /// bound for it in turn (`WorkCounts::creations_left_making`). Under + /// `PipelineWaitPolicy::Exact` they are made before the creation returns: the first on this + /// thread, the others on the device's pool, joined (`Pool::join_all`, the owner's HITCH rules 1 + /// and 3). Each piece settles its own key's memo entry as its pipeline is made, a failed one + /// not kept, and the join returns once every piece settled. The concurrent part only calls the + /// driver and settles its entries. Their specialized notices wait for their first draws /// ([`first_use`](Self::first_use)). Each key is its variant's. pub(crate) fn make_at_creation( keys: Vec<(Arc, GraphicsKey, RenderPassObject)>, state: &GraphicsState, ) { + let device = &state.0.device; + let joined = device.compile_device().policy().pipeline_waits == PipelineWaitPolicy::Exact; + let mut handed = Vec::new(); let mut pending = Vec::with_capacity(keys.len()); let mut pieces: Vec> = Vec::with_capacity(keys.len()); for (variant, key, pass) in keys { @@ -2738,6 +2780,15 @@ impl RenderVariant { // Its libraries claimed here, on the creating thread, where the device links them: // the device's, found by every later key and state that shares a part. let claimed = variant.claim_libraries(&key); + if !joined { + handed.push(variant.pooled( + state, + (key, Arc::new(pass), ticket), + (line, claimed), + true, + )); + continue; + } pending.push(ticket.pending()); // The piece owns the variant (its modules, layouts and immutable samplers, and the // device with its pipeline cache), the key (the specialization's bytes), the key's @@ -2771,8 +2822,19 @@ impl RenderVariant { drop(ticket.settle(made)); })); } + // Those handed to the pool, waited for a bound at most: a making still running then goes + // on for the draws that take it. + let deadline = Instant::now() + device.compile_device().policy().pipeline_creation_wait; + for making in &handed { + if making.wait_until(deadline).is_none() { + device.shared().counts.creation_left_making(); + } + } // The full join: every key begun here is settled before the creation returns. - drop(state.0.device.shared().pipeline_pool.join_all( + if pieces.is_empty() { + return; + } + drop(device.shared().pipeline_pool.join_all( pieces, true, // Each key handed to the pool waits there: a draw that finds it in flight, its @@ -2975,20 +3037,38 @@ impl RenderVariant { Some(formats), Occurrence::Made, ); - let pending = ticket.pending(); // Its creation log line numbered here, on the draw's thread in the guest's order. let line = state .0 .log .as_ref() .map(|log| log.begin((&self.key, &self.pipeline, key, self.logged_spirv()))); - let key = key.clone(); - let keeping = state.0.pieces.keep(PieceHeld::Draw( - Arc::clone(self), - Arc::clone(compatible), - Box::new(ticket), - )); - let place = device.shared().pipeline_pool.run(Box::new(move || { + let handed = (key.clone(), Arc::clone(compatible), ticket); + DrawPipeline::Making(self.pooled(state, handed, (line, claimed), false)) + } + + /// Hand the making of `key`, `ticket`'s, to the device's pool, against `pass`, a pass of + /// `key.pass`, kept by `state`'s piece holds (the state's release stops a piece not started, + /// failing the making), logged on `line`, linked from `claimed` where the device links + /// libraries: a draw's making, whose specialized notices the draw announced; or, where + /// `at_creation`, a state creation's predicted key's, whose notices wait for its first draw + /// ([`first_use`](Self::first_use)), counted made. The making, to look at later, queued at + /// its place there. + fn pooled( + self: &Arc, + state: &GraphicsState, + (key, pass, ticket): ( + GraphicsKey, + Arc, + Ticket, + ), + (line, claimed): (Option, Option), + at_creation: bool, + ) -> Pending { + let pending = ticket.pending(); + let keeping = + (state.0.pieces).keep(PieceHeld::Draw(Arc::clone(self), pass, Box::new(ticket))); + let place = (self.objects.device.shared().pipeline_pool).run(Box::new(move || { // Where the state let go meanwhile, the piece stops: its ticket went with the // state, failing the making. let Some((lease, held)) = keeping.start() else { @@ -3000,11 +3080,15 @@ impl RenderVariant { }; #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] super::pool::held::mid_making(); + let notices = match at_creation { + true => Notices::FirstDraw, + false => Notices::Announced, + }; let make = || { variant.objects.graphics_pipeline( &variant.pipeline, &key, - (&*compatible, Notices::Announced), + (&*compatible, notices), claimed, ) }; @@ -3012,6 +3096,10 @@ impl RenderVariant { None => make(), Some(line) => line.made(&variant.objects.device, make), }; + if at_creation && made.is_ok() { + let counts = &variant.objects.device.shared().counts; + counts.creation_pipeline_made(crate::work_counts::Predicted::Render); + } // Its callers take it from the making: from the settle, the batches that wait // for it may run and complete while this piece still holds the variant and the // pass, and the device with them, until it gave them back. A trail spans that @@ -3027,7 +3115,7 @@ impl RenderVariant { ); })); pending.queued_at(place); - DrawPipeline::Making(pending) + pending } /// The compute `VkPipeline`s of the variant's emulated object and mesh functions under a diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index ce7d23b61..812f5d086 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -1436,6 +1436,10 @@ pub(crate) struct RenderLowering { /// The encoder records an execution's commands (`render/executions.rs`): a draw that needs /// another instance than the execution's is refused. replaying: bool, + /// The place among the command buffer's ended encoders of the encoder whose execution it + /// replays (`RenderExecution`), which names a draw of the commands it drops + /// (`CommandBuffer::drop_late_draw`); `None` where it replays none. + executing_encoder: Option, /// The encoder records the current instance's draws again into an instance that leaves more /// colors out of its subpass (`render/reroute.rs`): a draw that would record elsewhere, or /// whose variant the interlocked storage form refuses, fails the reroute. @@ -2006,6 +2010,7 @@ impl RenderLowering { draw_calls: 0, tile_dispatch_calls: 0, replaying: false, + executing_encoder: None, rerouting: false, forms: BufferForms::Bound, replayed: None, @@ -8509,14 +8514,59 @@ impl RenderLowering { None => { let watch = EachWatch::start(); let key = draw_key(); - let (draw_pipeline, own) = match deferrable { - true => variant.begin_graphics_pipeline( + // An execution's replay records now: under its command buffer's bound its draw + // waits for its making on the device's pool (most begun by the settle at commit, + // `RenderExecution::settle`) until the bound at most, past which it records + // nothing. Not a device replay's draw, of one recording for every command. + let bounded = (self.replaying && self.replayed.is_none() && !self.rerouting) + && !(empty || culled) + && self.layout.sample_positions.is_empty(); + let deadline = match bounded { + true => self.core.command_buffer().making_deadline(), + false => None, + }; + let (draw_pipeline, own) = match (deferrable, deadline) { + (true, _) => variant.begin_graphics_pipeline( &device, &key, &compatible, (&pipeline, &formats), ), - false => ( + (false, Some(deadline)) => { + let begun = variant.begin_graphics_pipeline( + &device, + &key, + &compatible, + (&pipeline, &formats), + ); + match begun { + (DrawPipeline::Making(making), _) => { + match making.wait_until(deadline) { + Some(Ok(made)) => (DrawPipeline::Made(made), true), + // A failed making is made again here, as a caller after one + // does (`making.rs`). + Some(Err(_)) => ( + DrawPipeline::Made(variant.graphics_pipeline_now( + &device, + &key, + &compatible, + (&pipeline, &formats), + )?), + true, + ), + // Still being made at the bound: the draw records nothing, + // before anything of it is tracked, as a draw whose pipeline + // a capture misses does; later command buffers draw with it. + None => { + self.drop_late_replayed_draw(&variant, specialization)?; + return Ok(()); + } + } + } + made => made, + } + } + (false, None) => ( DrawPipeline::Made(variant.graphics_pipeline_now( &device, &key, diff --git a/crates/metal2vulkan-runtime/src/render/executions.rs b/crates/metal2vulkan-runtime/src/render/executions.rs index 243d781e8..6eb8b1404 100644 --- a/crates/metal2vulkan-runtime/src/render/executions.rs +++ b/crates/metal2vulkan-runtime/src/render/executions.rs @@ -305,7 +305,9 @@ use crate::indirect_execute::{self, unstrided_buffer, ExecutionRange}; use crate::pipeline::budget::Urgency; use crate::pipeline::RenderPipelineState; use crate::pipeline::Settled; -use crate::pipeline::{BufferForms, FixedState, GraphicsKey, RawPipeline, RenderVariant}; +use crate::pipeline::{ + BufferForms, DrawPipeline, FixedState, GraphicsKey, Pending, RawPipeline, RenderVariant, +}; use crate::rate_mapped_pass::RateMappedPass; use crate::render_pass::{ColorTarget, PassLayout, Target}; use crate::render_state::EncoderState; @@ -341,6 +343,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::ops::Range; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Instant; mod ahead; mod cause; @@ -757,6 +760,7 @@ impl RenderLowering { .map_or(IndirectCommandCheckNeeds::ALL, |(_, needs)| *needs), check: check.map(|(check, _)| Mutex::new(check)), read_at: AtomicU64::new(indirect_execute::NOT_READ), + encoder: self.core.command_buffer().state().open_encoder_place(), }); // Its commands may name any pipeline state, reading handles in any stage. self.command_encoded(every_render_stage()); @@ -959,6 +963,9 @@ pub(crate) struct RenderExecution { /// read them after (`IndirectCommandBuffer::cpu_writes`); `indirect_execute::NOT_READ` until /// then ([`rewritten`](Self::rewritten)). read_at: AtomicU64, + /// Its encoder's place among the command buffer's ended encoders, which names a draw of its + /// commands that its replay drops (`CommandBuffer::drop_late_draw`). + encoder: usize, } /// The encoder's state an execution's draws take: as the call found it, its tables only where @@ -1784,8 +1791,9 @@ fn object_threadgroup_lengths(record: &CommandRecord) -> BTreeMap { /// What an execution's settle at commit made for its host step's draw of one primitive type: the /// variant, and the draw's `VkPipeline` in the execution's instance where the settle could make -/// it. The command buffer holds them until it completes. -pub(crate) type SettledDraw = (Arc, Option>); +/// it, made or being made on the device's pool (`RenderVariant::settle_graphics_pipeline`). The +/// command buffer holds them until it completes. +pub(crate) type SettledDraw = (Arc, Option); impl RenderLowering { /// Make, into `made`, what a command's draw of `pipeline` under the encoder's state (an @@ -1946,9 +1954,14 @@ impl RenderLowering { &|k| plan.specialized_value(k), Some(&formats), ); - let raw = variant.graphics_pipeline(&key, &self.current.compatible, (state, &formats))?; - variant.first_use(&raw, &key.specialization, &formats); - Ok((variant, Some(raw))) + let device = self.core.device(); + let compatible = &self.current.compatible; + let drawn = + variant.settle_graphics_pipeline(device, &key, compatible, (state, &formats))?; + if let DrawPipeline::Made(raw) = &drawn { + variant.first_use(raw, &key.specialization, &formats); + } + Ok((variant, Some(drawn))) } } @@ -2384,6 +2397,7 @@ impl RenderExecution { draw_calls: 0, tile_dispatch_calls: 0, replaying: true, + executing_encoder: Some(self.encoder), rerouting: false, forms, replayed: None, @@ -2636,6 +2650,10 @@ pub(crate) struct DeferredPass { shadows: Vec>, /// What the commit made ahead for the host step that records it (`ahead.rs`), once made. ahead: OnceLock>, + /// The makings its executions' settle at commit handed to the device's pool + /// ([`settle`](Self::settle)), which its host step waits for, until its command buffer's bound + /// at most, as for its draws' pipelines. + settled: Mutex>>, /// Where `commit` recorded the pass with executions in their GPU form (`gpu.rs`), what each /// such execution's buffer's records may hold as the decision found it: a route encoded /// since that adds to it sends the pass to the host step ([`outgrown`](Self::outgrown)), @@ -2715,6 +2733,7 @@ impl DeferredPass { bare, shadows, ahead: OnceLock::new(), + settled: Mutex::new(Vec::new()), on_gpu: Mutex::new(Vec::new()), cause: Mutex::new(None), } @@ -2741,15 +2760,19 @@ impl DeferredPass { .any(|execution| execution.icb.gpu_written() || execution.range.indirect()) } - /// Whether a pipeline one of its draws or tile dispatches records is still being made. + /// Whether a pipeline one of its draws or tile dispatches records is still being made, or one + /// its executions' settle handed to the device's pool ([`settle`](Self::settle)). pub(crate) fn making(&self) -> bool { self.pending.iter().any(|draw| !draw.made()) || self.steps.tile_pipelines().any(TilePipelines::making) + || lock(&self.settled) + .iter() + .any(|pending| pending.outcome().is_none()) } - /// Whether the making of a pipeline one of its draws records failed: its recording fails - /// the command buffer, which a host step does (`render/pending.rs`); or one of its tile - /// dispatches', which its recording makes again (`render/pending_tile.rs`). + /// Whether the making of a pipeline one of its draws records failed: its recording, which a + /// host step does, drops the draw (`render/pending.rs`); or one of its tile dispatches', + /// which its recording makes again (`render/pending_tile.rs`). pub(crate) fn failed(&self) -> bool { self.pending.iter().any(PendingDraw::failed) || self.steps.tile_pipelines().any(TilePipelines::failed) @@ -2787,14 +2810,28 @@ impl DeferredPass { } /// Wait until every pipeline its draws and tile dispatches record is made, or failed, each - /// making hastened first (`pipeline/pool.rs`). - pub(crate) fn wait_made(&self) { + /// making hastened first (`pipeline/pool.rs`), until `deadline` at most, its command buffer's + /// bound, past which its recording drops the draw or tile dispatch (`render/pending.rs`, + /// `render/pending_tile.rs`). + pub(crate) fn wait_made(&self, deadline: Option) { self.hasten(Urgency::Committed); for draw in &self.pending { // Its outcome is the recording's to read. - drop(draw.pipeline.wait()); + match deadline { + Some(deadline) => drop(draw.pipeline.wait_until(deadline)), + None => drop(draw.pipeline.wait()), + } + } + for tile in self.steps.tile_pipelines() { + tile.wait(deadline); + } + let settled = lock(&self.settled).clone(); + for pending in &settled { + match deadline { + Some(deadline) => drop(pending.wait_until(deadline)), + None => drop(pending.wait()), + } } - self.steps.tile_pipelines().for_each(TilePipelines::wait); } /// Run the makings of the pipelines its draws and tile dispatches record before the @@ -2806,6 +2843,9 @@ impl DeferredPass { for tile in self.steps.tile_pipelines() { tile.hasten(urgency); } + for pending in lock(&self.settled).iter() { + pending.hasten(urgency); + } } /// Run `waker` each time the making of a pipeline its draws or tile dispatches record @@ -2818,6 +2858,10 @@ impl DeferredPass { for tile in self.steps.tile_pipelines() { tile.when_made(waker); } + for pending in lock(&self.settled).iter() { + let waker = waker.clone(); + pending.when_finished(Box::new(move |_| waker())); + } } /// Announce, once per device, an execution of a buffer from a command an earlier execution @@ -2896,7 +2940,7 @@ impl DeferredPass { } } drop(core); - self.wait_made(); + self.wait_made(command_buffer.making_deadline()); if self.making() || self.failed() { let rule = "a pipeline state the pass draws with is being made or failed to make"; return declined(HostStepCause::Rule(rule)); @@ -3300,10 +3344,14 @@ impl DeferredPass { /// draws of each state its records may name, the encoder's where its buffer inherits it, /// else those made with `supportIndirectCommandBuffers` alive now. Each such state's creation /// compiled its variant in the large-buffer form, which the commit looks up, and the commit - /// makes the `VkPipeline`s; it compiles a variant only where the encoder's state asks for - /// another, and the step only where a command's own buffers or strides ask for another, or - /// the draw records into a run of another shape. Returns what it made, which the command buffer - /// holds until it completes; what it cannot settle, the step meets as it is then. + /// begins the `VkPipeline`s: under `PipelineWaitPolicy::Bounded` (the default) each making is + /// handed to the device's pool (`RenderVariant::settle_graphics_pipeline`), kept here for the + /// host step to wait for until its command buffer's bound at most, so the commit compiles none + /// on the program's thread; under `Exact` made now. It compiles a variant only where the + /// encoder's state asks for another, and the step only where a command's own buffers or + /// strides ask for another, or the draw records into a run of another shape. Returns what it + /// made, which the command buffer holds until it completes; what it cannot settle, the step + /// meets as it is then. pub(crate) fn settle(&self, command_buffer: &CommandBuffer) -> Vec { let mut made = Vec::new(); let Ok(residency) = command_buffer.residency() else { @@ -3324,6 +3372,11 @@ impl DeferredPass { let inputs = (self.storage.clone(), &residency); core = execution.settle(core, inputs, &states, &mut made); } + // The makings handed to the pool, which the host step waits for. + lock(&self.settled).extend(made.iter().filter_map(|(_, drawn)| match drawn { + Some(DrawPipeline::Making(pending)) => Some(pending.clone()), + _ => None, + })); made } diff --git a/crates/metal2vulkan-runtime/src/render/pending.rs b/crates/metal2vulkan-runtime/src/render/pending.rs index e8bcf00cc..fb4ecbc72 100644 --- a/crates/metal2vulkan-runtime/src/render/pending.rs +++ b/crates/metal2vulkan-runtime/src/render/pending.rs @@ -20,28 +20,47 @@ //! they are made (`scheduler`), its batch held in its queue's order meanwhile, with no wait for //! the GPU. A pass that executes render commands the CPU writes records at commit, which waits //! for its pipelines: its commands are read as they stand then. -//! - **A failed making.** The command buffer completes with `CommandBufferError::PipelineCreation`, -//! its batch and those after it unrun; `CommandBuffer::failed_pipeline` names the draw (its -//! encoder's place and its order there), the state, its variant and specialization, and the -//! driver's error. Where creation ran at the draw, the draw returned that error. +//! - **A failed making.** The draw runs nothing and the command buffer runs on: its secondary +//! records the barriers and the query it would record around the draw, and no draw. +//! `CommandBuffer::dropped_draw` names the first such draw (its encoder's place and its order +//! there), the state, its variant and specialization, and the driver's error. Counted: +//! `WorkCounts::draws_dropped_unmade`. Where creation ran at the draw, the draw returned that +//! error. +//! - **A making past the bound.** Under `PipelineWaitPolicy::Bounded` (the default) a recording +//! waits for the draw's pipeline until its command buffer's commit plus the policy's +//! `pipeline_commit_wait` (4.5 s by default) at most (`CommandBuffer::making_deadline`; the +//! scheduler's host step runs then, `StepWaits::until`): a pipeline still being made then is not +//! waited for, and the draw records as nothing, as for a failed making, its making going on for +//! the command buffers after it. `CommandBuffer::dropped_draw` names the first such draw with the +//! error `VK_TIMEOUT`, which no driver's creation returns. Counted: +//! `WorkCounts::draws_dropped_still_making`; announced `draw-dropped-still-making`. Under +//! `PipelineWaitPolicy::Exact` the recording waits until the pipeline is made. +//! - **An execution's replay.** A draw of an execution's commands records as the replay runs +//! (the host step, or `commit` for records the CPU writes), so it takes no pending recording: +//! its pipeline, most begun on the device's pool by the execution's settle at commit +//! (`RenderExecution::settle`), is waited for until its command buffer's bound at most, and one +//! still being made then makes the draw record nothing, before anything of it is tracked, +//! named by its execution's encoder's place and its order among the replay's draws, counted and +//! announced as above ([`RenderLowering::drop_late_replayed_draw`]). A device replay's draw, +//! one recording for every command, waits until the pipeline is made. //! - **Recorded once.** A pass recorded at commit and again by a host step (an execution's //! buffer the GPU may write since) records each such draw once, its secondary executed by the //! recording that is submitted. use super::bound::{Bound, Recorded}; -use super::{DrawState, Recording}; +use super::{DrawState, Recording, RenderLowering}; use crate::binding::PushWrite; use crate::command_buffer::CommandBuffer; use crate::device::lock; use crate::draw_source::IndexBind; use crate::dynamic_state::ExtendedDynamicState; -use crate::error::{vulkan, Error, FailedPipeline, FailedState}; -use crate::pipeline::{Pending, RawPipeline, RenderPipelineState}; +use crate::error::{internal, vulkan, Error, FailedPipeline, FailedState}; +use crate::pipeline::{Pending, RawPipeline, RenderPipelineState, RenderVariant}; use crate::render_target; use crate::tracker::LegacyBarrier; use crate::visibility::Lent; use ash::vk; -use metal2vulkan::cache::VariantKey; +use metal2vulkan::cache::{SpecializationKey, VariantKey}; use metal2vulkan::pipeline::SpecKey; use std::sync::Mutex; @@ -115,8 +134,8 @@ impl PendingDraw { } /// Its secondary command buffer, recorded and ended once its pipeline is made, waiting for - /// that: recorded the first time, as `command_buffer`'s, which a failed making fails - /// (`CommandBuffer::fail_pipeline`). + /// that: recorded the first time, as `command_buffer`'s, without the draw where its making + /// failed (`CommandBuffer::drop_draw`). pub(super) fn record( &self, command_buffer: &CommandBuffer, @@ -133,18 +152,36 @@ impl PendingDraw { } fn record_once(&self, command_buffer: &CommandBuffer) -> Result<(), Error> { - let pipeline = match self.pipeline.wait() { - Ok(pipeline) => pipeline, - Err(error) => { - command_buffer.fail_pipeline(FailedPipeline { - encoder: self.encoder, - draw: self.draw, - state: FailedState::Render(self.state.clone()), - variant: self.variant.clone(), - specialization: self.specialization.clone(), - error: error.clone(), - }); - return Err(error); + // Until the command buffer's bound at most, where it has one (`PipelineWaitPolicy`). + let waited = match command_buffer.making_deadline() { + Some(deadline) => self.pipeline.wait_until(deadline), + None => Some(self.pipeline.wait()), + }; + // A device test's failure of the making (`CommandBuffer::fail_draw_making`). + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + let waited = match command_buffer.state().injected_making_failure() { + Some(error) => Some(Err(error)), + None => waited, + }; + let failed = |error| FailedPipeline { + encoder: self.encoder, + draw: self.draw, + state: FailedState::Render(self.state.clone()), + variant: self.variant.clone(), + specialization: self.specialization.clone(), + error, + }; + let pipeline = match waited { + Some(Ok(pipeline)) => Some(pipeline), + Some(Err(error)) => { + command_buffer.drop_draw(failed(error)); + None + } + // Still being made at the bound: the draw runs nothing, and a later command buffer + // draws with the pipeline once it is made. + None => { + command_buffer.drop_late_draw(failed(vulkan(vk::Result::TIMEOUT))); + None } }; let device = command_buffer.device(); @@ -157,7 +194,8 @@ impl PendingDraw { // until the command buffer completes (the encoder retained them at the draw, and the // pipeline is held with the pass); the barrier is the one the draw would record into its // instance, valid in the pass's subpass; the lent query is a continuation of the offset - // the encoder's draws count in, with none active in this secondary before it. + // the encoder's draws count in, with none active in this secondary before it. Without its + // pipeline it records them around no draw. unsafe { if let Some(view_mask) = self.storage_barrier { render_target::between_storage_draws(raw, cb, view_mask); @@ -173,33 +211,35 @@ impl PendingDraw { } let mut bound = Bound::default(); let mut recorded = Recorded::default(); - for owned in &self.recordings { - recorded += Recording { - raw, - command_buffer: cb, - layout: owned.layout, - shape: owned.shape, - pipeline: pipeline.raw, - sets: &owned.sets, - offsets: &owned.offsets, - pushed: &owned.pushed, - push_descriptor: shared.push_descriptor, - pushes_after_pipeline_binds: shared.pushes_after_pipeline_binds, - heap: owned.heap, - push: &owned.push, - vertex_buffers: &owned.vertex_buffers, - index: owned.index, - indirect: owned.indirect, - dynamic: &owned.dynamic, - topology: owned.topology, - primitive_restart: owned.primitive_restart, - state: &owned.state, - extended: owned.extended, - mesh: shared.mesh_draws.as_ref(), - draw: owned.draw, - pair: owned.pair.clone(), + if let Some(pipeline) = &pipeline { + for owned in &self.recordings { + recorded += Recording { + raw, + command_buffer: cb, + layout: owned.layout, + shape: owned.shape, + pipeline: pipeline.raw, + sets: &owned.sets, + offsets: &owned.offsets, + pushed: &owned.pushed, + push_descriptor: shared.push_descriptor, + pushes_after_pipeline_binds: shared.pushes_after_pipeline_binds, + heap: owned.heap, + push: &owned.push, + vertex_buffers: &owned.vertex_buffers, + index: owned.index, + indirect: owned.indirect, + dynamic: &owned.dynamic, + topology: owned.topology, + primitive_restart: owned.primitive_restart, + state: &owned.state, + extended: owned.extended, + mesh: shared.mesh_draws.as_ref(), + draw: owned.draw, + pair: owned.pair.clone(), + } + .record(&mut bound); } - .record(&mut bound); } recorded.count(&shared.counts); if let Some(query) = &self.query { @@ -210,3 +250,30 @@ impl PendingDraw { Ok(()) } } + +impl RenderLowering { + /// Drop a draw of an execution's replay whose `VkPipeline` of `variant` under + /// `specialization` was still being made at its command buffer's bound (the module docs): + /// named by its execution's encoder's place and its order among the replay's draws, its error + /// `VK_TIMEOUT`; counted and announced as any draw past the bound + /// (`CommandBuffer::drop_late_draw`). + pub(super) fn drop_late_replayed_draw( + &self, + variant: &RenderVariant, + specialization: &SpecializationKey, + ) -> Result<(), Error> { + let state = self + .pipeline + .clone() + .ok_or_else(|| internal("a draw without its pipeline state"))?; + self.core.command_buffer().drop_late_draw(FailedPipeline { + encoder: self.executing_encoder.unwrap_or_default(), + draw: self.draw_calls, + state: FailedState::Render(state), + variant: variant.key().clone(), + specialization: variant.constants(specialization), + error: vulkan(vk::Result::TIMEOUT), + }); + Ok(()) + } +} diff --git a/crates/metal2vulkan-runtime/src/render/pending_tile.rs b/crates/metal2vulkan-runtime/src/render/pending_tile.rs index 975ee4095..b5b06a7d6 100644 --- a/crates/metal2vulkan-runtime/src/render/pending_tile.rs +++ b/crates/metal2vulkan-runtime/src/render/pending_tile.rs @@ -22,6 +22,14 @@ //! `CommandBuffer::failed_pipeline` names the dispatch: its encoder's place, its order among the //! encoder's tile dispatch calls, the tile state, its variant and specialization, and the //! driver's error. +//! - **A making past its bound.** Under `PipelineWaitPolicy::Bounded` (the default) the pass's +//! recording waits for a making until its command buffer's bound at most, its commit plus the +//! policy's `pipeline_commit_wait` (4.5 s by default), as for a draw's (`render/pending.rs`): a +//! tile dispatch whose making is still in flight then records its copies into its scratch and +//! back and no dispatch, the command buffer running on without error. +//! `CommandBuffer::dropped_draw` names the first such command with the error `VK_TIMEOUT`; +//! counted, `WorkCounts::dispatches_dropped_still_making`; announced +//! `dispatch-dropped-still-making`. //! - **Encoded again** (`replay.rs`): an encoder encoded again waits for its tile dispatches' //! makings no more than its first encoding did, and leaves its pass to record later in the //! first encoding's place (`command_buffer/reencode.rs`), prepared as the commit prepared that @@ -32,15 +40,16 @@ use super::pass_steps::PassSteps; use crate::command_buffer::CommandBuffer; use crate::degradation::BoundFormats; -use crate::error::{Error, FailedPipeline, FailedState}; +use crate::error::{vulkan, Error, FailedPipeline, FailedState}; use crate::pipeline::budget::Urgency; use crate::pipeline::{ ComputePipelineState, Pending, RawPipeline, RegionKey, RegionPipeline, RenderPipelineState, Variant, }; +use ash::vk; use metal2vulkan::bind::DispatchRegion; use std::sync::{Arc, OnceLock}; -use std::time::Duration; +use std::time::{Duration, Instant}; /// A tile dispatch's regions' `VkPipeline`s, in its regions' order. pub(super) enum TilePipelines { @@ -149,11 +158,15 @@ impl TilePipelines { } } - /// Wait until every making finished, made or failed. - pub(super) fn wait(&self) { + /// Wait until every making finished, made or failed, until `deadline` at most, its command + /// buffer's bound where it has one (the module docs). + pub(super) fn wait(&self, deadline: Option) { for pending in self.makings() { // Its outcome is the recording's to read. - drop(pending.wait()); + match deadline { + Some(deadline) => drop(pending.wait_until(deadline)), + None => drop(pending.wait()), + } } } @@ -175,8 +188,11 @@ impl TilePipelines { Some(pending.created(made)) } - /// Its `VkPipeline`s, waiting for each making: one whose making failed made again here, on - /// this thread. Where that fails, `command_buffer` fails so (`CommandBuffer::fail_pipeline`). + /// Its `VkPipeline`s, waiting for each making until `command_buffer`'s bound at most, where + /// it has one: one whose making failed made again here, on this thread. Where that fails, + /// `command_buffer` fails so (`CommandBuffer::fail_pipeline`). Where a making is still in + /// flight at the bound, none: the dispatch is dropped (`CommandBuffer::drop_late_dispatch`), + /// its pass recording no dispatch for it (the module docs). pub(super) fn made( &self, command_buffer: &CommandBuffer, @@ -185,25 +201,38 @@ impl TilePipelines { TilePipelines::Made(made) => return Ok(made.clone()), TilePipelines::Making(pending) => pending, }; + let deadline = command_buffer.making_deadline(); + let failed = |key: &RegionKey, error| FailedPipeline { + encoder: pending.call.encoder, + draw: pending.call.dispatch, + state: FailedState::Render(pending.call.state.clone()), + variant: pending.variant.key().clone(), + specialization: pending.variant.constants(key), + error, + }; let mut made = Vec::with_capacity(pending.pipelines.len()); for (key, pipeline) in &pending.pipelines { let outcome = match pipeline { RegionPipeline::Made(made) => Ok(Arc::clone(made)), RegionPipeline::Making(making) => { - making.wait().or_else(|_| pending.variant.make_region(key)) + let waited = match deadline { + Some(deadline) => making.wait_until(deadline), + None => Some(making.wait()), + }; + let Some(waited) = waited else { + // Still being made at the bound: the dispatch runs nothing, and a later + // command buffer dispatches with the pipeline once it is made. + let late = failed(key, vulkan(vk::Result::TIMEOUT)); + command_buffer.drop_late_dispatch(late, true); + return Ok(Vec::new()); + }; + waited.or_else(|_| pending.variant.make_region(key)) } }; match outcome { Ok(pipeline) => made.push(pipeline), Err(error) => { - command_buffer.fail_pipeline(FailedPipeline { - encoder: pending.call.encoder, - draw: pending.call.dispatch, - state: FailedState::Render(pending.call.state.clone()), - variant: pending.variant.key().clone(), - specialization: pending.variant.constants(key), - error: error.clone(), - }); + command_buffer.fail_pipeline(failed(key, error.clone())); return Err(error); } } diff --git a/crates/metal2vulkan-runtime/src/scheduler/mod.rs b/crates/metal2vulkan-runtime/src/scheduler/mod.rs index c208c64fe..eb0928b12 100644 --- a/crates/metal2vulkan-runtime/src/scheduler/mod.rs +++ b/crates/metal2vulkan-runtime/src/scheduler/mod.rs @@ -478,6 +478,10 @@ pub(crate) struct State { pub(crate) group: Group, /// Those batches as the order held them, with their logical queues, in order. grouped: Vec<(u64, Held)>, + /// The earliest bound of a head whose host step waits for its draws' pipelines + /// ([`StepWaits::until`]), found by the last look ([`gate_heads`]): the thread sleeps no + /// later, so the step records those still being made as nothing then. + wake_by: Option, } impl State { @@ -571,6 +575,10 @@ pub(crate) struct StepWaits { pub(crate) queue_alone: Option, /// A pipeline it records, still being made. pub(crate) pipelines: bool, + /// Where it waits for pipelines and its command buffer's bound has not passed: the bound, + /// after which its draws' pipelines still being made are waited for no longer + /// (`CommandBuffer::making_deadline`). + pub(crate) until: Option, } /// What one committed batch waits for and signals, as the scheduler orders it. @@ -610,6 +618,7 @@ impl Scheduler { decodes: BTreeMap::new(), untracked_decodes: 0, kept: KeptBarriers::default(), + wake_by: None, lists: BatchLists::default(), group: Group::default(), grouped: Vec::new(), @@ -939,6 +948,19 @@ fn run(shared: &SchedulerShared) { && !shared.inbox.holds_commits() && !shared.inbox.nudged() { + // A head whose step waits for its draws' pipelines waits until its bound at most + // (`StepWaits::until`): a pass looks at it again then. + let bound = match state.wake_by { + None => None, + Some(at) => match at.checked_duration_since(Instant::now()) { + Some(left) if !left.is_zero() => Some(left), + _ => { + state.wake_by = None; + state.dirty = true; + continue; + } + }, + }; // A stall due is taken without the lock, the empty submissions stopping where a // commit or a waker came; the sleep before it ends at the idle's length, no slice. let stalls = (shared.stalls.get()).filter(|stalls| !looked && stalls.may_be_due()); @@ -962,6 +984,7 @@ fn run(shared: &SchedulerShared) { } None => (WAIT_SLICE, false), }; + let slice = bound.map_or(slice, |left| left.min(slice)); shared.sleeps.fetch_add(1, Ordering::Relaxed); if let Some(nudge) = shared.nudge.get().filter(|_| shared.gpu_waits(&mut gpu)) { state = wait_for_gpu(shared, state, nudge, &mut gpu, (slice, short)); @@ -999,10 +1022,10 @@ fn run(shared: &SchedulerShared) { } /// Sleep on the GPU (the module docs): for any of `gpu`'s semaphores to reach its value, or the -/// nudge its next, at most `slice` ([`WAIT_SLICE`], or, where `short`, the idle's length before -/// a driver's stall is taken, whose end is no slice's), without the lock `state` holds, which -/// comes back taken. Where a value landed, its events observe their counters, and the state is -/// marked for a pass. +/// nudge its next, at most `slice` ([`WAIT_SLICE`], or less to a head's bound, or, where `short`, +/// the idle's length before a driver's stall is taken, whose end is no slice's), without the lock +/// `state` holds, which comes back taken. Where a value landed, its events observe their counters, +/// and the state is marked for a pass. fn wait_for_gpu<'a>( shared: &'a SchedulerShared, mut state: std::sync::MutexGuard<'a, State>, @@ -1850,8 +1873,10 @@ fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left, awaits: order, values, binary, + wake_by, .. } = state; + *wake_by = None; let mut waiting = false; for held in order.heads_mut(behind) { if !held.segments @@ -1868,6 +1893,10 @@ fn gate_heads(state: &mut State, behind: &[u64], left: &mut Left, awaits: // they finish; one for them alone waits for no work on the GPU. let waits = held.buffer.step_waits(held.index); if waits.pipelines { + // Its bound wakes the thread where its makings do not finish first. + if let Some(at) = waits.until { + *wake_by = Some(wake_by.map_or(at, |by| by.min(at))); + } continue; } if !waits.gpu { diff --git a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs index 6c905701a..c684b8d63 100644 --- a/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs +++ b/crates/metal2vulkan-runtime/src/tests/deferred_calls.rs @@ -20,6 +20,7 @@ use super::blit_holds::{busy, over_host, until, Host, Scratch, FILLED, WAIT}; use super::encoder_holds::{bits, bytes_of, pass, render_state, words_of}; use crate::error::{invalid, vulkan}; +use crate::pipeline::pool::held; use crate::render::{BATCH_CALLS, HANDED_BATCHES}; use crate::StoreAction; use crate::{ @@ -29,12 +30,12 @@ use crate::{ ShaderCacheOptions, Size, Texture, TextureDescriptor, VertexAmplificationViewMapping, Viewport, }; use ash::vk; -use metal2vulkan::device::RenderLoweringPolicy; +use metal2vulkan::device::{PipelineWaitPolicy, RenderLoweringPolicy}; use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureUsage}; use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{mpsc, Arc, Mutex}; -use std::time::Duration; +use std::time::{Duration, Instant}; /// The side of the target, and the color the draws draw: `(0.2, 0.4, 0.6, 1)`, whose /// `RGBA8Unorm` bytes are exact. @@ -58,6 +59,33 @@ fn device( refuses: &[Degradation], heard: &Heard, ) -> Device { + device_with(cache, heard, |options| { + options.lowering_refuses = refuses.iter().copied().collect(); + options.policy.render_lowering = lowering; + }) +} + +/// A device of the kind the cfg selects that waits for a draw's pipeline still being made as +/// `waits` says, under `Bounded` [`CREATION_WAIT`] at a state's creation and [`COMMIT_WAIT`] from +/// a command buffer's commit, its notices into `heard`. +fn waiting_device(cache: &Path, waits: PipelineWaitPolicy, heard: &Heard) -> Device { + device_with(cache, heard, |options| { + options.policy.pipeline_waits = waits; + options.policy.pipeline_creation_wait = CREATION_WAIT; + options.policy.pipeline_commit_wait = COMMIT_WAIT; + }) +} + +/// The bounds [`waiting_device`] sets for a state's creation and from a command buffer's commit, +/// apart from the defaults and far enough apart that a test tells which one a wait took: a +/// creation that waits its own bound returns before [`COMMIT_WAIT`], and a command buffer that +/// waits its own completes after it. +const CREATION_WAIT: Duration = Duration::from_millis(250); +const COMMIT_WAIT: Duration = Duration::from_secs(3); + +/// A device of the kind the cfg selects, its shader cache in `cache` and its notices into +/// `heard`, of the options `adjust` sets. +fn device_with(cache: &Path, heard: &Heard, adjust: impl FnOnce(&mut DeviceOptions)) -> Device { let heard = Arc::clone(heard); let mut options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { @@ -77,10 +105,9 @@ fn device( heard.lock().unwrap().push(notice.clone()); } })), - lowering_refuses: refuses.iter().copied().collect(), ..DeviceOptions::default() }; - options.policy.render_lowering = lowering; + adjust(&mut options); Device::system_default_with(&options).unwrap() } @@ -1096,3 +1123,472 @@ fn a_commit_whose_own_work_fails_completes_with_the_refusal() { assert_eq!(commits, 2, "{counts:?}"); } } +/// A draw whose pipeline the driver did not make after the draw returned (a line over the +/// rectangle state, whose making waits in the held pool, its failure injected as the driver's +/// out of device memory) runs nothing, under both policies: its command buffer completes without +/// error, the pass clears its target and the blit after it copies it, `dropped_draw` names the +/// draw (encoder 0, draw 0, the driver's error) and `failed_pipeline` nothing. Counted: +/// `WorkCounts::draws_dropped_unmade`, and announced `draw-dropped-unmade`, naming the driver's +/// error. +#[test] +fn a_draw_whose_pipeline_was_not_made_runs_nothing_and_its_command_buffer_runs_on() { + let scratch = Scratch::new("deferred-dropped-draw"); + let failure = vulkan(vk::Result::ERROR_OUT_OF_DEVICE_MEMORY); + for policy in POLICIES { + let heard = Heard::default(); + let device = device(&scratch.0, policy, &[], &heard); + let state = rectangle_state(&device); + let queue = device.new_command_queue().unwrap(); + let target = target(&device); + let counts = device.work_counts(); + let hold = crate::pipeline::pool::held::hold(); + let command_buffer = queue.command_buffer().unwrap(); + command_buffer.fail_draw_making(failure.clone()); + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + rectangle(&state, &mut encoder); + let red = bytes_of(&[1.0f32, 0.0, 0.0, 1.0], f32::to_le_bytes); + encoder.set_fragment_bytes(&red, 0).unwrap(); + encoder + .draw_primitives(PrimitiveType::Line, 0, 6, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + let back = copy_back(&device, &command_buffer, &target); + command_buffer.commit().unwrap(); + drop(hold); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None, "{policy:?}"); + assert!(command_buffer.failed_pipeline().is_none(), "{policy:?}"); + let dropped = command_buffer + .dropped_draw() + .expect("the draw dropped is named"); + assert_eq!((dropped.encoder, dropped.draw), (0, 0), "{policy:?}"); + assert_eq!(dropped.error, failure, "{policy:?}"); + assert!(words_of(&back).iter().all(|&w| w == 0), "{policy:?}"); + let after = device.work_counts(); + assert!( + after.pipelines_pooled > counts.pipelines_pooled, + "the making waited" + ); + assert_eq!(after.draws_dropped_unmade - counts.draws_dropped_unmade, 1); + let unmade: Vec<_> = (heard.lock().unwrap().iter()) + .filter(|notice| notice.degradation == Degradation::DrawDroppedUnmade) + .cloned() + .collect(); + assert_eq!(unmade.len(), 1, "{policy:?}: {unmade:?}"); + assert!( + unmade[0].reason.contains(&failure.to_string()), + "{policy:?}: the notice names the driver's error: {unmade:?}" + ); + } +} + +/// The 10 s a guest's FIFO check gives one of its command buffers' executions, past which it ends +/// the guest's task: no wait for a pipeline's making may hold a command buffer that long. +const GUEST_WATCHDOG: Duration = Duration::from_secs(10); + +/// A render pass of `state`'s rectangle in [`COLOR`] into `target`, and a copy of `target` after +/// it, encoded into `command_buffer`, drawn as `primitive`: the buffer the copy fills. +fn rectangle_pass( + device: &Device, + command_buffer: &CommandBuffer, + (state, target): (&RenderPipelineState, &Texture), + primitive: PrimitiveType, +) -> Buffer { + let mut encoder = command_buffer + .render_command_encoder(&pass(target)) + .unwrap(); + rectangle(state, &mut encoder); + let color = bytes_of(&COLOR, f32::to_le_bytes); + encoder.set_fragment_bytes(&color, 0).unwrap(); + encoder.draw_primitives(primitive, 0, 6, 1, 0).unwrap(); + encoder.end_encoding().unwrap(); + copy_back(device, command_buffer, target) +} + +/// A draw whose pipeline is still being made at its command buffer's bound runs nothing, under +/// `PipelineWaitPolicy::Bounded` (the default), the slow compile the pool's test hold +/// (`pool::held`), which keeps every making waiting, no sleep: the state's creation hands its +/// predicted key's making to the held pool and returns at its own bound, the policy's creation +/// wait as set ([`CREATION_WAIT`], before the commit wait), the making still waiting +/// (`WorkCounts::creations_left_making`), never past the 10 s a guest's FIFO check allows. The +/// rectangle's draw takes that making, and its command buffer, committed with the pool still held, +/// completes without error once its own bound passed, the policy's commit wait as set +/// ([`COMMIT_WAIT`]), within those 10 s: the pass clears its +/// target and the blit after it copies it, `dropped_draw` names the draw (encoder 0, draw 0, +/// `VK_TIMEOUT`), `failed_pipeline` nothing, counted `draws_dropped_still_making` (not +/// `draws_dropped_unmade`) and announced `draw-dropped-still-making`. Once the hold goes the making +/// lands, and a later command buffer draws the rectangle. +#[test] +fn a_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing() { + let scratch = Scratch::new("deferred-making-bound"); + let heard = Heard::default(); + let device = waiting_device(&scratch.0, PipelineWaitPolicy::Bounded, &heard); + let queue = device.new_command_queue().unwrap(); + let target = target(&device); + let counts = device.work_counts(); + let hold = held::hold(); + let creating = Instant::now(); + let state = rectangle_state(&device); + let created = creating.elapsed(); + let made = device.work_counts(); + assert_eq!( + made.creations_left_making - counts.creations_left_making, + 1, + "the creation returned with its predicted making held" + ); + assert_eq!(made.creation_pipelines_made, counts.creation_pipelines_made); + assert!( + (CREATION_WAIT..COMMIT_WAIT).contains(&created), + "the creation took {created:?}, not its own bound" + ); + let command_buffer = queue.command_buffer().unwrap(); + let back = rectangle_pass( + &device, + &command_buffer, + (&state, &target), + PrimitiveType::Triangle, + ); + let committing = Instant::now(); + command_buffer.commit().unwrap(); + command_buffer + .wait_until_completed_for(GUEST_WATCHDOG) + .expect("the command buffer completes at its bound with its draw's making held"); + let waited = committing.elapsed(); + assert!( + (COMMIT_WAIT..GUEST_WATCHDOG).contains(&waited), + "completed after {waited:?}, not its own bound" + ); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + assert!(command_buffer.failed_pipeline().is_none()); + let dropped = command_buffer + .dropped_draw() + .expect("the draw dropped is named"); + assert_eq!((dropped.encoder, dropped.draw), (0, 0)); + assert_eq!(dropped.error, vulkan(vk::Result::TIMEOUT)); + assert!(words_of(&back).iter().all(|&w| w == 0), "the draw drew"); + let after = device.work_counts(); + assert_eq!( + after.draws_dropped_still_making - counts.draws_dropped_still_making, + 1 + ); + assert_eq!(after.draws_dropped_unmade, counts.draws_dropped_unmade); + assert!( + (heard.lock().unwrap().iter()) + .any(|notice| notice.degradation == Degradation::DrawDroppedStillMaking), + "no notice of the dropped draw" + ); + drop(hold); + // The making lands for the command buffers after it. + let deadline = Instant::now() + WAIT; + loop { + let command_buffer = queue.command_buffer().unwrap(); + let back = rectangle_pass( + &device, + &command_buffer, + (&state, &target), + PrimitiveType::Triangle, + ); + let words = committed(&command_buffer, &back); + if command_buffer.dropped_draw().is_none() { + assert!(words.iter().all(|&w| w == PACKED), "the rectangle, drawn"); + break; + } + assert!(Instant::now() < deadline, "the making never landed"); + } +} + +/// A draw of an execution's replay whose pipeline is still being made at its command buffer's +/// bound runs nothing, under `PipelineWaitPolicy::Bounded` (the default), the slow compile the +/// pool's test hold (`pool::held`), no sleep. The commit replays the records the CPU wrote as it +/// reads them, so the draw takes no pending recording: it waits for its making, held in the pool, +/// until the bound, then records nothing. The commit returns once the bound passed, within the +/// 10 s a guest's FIFO check allows, and the command buffer completes without error, its pass +/// clearing its target and the blit after it copying it: `dropped_draw` names the draw (its +/// execution's encoder 0, draw 0, `VK_TIMEOUT`), `failed_pipeline` nothing, counted +/// `draws_dropped_still_making` and announced `draw-dropped-still-making`. Once the hold goes the +/// making lands, and a later command buffer draws the rectangle. +#[test] +fn a_replayed_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing() { + use super::encoder_holds::library; + use crate::{IndirectCommandBufferDescriptor, PipelineOptions}; + use metal2vulkan::metal::{IndirectCommandType, RenderStages, ResourceUsage}; + use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource, + }; + let scratch = Scratch::new("deferred-replay-bound"); + let heard = Heard::default(); + let device = waiting_device(&scratch.0, PipelineWaitPolicy::Bounded, &heard); + let queue = device.new_command_queue().unwrap(); + let target = target(&device); + let library = library(&device, "engine/tob_renders.ll"); + let vertex = library.new_function_with_name("tob_rect").unwrap(); + let fragment = library.new_function_with_name("tob_solid").unwrap(); + let mut descriptor = + RenderPipelineDescriptor::new(StageSource::Function(vertex.function_descriptor())); + descriptor.fragment = Some(StageSource::Function(fragment.function_descriptor())); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(PixelFormat::RGBA8Unorm)); + descriptor.support_indirect_command_buffers = true; + let shared = ResourceOptions::shared(); + let corners = bytes_of(&[-1.0f32, -1.0, 1.0, 1.0], f32::to_le_bytes); + let corners = device.new_buffer_with_bytes(&corners, shared).unwrap(); + let color = bytes_of(&COLOR, f32::to_le_bytes); + let color = device.new_buffer_with_bytes(&color, shared).unwrap(); + let counts = device.work_counts(); + let hold = held::hold(); + let state = device + .new_render_pipeline_state(&descriptor, &PipelineOptions::default()) + .unwrap(); + let mut commands = IndirectCommandBufferDescriptor::new(); + commands.command_types = IndirectCommandType::DRAW; + commands.max_vertex_buffer_bind_count = 1; + commands.max_fragment_buffer_bind_count = 1; + let icb = device + .new_indirect_command_buffer(&commands, 1, shared) + .unwrap(); + let command = icb.indirect_render_command_at(0).unwrap(); + command.set_render_pipeline_state(&state).unwrap(); + command.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + command.set_fragment_buffer(Some(&color), 0, 0).unwrap(); + command + .draw_primitives(PrimitiveType::Triangle, 0, 6, 1, 0) + .unwrap(); + let replayed = |command_buffer: &CommandBuffer| { + let mut encoder = command_buffer + .render_command_encoder(&pass(&target)) + .unwrap(); + let (read, vertex, fragment) = ( + ResourceUsage::READ, + RenderStages::VERTEX, + RenderStages::FRAGMENT, + ); + encoder + .use_resource(corners.as_resource(), read, vertex) + .unwrap(); + encoder + .use_resource(color.as_resource(), read, fragment) + .unwrap(); + encoder.execute_commands_in_buffer(&icb, 0..1).unwrap(); + encoder.end_encoding().unwrap(); + copy_back(&device, command_buffer, &target) + }; + let command_buffer = queue.command_buffer().unwrap(); + let back = replayed(&command_buffer); + let committing = Instant::now(); + command_buffer.commit().unwrap(); + command_buffer + .wait_until_completed_for(GUEST_WATCHDOG) + .expect("the command buffer completes at its bound with its draw's making held"); + let waited = committing.elapsed(); + assert!( + (COMMIT_WAIT..GUEST_WATCHDOG).contains(&waited), + "completed after {waited:?}, not its own bound" + ); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + assert!(command_buffer.failed_pipeline().is_none()); + let dropped = command_buffer + .dropped_draw() + .expect("the replayed draw dropped is named"); + assert_eq!((dropped.encoder, dropped.draw), (0, 0)); + assert_eq!(dropped.error, vulkan(vk::Result::TIMEOUT)); + assert!(words_of(&back).iter().all(|&w| w == 0), "the draw drew"); + let after = device.work_counts(); + assert_eq!( + after.draws_dropped_still_making - counts.draws_dropped_still_making, + 1 + ); + assert!( + (heard.lock().unwrap().iter()) + .any(|notice| notice.degradation == Degradation::DrawDroppedStillMaking), + "no notice of the dropped draw" + ); + drop(hold); + // The making lands for the command buffers after it. + let deadline = Instant::now() + WAIT; + loop { + let command_buffer = queue.command_buffer().unwrap(); + let back = replayed(&command_buffer); + let words = committed(&command_buffer, &back); + if command_buffer.dropped_draw().is_none() { + assert!(words.iter().all(|&w| w == PACKED), "the rectangle, drawn"); + break; + } + assert!(Instant::now() < deadline, "the making never landed"); + } +} + +/// A compute dispatch whose pipeline is still being made at its command buffer's bound runs +/// nothing, under `PipelineWaitPolicy::Bounded` (the default), the slow compile the pool's test +/// hold (`pool::held`), no sleep. The state requires no threadgroup size, so its creation predicts +/// nothing; the dispatch hands its region's making to the held pool, and its command buffer, +/// committed with the pool still held, completes without error once its bound passed, within the +/// 10 s a guest's FIFO check allows, its output unwritten: `dropped_draw` names the dispatch +/// (encoder 0, dispatch 0, `VK_TIMEOUT`), `failed_pipeline` nothing, counted +/// `dispatches_dropped_still_making` and announced `dispatch-dropped-still-making`. Once the hold +/// goes the making lands, and a later command buffer writes what Metal's writes. +#[test] +fn a_dispatch_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing() { + use super::dispatch_pending::{dispatch, state, Buffers, Grid}; + let scratch = Scratch::new("deferred-dispatch-bound"); + let heard = Heard::default(); + let device = waiting_device(&scratch.0, PipelineWaitPolicy::Bounded, &heard); + let queue = device.new_command_queue().unwrap(); + let state = state(&device); + let buffers = Buffers::new(&device); + let one = || Grid::One(Size::new(64, 1, 1)); + let counts = device.work_counts(); + let hold = held::hold(); + let command_buffer = dispatch(&queue, &state, &buffers, one()); + let committing = Instant::now(); + command_buffer.commit().unwrap(); + command_buffer + .wait_until_completed_for(GUEST_WATCHDOG) + .expect("the command buffer completes at its bound with its dispatch's making held"); + let waited = committing.elapsed(); + assert!( + (COMMIT_WAIT..GUEST_WATCHDOG).contains(&waited), + "completed after {waited:?}, not its own bound" + ); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + assert!(command_buffer.failed_pipeline().is_none()); + let dropped = command_buffer + .dropped_draw() + .expect("the dispatch dropped is named"); + assert_eq!((dropped.encoder, dropped.draw), (0, 0)); + assert_eq!(dropped.error, vulkan(vk::Result::TIMEOUT)); + assert!(!buffers.written(2), "the dispatch wrote"); + let after = device.work_counts(); + assert_eq!( + after.dispatches_dropped_still_making - counts.dispatches_dropped_still_making, + 1 + ); + assert_eq!( + after.draws_dropped_still_making, + counts.draws_dropped_still_making + ); + assert!( + (heard.lock().unwrap().iter()) + .any(|notice| notice.degradation == Degradation::DispatchDroppedStillMaking), + "no notice of the dropped dispatch" + ); + drop(hold); + // The making lands for the command buffers after it. + let deadline = Instant::now() + WAIT; + loop { + let command_buffer = dispatch(&queue, &state, &buffers, one()); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + if command_buffer.dropped_draw().is_none() { + assert!( + buffers.written(64), + "the dispatch wrote what Metal's writes" + ); + break; + } + assert!(Instant::now() < deadline, "the making never landed"); + } +} + +/// A compute state whose descriptor requires a threadgroup size predicts its first dispatch's +/// region at its creation (`pipeline/dispatch_making.rs`). Under `PipelineWaitPolicy::Bounded` +/// (the default) the creation hands that making to the device's pool and, the pool held +/// (`pool::held`), returns at its bound with the making still waiting +/// (`WorkCounts::creations_left_making`), never past the 10 s a guest's FIFO check allows; under +/// `Exact` it makes the region on its own thread before it returns, the pool held or not. +#[test] +fn a_compute_state_s_creation_waits_its_bound_for_its_predicted_making() { + use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; + for waits in [PipelineWaitPolicy::Bounded, PipelineWaitPolicy::Exact] { + let scratch = Scratch::new("deferred-compute-creation-bound"); + let heard = Heard::default(); + let device = waiting_device(&scratch.0, waits, &heard); + let ll = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../metal2vulkan-validation/fixtures/public/examples/runtime_examples.ll"); + let bitcode = metal2vulkan_devtools::llvm_assemble(&ll).unwrap(); + let function = device + .new_library_with_compile_library( + metal2vulkan::library::Library::from_air(&bitcode).unwrap(), + ) + .new_function_with_name("scale_and_offset") + .unwrap(); + let mut descriptor = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + descriptor.required_threads_per_threadgroup = Some([32, 1, 1]); + let counts = device.work_counts(); + let hold = held::hold(); + let creating = Instant::now(); + let _state = device + .new_compute_pipeline_state(&descriptor, &crate::PipelineOptions::default()) + .unwrap(); + let created = creating.elapsed(); + let after = device.work_counts(); + drop(hold); + let left = after.creations_left_making - counts.creations_left_making; + let made = after.creation_dispatch_pipelines_made - counts.creation_dispatch_pipelines_made; + match waits { + PipelineWaitPolicy::Bounded => { + assert_eq!((left, made), (1, 0), "the creation's making, held"); + assert!( + (CREATION_WAIT..COMMIT_WAIT).contains(&created), + "the creation took {created:?}, not its own bound" + ); + } + _ => assert_eq!((left, made), (0, 1), "the creation's making, made"), + } + } +} + +/// Under `PipelineWaitPolicy::Exact` a held making is waited for until it is made: the state's +/// creation makes its predicted key before it returns, the pool held or not (none left making); a +/// line over it, whose key only its draw makes, waits in the held pool, and its command buffer, +/// committed, is not complete a second past the bounded form's commit wait; once the hold goes, the making lands and the +/// command buffer completes with the line drawn, no draw dropped. +#[test] +fn under_the_exact_wait_a_held_making_holds_its_command_buffer_until_it_lands() { + let scratch = Scratch::new("deferred-making-exact"); + let heard = Heard::default(); + let device = waiting_device(&scratch.0, PipelineWaitPolicy::Exact, &heard); + let queue = device.new_command_queue().unwrap(); + let target = target(&device); + let counts = device.work_counts(); + let hold = held::hold(); + let state = rectangle_state(&device); + let made = device.work_counts(); + assert_eq!(made.creations_left_making, counts.creations_left_making); + let command_buffer = queue.command_buffer().unwrap(); + let back = rectangle_pass( + &device, + &command_buffer, + (&state, &target), + PrimitiveType::Line, + ); + assert!( + device.work_counts().pipelines_pooled > made.pipelines_pooled, + "the line's making waits in the pool" + ); + command_buffer.commit().unwrap(); + assert!( + command_buffer + .wait_until_completed_for(COMMIT_WAIT + Duration::from_secs(1)) + .is_err(), + "completed while its draw's making was held" + ); + drop(hold); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + assert_eq!(command_buffer.error(), None); + assert!(command_buffer.dropped_draw().is_none()); + assert!(words_of(&back).contains(&PACKED), "the line, drawn"); + let after = device.work_counts(); + assert_eq!( + after.draws_dropped_still_making, + counts.draws_dropped_still_making + ); + assert!(!(heard.lock().unwrap().iter()) + .any(|notice| notice.degradation == Degradation::DrawDroppedStillMaking)); +} diff --git a/crates/metal2vulkan-runtime/src/tests/dispatch_pending.rs b/crates/metal2vulkan-runtime/src/tests/dispatch_pending.rs index 7cfc5b324..8fe87cbd2 100644 --- a/crates/metal2vulkan-runtime/src/tests/dispatch_pending.rs +++ b/crates/metal2vulkan-runtime/src/tests/dispatch_pending.rs @@ -113,7 +113,7 @@ impl Buffers { } /// Whether the output's first `n` words are `input[i] * SCALE + i`. - fn written(&self, n: u64) -> bool { + pub(super) fn written(&self, n: u64) -> bool { let contents = self.output.contents().unwrap(); // SAFETY: the buffer's `COUNT * 4` bytes, which no command buffer writes now. let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), (COUNT * 4) as usize) }; diff --git a/crates/metal2vulkan-runtime/src/tests/inline_continues.rs b/crates/metal2vulkan-runtime/src/tests/inline_continues.rs index d88344e01..14d72581a 100644 --- a/crates/metal2vulkan-runtime/src/tests/inline_continues.rs +++ b/crates/metal2vulkan-runtime/src/tests/inline_continues.rs @@ -22,6 +22,7 @@ use crate::{ RenderPassDescriptor, RenderPipelineState, ResourceOptions, ShaderCacheOptions, Size, StoreAction, TextureDescriptor, }; +use metal2vulkan::device::PipelineWaitPolicy; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use std::path::{Path, PathBuf}; @@ -58,7 +59,7 @@ impl Drop for Scratch { /// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache /// in `cache`. fn device(cache: &Path) -> Device { - let options = DeviceOptions { + let mut options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { true => vec![DeviceKind::Cpu], false => vec![ @@ -73,6 +74,10 @@ fn device(cache: &Path) -> Device { }, ..DeviceOptions::default() }; + // The held making is waited for until it is made, whatever the hold's length: under + // `PipelineWaitPolicy::Bounded` a draw whose making is held past its command buffer's bound + // runs nothing (`tests/deferred_calls.rs` takes that form). + options.policy.pipeline_waits = PipelineWaitPolicy::Exact; Device::system_default_with(&options).unwrap() } diff --git a/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs b/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs index 22c2855d5..25d361230 100644 --- a/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs +++ b/crates/metal2vulkan-runtime/src/tests/pipeline_wait_order.rs @@ -21,6 +21,7 @@ use crate::{ RenderPassDescriptor, RenderPipelineState, ResourceOptions, ShaderCacheOptions, Size, StoreAction, Texture, TextureDescriptor, }; +use metal2vulkan::device::PipelineWaitPolicy; use metal2vulkan::metal::{PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use std::alloc::Layout; @@ -67,7 +68,7 @@ impl Drop for Scratch { /// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache /// in `cache`. fn device(cache: &Path) -> Device { - let options = DeviceOptions { + let mut options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { true => vec![DeviceKind::Cpu], false => vec![ @@ -82,6 +83,10 @@ fn device(cache: &Path) -> Device { }, ..DeviceOptions::default() }; + // The held making is waited for until it is made, whatever the hold's length: under + // `PipelineWaitPolicy::Bounded` a draw whose making is held past its command buffer's bound + // runs nothing (`tests/deferred_calls.rs` takes that form). + options.policy.pipeline_waits = PipelineWaitPolicy::Exact; Device::system_default_with(&options).unwrap() } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index a0db24d30..13f305c71 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -83,8 +83,12 @@ pub(crate) struct Counters { predicated_loop_runs_again: AtomicU64, variants_taken_back: AtomicU64, unlisted_argument_sampler_buffers: AtomicU64, + draws_dropped_unmade: AtomicU64, + draws_dropped_still_making: AtomicU64, + dispatches_dropped_still_making: AtomicU64, host_step_sampler_sets_made: AtomicU64, creation_pipelines_made: AtomicU64, + creations_left_making: AtomicU64, creation_pipelines_drawn: AtomicU64, creation_render_pipelines_made: AtomicU64, creation_render_pipelines_drawn: AtomicU64, @@ -1020,6 +1024,26 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// A draw whose pipeline the driver did not make after the draw returned ran nothing + /// (`CommandBuffer::drop_draw`). + pub(crate) fn draw_dropped_unmade(&self) { + self.draws_dropped_unmade.fetch_add(1, Ordering::Relaxed); + } + + /// A draw whose pipeline was still being made at its command buffer's bound ran nothing + /// (`CommandBuffer::drop_late_draw`). + pub(crate) fn draw_dropped_still_making(&self) { + self.draws_dropped_still_making + .fetch_add(1, Ordering::Relaxed); + } + + /// A dispatch, or a render pass's tile dispatch, whose pipeline was still being made at its + /// command buffer's bound ran nothing (`CommandBuffer::drop_late_dispatch`). + pub(crate) fn dispatch_dropped_still_making(&self) { + self.dispatches_dropped_still_making + .fetch_add(1, Ordering::Relaxed); + } + /// `count` records of an indirect command buffer's commands were read from its storage and /// decoded (`indirect_command_buffer.rs`). pub(crate) fn indirect_records_read(&self, count: u64) { @@ -1077,6 +1101,13 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// A state's creation returned while its predicted key's making, handed to the device's pool, + /// was still running at the bound (`PipelineWaitPolicy::Bounded`, `pipeline/render.rs`, + /// `pipeline/dispatch_making.rs`). + pub(crate) fn creation_left_making(&self) { + self.creations_left_making.fetch_add(1, Ordering::Relaxed); + } + /// A draw or dispatch took a `VkPipeline` a state's creation made for `predicted`, its first /// use: counted in both the whole count and its prediction's. pub(crate) fn creation_pipeline_drawn(&self, predicted: Predicted) { @@ -3068,6 +3099,23 @@ pub struct WorkCounts { /// (`Degradation::UnlistedArgumentSampler`), and is counted once whether or not its /// functions reach the state left out. pub unlisted_argument_sampler_buffers: u64, + /// Draws whose `VkPipeline` the driver did not make after the draw returned (the runtime makes + /// a draw's pipeline while the draw goes on): each ran nothing, its command buffer running on + /// without error (`CommandBuffer::dropped_draw` names the first of a command buffer). + pub draws_dropped_unmade: u64, + /// Draws whose `VkPipeline` was still being made once their command buffer's bound passed + /// (`PipelineWaitPolicy::Bounded`, the default: its commit plus the policy's + /// `pipeline_commit_wait`): each ran nothing, its command buffer running on without error, and the command buffers after it draw with + /// the pipeline once it is made (`CommandBuffer::dropped_draw` names the first of a command + /// buffer, with the error `VK_TIMEOUT`). + pub draws_dropped_still_making: u64, + /// Compute dispatches and render passes' tile dispatches whose `VkPipeline` was still being + /// made once their command buffer's bound passed (`PipelineWaitPolicy::Bounded`, the default: + /// its commit plus the policy's `pipeline_commit_wait`): each ran nothing, so wrote nothing, its command buffer running on + /// without error, and the command buffers after it dispatch with the pipeline once it is made + /// (`CommandBuffer::dropped_draw` names the first of a command buffer, with the error + /// `VK_TIMEOUT`). + pub dispatches_dropped_still_making: u64, /// Immutable sampler sets a command buffer's host step made, counting samplers on the /// scheduler's thread, because the device's map held no set of its variant's samplers: the /// open break (a render execution's step drawing a state made after its commit, on the variant @@ -3093,6 +3141,13 @@ pub struct WorkCounts { /// Of [`creation_dispatch_pipelines_made`](Self::creation_dispatch_pipelines_made), the ones a /// dispatch took so far. pub creation_dispatch_pipelines_drawn: u64, + /// Render and compute states' creations that returned while the making of their predicted + /// key's `VkPipeline`, which they handed to the device's pool, was still running the policy's + /// `pipeline_creation_wait` after they handed it there (`PipelineWaitPolicy::Bounded`, the + /// default): their draws and dispatches take the making in flight, their command buffer + /// waiting its own bound for it in turn. Each is counted in + /// [`creation_pipelines_made`](Self::creation_pipelines_made) too once made. + pub creations_left_making: u64, /// Immutable sampler sets variants made (the device's map's, and a host step's or a pool /// piece's own): none for a variant without immutable samplers. pub sampler_sets_made: u64, @@ -4879,10 +4934,16 @@ impl Device { unlisted_argument_sampler_buffers: counters .unlisted_argument_sampler_buffers .load(Ordering::Relaxed), + draws_dropped_unmade: counters.draws_dropped_unmade.load(Ordering::Relaxed), + draws_dropped_still_making: counters.draws_dropped_still_making.load(Ordering::Relaxed), + dispatches_dropped_still_making: counters + .dispatches_dropped_still_making + .load(Ordering::Relaxed), host_step_sampler_sets_made: counters .host_step_sampler_sets_made .load(Ordering::Relaxed), creation_pipelines_made: counters.creation_pipelines_made.load(Ordering::Relaxed), + creations_left_making: counters.creations_left_making.load(Ordering::Relaxed), creation_pipelines_drawn: counters.creation_pipelines_drawn.load(Ordering::Relaxed), creation_render_pipelines_made: counters .creation_render_pipelines_made diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 3f0d09abe..1ac2ec56f 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -66af4c03a23d3493ebef736c0e06922f655221a99d1ccf4235cca567bc750115 +3ccc1c29e515b3b1b112f88c18ceb092782179c4a7eb8cbb997639cc2094fc0d diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index b76659194..23f33ee80 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -562,6 +562,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &DELAYED_DEALLOCATORS, &READ_ONLY_PAGES, &MISPLACED, + &STILL_MAKING, &DEPTH_DENORMALS, &SIGNED_DEPTH_TESTS, &FIRST_SPARSE, @@ -761,6 +762,22 @@ fn an_anisotropic_state_without_mips_is_announced_through_metals_sampler() { /// takes its site, as a build without debug assertions does. const MISPLACED: [Degradation; 1] = [Degradation::MisplacedNotice]; +/// The kinds a draw and a dispatch take whose pipeline was still being made once their command +/// buffer's bound passed (`PipelineWaitPolicy::Bounded`, `pipeline_commit_wait` after its +/// commit), and a draw whose pipeline the driver failed to make. No lane meets them: a lane holds +/// none of the runtime's pipeline makings, a driver's compile outlasting the bound is a timing no +/// lane may count on, and no lane's pipeline fails. The runtime's own tests +/// `a_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing`, +/// `a_dispatch_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` and +/// `a_draw_whose_pipeline_was_not_made_runs_nothing_and_its_command_buffer_runs_on` take their +/// sites, the makings held in the device's pool by the runtime's test hold, the last one's +/// failure injected. +const STILL_MAKING: [Degradation; 3] = [ + Degradation::DrawDroppedStillMaking, + Degradation::DispatchDroppedStillMaking, + Degradation::DrawDroppedUnmade, +]; + /// The kind Metal's private option bit takes where the GPU's writes reach the memory here /// ([`the_private_option_bit_is_announced_on_a_heap_of_the_runtime_s_memory`], /// [`the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory`]). diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d4bfe1438..425b51a64 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 477; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1688; +pub const RUNTIME_VERSION: u32 = 1689; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/device/mod.rs b/crates/metal2vulkan/src/device/mod.rs index 6c9d87e76..6fc822178 100644 --- a/crates/metal2vulkan/src/device/mod.rs +++ b/crates/metal2vulkan/src/device/mod.rs @@ -67,7 +67,7 @@ pub(crate) use mechanism::mechanism; pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd}; pub use policy::{ BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DevicePolicy, HalfChainPolicy, - HeapCompressionPolicy, HostPageTexturePolicy, RenderLoweringPolicy, + HeapCompressionPolicy, HostPageTexturePolicy, PipelineWaitPolicy, RenderLoweringPolicy, }; pub(crate) use profile::whole_point_size; pub use profile::{DeviceProfile, SpirvValidation}; diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs index 029b45408..be5bec3df 100644 --- a/crates/metal2vulkan/src/device/policy.rs +++ b/crates/metal2vulkan/src/device/policy.rs @@ -2,14 +2,16 @@ //! decide a `DeviceProfile`. use crate::device::profile::{GuestIsolation, HandleDomain, PointerDomain}; +use std::time::Duration; /// Policy inputs of `Device::new`. Every field but `heap_compression`, `completion`, -/// `batch_order`, `render_lowering` and `host_page_textures` can change emitted code, so the -/// profile carries it (containment as the encoding it selects) and its fingerprint covers it; those -/// five are the runtime's alone (a heap's compressed texture's image, when the host sees a command +/// `batch_order`, `render_lowering`, `host_page_textures`, `pipeline_waits`, +/// `pipeline_creation_wait` and `pipeline_commit_wait` can change emitted code, so the profile +/// carries it (containment as the encoding it selects) and its fingerprint covers it; those eight +/// are the runtime's alone (a heap's compressed texture's image, when the host sees a command /// buffer complete, how a batch begins after the earlier ones of its queue, where a render -/// encoder's calls are lowered, and what holds a sampled texture over host pages), and no profile -/// carries them. +/// encoder's calls are lowered, what holds a sampled texture over host pages, and whether and how +/// long a pipeline the driver is still making is waited for), and no profile carries them. #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] @@ -53,6 +55,25 @@ pub struct DevicePolicy { /// without `shaderFloat16`, rounds where a value leaves it (the default) or at each operation. /// Changes emitted code: the profile carries it. pub half_chains: HalfChainPolicy, + /// Whether a render or compute state's creation, and a committed command buffer, wait a + /// bound for a pipeline the driver is still making, the command buffer then dropping the + /// draws and dispatches whose pipeline is not made (the default), or until it is made. The + /// bounds are the two fields below. The runtime's choice alone: no emitted code changes. + pub pipeline_waits: PipelineWaitPolicy, + /// Under [`PipelineWaitPolicy::Bounded`], the longest a render or compute state's creation + /// waits for the pipelines it hands to the runtime's pool, one deadline for all of them from + /// the wait's start: then it returns, the makings going on. 4.5 s by default, so a host call that + /// both creates a state and commits a command buffer (a guest's FIFO step may) waits 9 s at + /// most for the driver's makings, under a guest's 10 s check of its FIFO. Unread under + /// `Exact`. The runtime's alone: no emitted code changes. + pub pipeline_creation_wait: Duration, + /// Under [`PipelineWaitPolicy::Bounded`], how long after its commit a command buffer waits + /// for the pipelines of its commands the driver is still making: one deadline, its commit plus + /// this, which its draws, compute dispatches, tile dispatches and execution replays share, + /// wherever they record (in its `commit`, or on the runtime's scheduler thread), past which + /// each such command records as nothing. 4.5 s by default (as the creation wait, above). Unread + /// under `Exact`. The runtime's alone: no emitted code changes. + pub pipeline_commit_wait: Duration, } impl DevicePolicy { @@ -60,7 +81,8 @@ impl DevicePolicy { /// compressed image of a heap's texture Metal keeps compressed, command buffers ready together /// in one kernel submission, batches of one queue ordered by their ends where the driver runs /// them one after another, and a sampled - /// texture over host pages in place where the device's check passed. + /// texture over host pages in place where the device's check passed, and a pipeline still + /// being made waited for a bound (4.5 s at a state's creation, and 4.5 s from a commit). pub const UNTRUSTED: DevicePolicy = DevicePolicy { pointer_domain: PointerDomain::ResidentTable, handle_domain: HandleDomain::Table, @@ -72,6 +94,9 @@ impl DevicePolicy { render_lowering: RenderLoweringPolicy::AtCall, host_page_textures: HostPageTexturePolicy::InPlace, half_chains: HalfChainPolicy::AtExits, + pipeline_waits: PipelineWaitPolicy::Bounded, + pipeline_creation_wait: Duration::from_millis(4500), + pipeline_commit_wait: Duration::from_millis(4500), }; /// This policy with Metal's answer wherever the choices offer it: a heap's texture whose bytes @@ -82,9 +107,10 @@ impl DevicePolicy { /// the accesses it depends on alone ([`BatchOrderPolicy::Exact`]), each render encoder /// call lowered inside the call, which returns every refusal /// ([`RenderLoweringPolicy::AtCall`]), every texture over host pages a shadow, whose - /// copies touch its texels alone ([`HostPageTexturePolicy::Shadow`]), and each `half` - /// operation rounded on a device without `shaderFloat16` ([`HalfChainPolicy::EachOperation`]). - /// Every other field is kept. + /// copies touch its texels alone ([`HostPageTexturePolicy::Shadow`]), each `half` + /// operation rounded on a device without `shaderFloat16` ([`HalfChainPolicy::EachOperation`]), + /// and a render state's predicted pipeline made at its creation, each draw's pipeline waited + /// for until it is made ([`PipelineWaitPolicy::Exact`]). Every other field is kept. pub const fn exact_answers(self) -> DevicePolicy { DevicePolicy { heap_compression: HeapCompressionPolicy::Uncompressed, @@ -93,6 +119,7 @@ impl DevicePolicy { render_lowering: RenderLoweringPolicy::AtCall, host_page_textures: HostPageTexturePolicy::Shadow, half_chains: HalfChainPolicy::EachOperation, + pipeline_waits: PipelineWaitPolicy::Exact, ..self } } @@ -266,3 +293,48 @@ pub enum HalfChainPolicy { /// Every operation's result rounded to `half`, as the AIR computes it. EachOperation, } + +/// How long the runtime waits for a draw's `VkPipeline` the driver is still making. Metal makes a +/// render state's pipeline inside `newRenderPipelineState`, so no command buffer of Metal's waits +/// for a compile, and no draw of a state that was made is dropped. The runtime makes a state's +/// pipelines on its pool while the draws that need them go on (a draw's own key, and a state's +/// predicted key), so a command buffer committed before one is made waits for it. A driver's cold +/// compile (MoltenVK on a cold Metal compiler service) can take seconds, past a guest's watchdog, +/// where a host that creates a state lazily inside a command buffer's encoding would wait inside +/// it. The runtime's choice alone: no emitted code changes. +#[non_exhaustive] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +pub enum PipelineWaitPolicy { + /// The default. A render or compute state's creation hands the making of its predicted + /// pipeline to the runtime's pool and waits for it [`DevicePolicy::pipeline_creation_wait`] at + /// most (4.5 s by default), then returns with it still being made; a committed command buffer + /// waits for its draws' and dispatches' (a compute encoder's, a render pass's tile + /// dispatches, an execution replay's draws) pipelines still being made until its commit plus + /// [`DevicePolicy::pipeline_commit_wait`] at most (4.5 s by default), one deadline its + /// commands share, then records those commands as nothing, the command buffer running on, + /// each counted, the first named, announced `draw-dropped-still-making` or + /// `dispatch-dropped-still-making`. Later command buffers draw and dispatch with each pipeline + /// once made. + /// + /// What one call blocks for, waiting for the driver's makings: a state's creation, its + /// creation wait; a `commit`, which records there what it can (a pass whose pipelines are + /// made, an execution of render commands the CPU writes, which waits for its pipelines), until + /// its own deadline at most (the moment it committed plus its commit wait), whatever earlier + /// command buffers wait for (their deadlines are earlier); every other recording runs on the + /// runtime's scheduler thread, which no program call waits for. A creation waits on no command buffer's + /// deadline and a commit on no creation's, so a host call that creates a state and commits a + /// command buffer waits their sum at most: 9 s by default. Made until made, under this value + /// too, where the call that makes them waits for them: a draw that records nothing (no + /// vertices or instances, or culled whole), a draw in a pass of custom sample positions, and + /// one recorded again into another instance of its pass (an extended-range color's `half` + /// shadow starting), each in the draw's call or in an execution's replay; a device replay's + /// draws (an execution of render commands the GPU may write, recorded on the GPU), in its + /// `commit`; and a making that failed, made again by its command's recording. + #[default] + Bounded, + /// A render or compute state's creation makes its predicted pipeline before it returns, as + /// Metal compiles there, and a committed command buffer waits for each of its draws' and + /// dispatches' pipelines until it is made: no command is dropped for its making's time. + Exact, +} diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index 597a41a43..b407dd925 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -7,7 +7,7 @@ use crate::device::{ BatchOrderPolicy, CompletionPolicy, DevicePolicy, HalfChainPolicy, HeapCompressionPolicy, - HostPageTexturePolicy, RenderLoweringPolicy, + HostPageTexturePolicy, PipelineWaitPolicy, RenderLoweringPolicy, }; use crate::pipeline::PrecisionNote; use std::collections::BTreeSet; @@ -59,12 +59,17 @@ fn choices() -> Vec { // The accuracy choices, below. // The runtime's: a heap's compressed texture's image, when the host sees a command buffer // complete, how a batch begins after the earlier ones of its queue, where a render - // encoder's calls are lowered, and what holds a sampled texture over host pages. + // encoder's calls are lowered, what holds a sampled texture over host pages, and whether and + // how long a pipeline being made is waited for (the bounds' values: + // `the_ledger_states_the_pipeline_wait_bounds`). heap_compression: _, completion: _, batch_order: _, render_lowering: _, host_page_textures: _, + pipeline_waits: _, + pipeline_creation_wait: _, + pipeline_commit_wait: _, // The translator's: how a `half` chain rounds without `shaderFloat16`. half_chains: _, } = p; @@ -75,6 +80,7 @@ fn choices() -> Vec { choice!(p.render_lowering: RenderLoweringPolicy { AtCall, Worker }), choice!(p.host_page_textures: HostPageTexturePolicy { InPlace, Shadow }), choice!(p.half_chains: HalfChainPolicy { AtExits, EachOperation }), + choice!(p.pipeline_waits: PipelineWaitPolicy { Bounded, Exact }), ] } @@ -467,3 +473,53 @@ fn exact_answers_shadow_every_texture_over_host_pages() { HostPageTexturePolicy::Shadow ); } + +/// The runtime's choice of how long a draw's pipeline being made is waited for (`pipeline_waits`) +/// moves no committed profile's fingerprint: no profile carries it, so no translation follows it. +#[test] +fn the_runtime_s_pipeline_waits_choice_keys_no_profile() { + use crate::spirv::testing::committed_profiles_with; + let bounded = committed_profiles_with(DevicePolicy::UNTRUSTED).expect("profiles"); + let exact = committed_profiles_with(DevicePolicy { + pipeline_waits: PipelineWaitPolicy::Exact, + ..DevicePolicy::UNTRUSTED + }) + .expect("profiles"); + assert_eq!(bounded.len(), exact.len()); + for ((stem, b), (other, e)) in bounded.iter().zip(&exact) { + assert_eq!(stem, other); + assert_eq!(b.fingerprint(), e.fingerprint(), "{stem}"); + } +} + +/// `DevicePolicy::exact_answers()` waits for every draw's pipeline until it is made, and the +/// default waits a bound. +#[test] +fn exact_answers_wait_for_every_pipeline() { + assert_eq!( + DevicePolicy::UNTRUSTED.pipeline_waits, + PipelineWaitPolicy::Bounded + ); + assert_eq!( + DevicePolicy::UNTRUSTED.exact_answers().pipeline_waits, + PipelineWaitPolicy::Exact + ); +} + +/// The ledger's row of the pipeline waits states each bound as the default policy sets it, as +/// `field = N s`: a changed bound changes its row. +#[test] +fn the_ledger_states_the_pipeline_wait_bounds() { + let ledger = text("../../docs/FAST-PATHS.md"); + let p = DevicePolicy::UNTRUSTED; + for (field, bound) in [ + ("pipeline_creation_wait", p.pipeline_creation_wait), + ("pipeline_commit_wait", p.pipeline_commit_wait), + ] { + let named = format!("{field} = {} s", bound.as_secs_f64()); + assert!( + ledger.contains(&named), + "docs/FAST-PATHS.md does not state `{named}`, the default's bound" + ); + } +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 194028e58..ca35a7140 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1384,6 +1384,7 @@ enum metal2vulkan::device::HandleDomain #[cfg_attr(feature = "serde", derive(ser enum metal2vulkan::device::HeapCompressionPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HeapCompressionPolicy enum metal2vulkan::device::HostPageTexturePolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum HostPageTexturePolicy enum metal2vulkan::device::Independence #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum Independence +enum metal2vulkan::device::PipelineWaitPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PipelineWaitPolicy enum metal2vulkan::device::PointerDomain #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum PointerDomain enum metal2vulkan::device::RenderLoweringPolicy #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub enum RenderLoweringPolicy enum metal2vulkan::device::ResolveMode #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ResolveMode @@ -2475,6 +2476,7 @@ field metal2vulkan-runtime::WorkCounts.creation_pipelines_drawn pub creation_pip field metal2vulkan-runtime::WorkCounts.creation_pipelines_made pub creation_pipelines_made: u64 field metal2vulkan-runtime::WorkCounts.creation_render_pipelines_drawn pub creation_render_pipelines_drawn: u64 field metal2vulkan-runtime::WorkCounts.creation_render_pipelines_made pub creation_render_pipelines_made: u64 +field metal2vulkan-runtime::WorkCounts.creations_left_making pub creations_left_making: u64 field metal2vulkan-runtime::WorkCounts.dedicated_memory_blocks_live pub dedicated_memory_blocks_live: u64 field metal2vulkan-runtime::WorkCounts.depth_attachments_moved pub depth_attachments_moved: u64 field metal2vulkan-runtime::WorkCounts.depth_instances_held pub depth_instances_held: u64 @@ -2492,6 +2494,7 @@ field metal2vulkan-runtime::WorkCounts.dirty_wait_nanos pub dirty_wait_nanos: u6 field metal2vulkan-runtime::WorkCounts.dirty_waits pub dirty_waits: u64 field metal2vulkan-runtime::WorkCounts.dirty_waits_unanswered pub dirty_waits_unanswered: u64 field metal2vulkan-runtime::WorkCounts.dispatch_pipelines_pooled pub dispatch_pipelines_pooled: u64 +field metal2vulkan-runtime::WorkCounts.dispatches_dropped_still_making pub dispatches_dropped_still_making: u64 field metal2vulkan-runtime::WorkCounts.dispatches_planned_as_before pub dispatches_planned_as_before: u64 field metal2vulkan-runtime::WorkCounts.dispatches_pushing_set_zero pub dispatches_pushing_set_zero: u64 field metal2vulkan-runtime::WorkCounts.dispatches_settled_as_before pub dispatches_settled_as_before: u64 @@ -2506,6 +2509,8 @@ field metal2vulkan-runtime::WorkCounts.draw_shapes_found pub draw_shapes_found: field metal2vulkan-runtime::WorkCounts.draw_shapes_made pub draw_shapes_made: u64 field metal2vulkan-runtime::WorkCounts.draw_shapes_reused pub draw_shapes_reused: u64 field metal2vulkan-runtime::WorkCounts.draw_states_recorded pub draw_states_recorded: u64 +field metal2vulkan-runtime::WorkCounts.draws_dropped_still_making pub draws_dropped_still_making: u64 +field metal2vulkan-runtime::WorkCounts.draws_dropped_unmade pub draws_dropped_unmade: u64 field metal2vulkan-runtime::WorkCounts.draws_pushing_set_zero pub draws_pushing_set_zero: u64 field metal2vulkan-runtime::WorkCounts.draws_settled pub draws_settled: u64 field metal2vulkan-runtime::WorkCounts.driver_diagnostics_withheld pub driver_diagnostics_withheld: u64 @@ -3628,6 +3633,9 @@ field metal2vulkan::device::DevicePolicy.handle_domain pub handle_domain: Handle field metal2vulkan::device::DevicePolicy.heap_compression pub heap_compression: HeapCompressionPolicy field metal2vulkan::device::DevicePolicy.host_page_textures pub host_page_textures: HostPageTexturePolicy field metal2vulkan::device::DevicePolicy.isolation pub isolation: GuestIsolation +field metal2vulkan::device::DevicePolicy.pipeline_commit_wait pub pipeline_commit_wait: Duration +field metal2vulkan::device::DevicePolicy.pipeline_creation_wait pub pipeline_creation_wait: Duration +field metal2vulkan::device::DevicePolicy.pipeline_waits pub pipeline_waits: PipelineWaitPolicy field metal2vulkan::device::DevicePolicy.pointer_domain pub pointer_domain: PointerDomain field metal2vulkan::device::DevicePolicy.render_lowering pub render_lowering: RenderLoweringPolicy field metal2vulkan::device::DriverDiagnostic.id pub id: i32 @@ -4889,9 +4897,12 @@ macro-member metal2vulkan-runtime::Degradation::DeviceTexelConversion DeviceTexe macro-member metal2vulkan-runtime::Degradation::DeviceTranscendentals DeviceTranscendentals = "device-transcendentals"; macro-member metal2vulkan-runtime::Degradation::DeviceVertexConversion DeviceVertexConversion = "device-vertex-conversion"; macro-member metal2vulkan-runtime::Degradation::DiscardDropsSimdgroupStores DiscardDropsSimdgroupStores = "discard-drops-simdgroup-stores"; +macro-member metal2vulkan-runtime::Degradation::DispatchDroppedStillMaking DispatchDroppedStillMaking = "dispatch-dropped-still-making", Precision, macro-member metal2vulkan-runtime::Degradation::DontCareLoadTiles DontCareLoadTiles = "dont-care-load-tiles", Precision, macro-member metal2vulkan-runtime::Degradation::DontCareStandIn DontCareStandIn = "dont-care-stand-in", Performance, macro-member metal2vulkan-runtime::Degradation::DontCareStore DontCareStore = "dont-care-store", Precision, +macro-member metal2vulkan-runtime::Degradation::DrawDroppedStillMaking DrawDroppedStillMaking = "draw-dropped-still-making", Precision, +macro-member metal2vulkan-runtime::Degradation::DrawDroppedUnmade DrawDroppedUnmade = "draw-dropped-unmade", Precision, macro-member metal2vulkan-runtime::Degradation::DrawnDepthCopy DrawnDepthCopy = "drawn-depth-copy", Precision, macro-member metal2vulkan-runtime::Degradation::DriverPipelineCacheKept DriverPipelineCacheKept = "driver-pipeline-cache-kept", Performance, macro-member metal2vulkan-runtime::Degradation::EmulatedMeshDraws EmulatedMeshDraws = "emulated-mesh-draws", Performance, @@ -7464,6 +7475,7 @@ method metal2vulkan-runtime::CommandBuffer::compute_command_encoder pub fn compu method metal2vulkan-runtime::CommandBuffer::compute_command_encoder_with_dispatch_type pub fn compute_command_encoder_with_dispatch_type(&self, dispatch_type: DispatchType) -> Result method metal2vulkan-runtime::CommandBuffer::compute_command_encoder_with_raw_dispatch_type pub fn compute_command_encoder_with_raw_dispatch_type(&self, raw: u64) -> Result method metal2vulkan-runtime::CommandBuffer::device pub fn device(&self) -> &Device +method metal2vulkan-runtime::CommandBuffer::dropped_draw pub fn dropped_draw(&self) -> Option method metal2vulkan-runtime::CommandBuffer::encode_signal_event pub fn encode_signal_event(&self, event: EventRef<'_>, value: u64) -> Result<(), Error> method metal2vulkan-runtime::CommandBuffer::encode_signal_event_scheduled pub fn encode_signal_event_scheduled(&self, event: &SharedEvent, value: u64) -> Result<(), Error> method metal2vulkan-runtime::CommandBuffer::encode_signal_vk_semaphore pub unsafe fn encode_signal_vk_semaphore(&self, semaphore: vk::Semaphore) -> Result<(), Error> @@ -12346,6 +12358,8 @@ variant metal2vulkan::device::HostPageTexturePolicy::Shadow Shadow variant metal2vulkan::device::Independence::All All variant metal2vulkan::device::Independence::None None variant metal2vulkan::device::Independence::Only32Bit Only32Bit +variant metal2vulkan::device::PipelineWaitPolicy::Bounded Bounded +variant metal2vulkan::device::PipelineWaitPolicy::Exact Exact variant metal2vulkan::device::PointerDomain::ResidentTable ResidentTable variant metal2vulkan::device::RenderLoweringPolicy::AtCall AtCall variant metal2vulkan::device::RenderLoweringPolicy::Worker Worker diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index b12e11af4..6d77121eb 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -230,6 +230,7 @@ surface! { enum RenderLoweringPolicy N; enum HostPageTexturePolicy N; enum HalfChainPolicy N; + enum PipelineWaitPolicy N; struct DeviceProfile O; struct SpirvValidation N; struct EnabledCaps N; diff --git a/docs/API.md b/docs/API.md index c76533e01..d4439ed78 100644 --- a/docs/API.md +++ b/docs/API.md @@ -132,7 +132,8 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: while the program goes on. A program that runs 16 batches ahead of that thread waits for it in its next call, and one 4 encoders' ends ahead in its next `end_encoding`. `end_encoding` hands the encoder's end to that thread too and returns; the next call that follows the end in its command buffer (another encoder, an event or semaphore - command, `commit_failed`, `refusal`, `used_resources`, `ended_encoders`, `failed_pipeline`) + command, `commit_failed`, `refusal`, `used_resources`, `ended_encoders`, `failed_pipeline`, + `dropped_draw`) lowers on the program's thread what the thread has not, and a rebind or detach of host pages and `Device::work_counts` lower every encoder's first. `commit` makes its checks at the call (committed already, an encoder open, one abandoned) and returns, its status `Committed`, its own work left to run once the end is lowered, on the @@ -167,6 +168,31 @@ compile does. `DevicePolicy::default()` is `DevicePolicy::UNTRUSTED`: Notices a logged call's lowering announces name the call (`DegradeNotice::call`) and may reach the message sink on the lowering thread, and `DeviceOptions::lowering_refuses` turns the kinds it lists into such refusals (section 9). +- **A pipeline still being made waited for a bound** (`PipelineWaitPolicy::Bounded`, the + default; the runtime's choice, no pipeline differs). A render or compute state's creation + hands the driver's making of its predicted pipeline to the runtime's pool and waits for it + `DevicePolicy::pipeline_creation_wait` at most; a committed command buffer waits until its + commit plus `DevicePolicy::pipeline_commit_wait` at most, one deadline its commands share, for + its draws' and dispatches' (a compute encoder's, a render pass's tile dispatches) pipelines + still being made, an execution's replayed draws among them (whose pipelines the commit hands to + the pool), then records each such command as nothing (`draw-dropped-still-making`, + `dispatch-dropped-still-making`, the first named by `CommandBuffer::dropped_draw` with + `VK_TIMEOUT`, counted `WorkCounts::draws_dropped_still_making` and + `dispatches_dropped_still_making`), and later command buffers draw and dispatch with the + pipeline once made. Both bounds are 4.5 s by default. What one call waits for the driver's + makings: a state's creation, its creation wait at most; a `commit`, until its own deadline at + most (it records there what it can, an execution of render commands the CPU writes among + them; every other recording runs on the runtime's scheduler thread, which no call waits for). A + creation waits on no command buffer's deadline and a commit on no creation's, so a host step + that creates a state and commits a command buffer waits their sum at most, 9 s by default, + under a guest's 10 s FIFO check, where a driver's cold compile took 11.6 s (MoltenVK with a cold + Metal compiler service). Made until made under this value too, in the call that makes them: a + draw that records nothing, a draw in a pass of custom sample positions, and one recorded again + into another instance of its pass (each in the draw's call or an execution's replay), a device + replay's draws (in its `commit`), and a making that failed, made again by its command's + recording. `pipeline_waits = PipelineWaitPolicy::Exact`, which `exact_answers()` selects, makes + the predicted pipeline before the creation returns, as Metal compiles there, and waits for + every draw's and dispatch's until made. Loops run as written: no execution bound is translated in. @@ -2480,6 +2506,47 @@ bound. and the submission checks of the batches behind a queue's next one run with its own, before the batch before them is submitted; their commands, barriers and GPU times are unchanged; `CompletionPolicy::Exact` submits and checks each batch alone. +- `metal2vulkan-degrade-draw-dropped-still-making` (precision). `DrawDroppedStillMaking`: A draw + whose `VkPipeline` the driver was still making once its command buffer's bound passed + (`PipelineWaitPolicy::Bounded`, the default: its commit plus + `DevicePolicy::pipeline_commit_wait`, 4.5 s by default) ran nothing: its recording + records the barriers and the visibility query around it and no draw, and the command buffer runs + on without error. Metal makes a render state's pipelines inside `newRenderPipelineState`, so none + of its draws waits for a compile; the runtime makes them on its pool, a state's predicted one + among them (the creation waits for it `DevicePolicy::pipeline_creation_wait` at most), so a + driver's cold compile (seconds on + MoltenVK with a cold Metal compiler service) cannot hold the command buffer past a guest's + watchdog. Announced where the draw is recorded: in the program's `commit`, or the command + buffer's host step. Cost: the draw's commands ran nothing, where Metal's draw renders; the + command buffers committed after the pipeline is made draw with it; + `CommandBuffer::dropped_draw` names the first such draw with the error VK_TIMEOUT; + `PipelineWaitPolicy::Exact` waits until the pipeline is made. +- `metal2vulkan-degrade-draw-dropped-unmade` (precision). `DrawDroppedUnmade`: A draw whose + `VkPipeline` the driver failed to make after the draw returned (the runtime makes a draw's + pipeline while the draw goes on, `render/pending.rs`) ran nothing: its recording records the + barriers and the visibility query around it and no draw, and the command buffer runs on without + error. Metal makes a render state's pipelines inside `newRenderPipelineState`, which fails there, + so none of its draws meets such a failure. The notice names the draw, its state, the variant and + the driver's error. Announced where the draw is recorded: in the program's `commit`, or the + command buffer's host step. Cost: the draw's commands ran nothing, where Metal's draw renders; + the draws after it that need the same pipeline make it again; `CommandBuffer::dropped_draw` + names the first such draw with the driver's error, and `WorkCounts::draws_dropped_unmade` counts + them. +- `metal2vulkan-degrade-dispatch-dropped-still-making` (precision). `DispatchDroppedStillMaking`: A + compute dispatch, or a render pass's tile dispatch, whose `VkPipeline` the driver was still + making once its command buffer's bound passed (`PipelineWaitPolicy::Bounded`, the default: its + commit plus `DevicePolicy::pipeline_commit_wait`, 4.5 s by default) ran nothing: its recording + records its barriers (a tile dispatch's copies into + its scratch and back) and no dispatch, and the command buffer runs on without error. Metal makes + a compute state's pipeline inside `newComputePipelineState`, so none of its dispatches waits for + a compile; the runtime makes a dispatch's on its pool, a compute state's predicted one among them + (the creation waits for it `DevicePolicy::pipeline_creation_wait` at most), so a driver's cold + compile cannot hold the command + buffer past a guest's watchdog. Announced where the dispatch is recorded: in the program's + `commit`, or the command buffer's host step. Cost: the dispatch ran nothing and wrote nothing, + where Metal's dispatch runs; the command buffers committed after the pipeline is made dispatch + with it; `CommandBuffer::dropped_draw` names the first such dispatch with the error VK_TIMEOUT; + `PipelineWaitPolicy::Exact` waits until the pipeline is made. - `metal2vulkan-degrade-misplaced-notice` (performance). `MisplacedNotice`: In a build without debug assertions, a notice announced where the runtime's rule announces none (`DegradeNotice::misplaced` names its kind and `NoticePlace`): inside a pipeline pool's piece, or, for a kind announced at diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 0eb6626b3..c3088043e 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -41,6 +41,7 @@ three consumer pipelines: A2X (`a2x-s4`, `a2x-s96`), Xgc14 (`xgc14-bgra8`) and X | Batches of command buffers on one `VkQueue`, on a driver measured to start no kernel submission of a queue before the one before it completed (ANV, RADV and NVIDIA's; `batch_order.rs`), are ordered by their ends: each ends with a barrier ordering its work before every later command of its `VkQueue` (the exact form's end orders it before the host's reads and writes alone), so a batch that depends on an earlier one there begins with no barrier of its own, often no command buffer of barriers, and its first encoder's GPU start is written at the bottom of the pipe, once everything before it completed. Metal starts an independent command buffer committed behind running work while that work runs (an M3 Max under macOS 27.0.1, probe `gpustart`); those drivers ran two batches of independent work one after the other under every shape measured (no end barrier, the host's or the widened one; in one `vkQueueSubmit` or two, merged into one kernel submission or not), where two dispatches of one command buffer ran side by side. The runtime's: no pipeline differs. | `batch_order = BatchOrderPolicy::Ends` | `batch_order = BatchOrderPolicy::Exact`: a barrier for each dependency of a batch's work on an earlier batch's of its `VkQueue`, the end's barrier to the host's reads and writes alone, the GPU start written at the top of the pipe; every other driver takes it under either value | None: on those drivers each batch starts once the one before it completed under either value, so the work's order, its results and its GPU times are the same, and a batch's GPU start is the end of the work before it, when such a driver starts it. Not announced; `runtime_lane::commit_work` and `runtime_lane::gpu_times` test both values | UHD 770 (ANV, RPL-S), the consumer's frame shape over 520 host imports, 67 command buffers a frame, Grouped completion, the widened end barrier against the exact form (a probe build of each): with no fill ahead of each command buffer, 67.0 command buffers submitted a frame against 129.3-129.7, the GPU's span a frame 1.84-1.90 ms against 1.99-2.06 ms, a frame through completion 2.13-2.22 ms against 2.27-2.38 ms; with a 1 MiB fill ahead of each, 134.0 against 262.9, 8.03-8.22 ms against 8.32-8.42 ms, 9.00-9.15 ms against 9.25-9.36 ms. Radeon 780M (RADV, Mesa 26.0.8), this switch: with no fill, 67.0 against 128.9-129.0, a frame through completion 48.3-48.6 ms against 42.6-47.0 ms; with a 16 MiB fill committed at once, 134.0 against 251.0-251.1, 50.6-50.8 ms against 50.8-57.3 ms; committed every 1 ms, 134.0 against 249.7-250.2, 71.3-83.6 ms against 106.3-113.6 ms (each kernel submission there leaves about 2.5 ms of the GPU idle over 520 host imports, which sets these frames) | | A chain of `half` additions, subtractions and products on a device without `shaderFloat16` (vk12-floor, SwiftShader, Pascal; capability emulation: the module computes each in `float` and rounds it by the device's `OpQuantizeToF16`): an operation whose flags hold `contract` and `reassoc` and whose result only such operations read is held at `float` precision unrounded, so the chain rounds where a value leaves it (a store, an output, a conversion, a comparison, a call, a phi, a vector move, an operation without both flags), one quantize per exit instead of one per operation (`lower::arith::half_chain`). A device with `shaderFloat16` computes `half` alike under either value. | `half_chains = HalfChainPolicy::AtExits` | `half_chains = HalfChainPolicy::EachOperation`: every operation's result rounded to `half`, as the AIR computes it | The result may differ from the rounded operations' by the roundings the chain skips, each within half a unit in the last place of a `half` at its step, compounded along the chain; a value inside the chain past `half`'s range (65504) stays finite where the rounded operations reach infinity. Within the AIR's flags, which let a compiler regroup and fuse such operations. `FastMathRewrites` (`fast-math-rewrites`) | Not timed. Size on vk12-floor (the fixtures' SPIR-V words, the default against the accurate form): `hfb_filter_bank` 121,270 against 131,766 (1,024 quantizes against 2,464), `grd_half_many_samples` 82,019 against 84,627, `nan_half_fast` 9,808 against 9,832 | | A texture that only samples or reads (no `RenderTarget`, `ShaderWrite` or `ShaderAtomic` usage) over host pages (a no-copy buffer's, or a no-copy heap's buffer's, imported by their pointer or as dma-bufs; or a buffer in fresh pages) is a linear image aliasing the pages in place, where the device's own check shows that the image's first move, which Vulkan lets read and write every byte bound to it (`VUID-VkImageCreateInfo-pNext-01443` makes such an image start `UNDEFINED`), leaves every byte alone while the CPU writes beside it: a deliberate, scoped exception to relying on documented Vulkan behaviour alone, the owner's ruling (`in_place.rs`). The check runs once per driver, release and runtime, per class of pages, on a thread of its own, its verdict kept in the shader cache's directory; a texture made before its class's verdict is a shadow. A texture whose usage renders or writes, a check that failed or made no image, and a pitch no image takes keep the shadow (`shadowed-texture`, its reason named, `WorkCounts::host_texture_shadows_*`). | `host_page_textures = HostPageTexturePolicy::InPlace` | `host_page_textures = HostPageTexturePolicy::Shadow`: every texture over host pages a shadow, its texels copied in before each command buffer that uses it and merged back after each write (the host-pages bullet under **Costs of matching Metal**) | Exact where the driver keeps what its check showed: the check covers texels, the bytes between rows and those after the image, of 1, 2, 4, 8 and 16-byte texels and a 3840x2160 surface, three rounds each; a driver whose first move changed a byte outside every round's window would undo a CPU write made meanwhile. Not announced where the check passed. A CPU write reaches the image's reads as it reaches the buffer's (Host Write Ordering Guarantees) | See **Costs of matching Metal** (host pages): the shadow copies a sampled 3840x2160 surface in whole each command buffer | +| A render or compute state's creation hands the driver's making of its predicted pipeline (`pipeline/predicted.rs`, `pipeline/dispatch_making.rs`) to the runtime's pool, kept by the state as a draw's or dispatch's making is, and waits for it `pipeline_creation_wait` at most; a committed command buffer's recordings wait until its commit plus `pipeline_commit_wait` at most, one deadline its commands share, for its draws' and dispatches' (a compute encoder's, a render pass's tile dispatches) pipelines still being made (the scheduler wakes at the bound, `StepWaits::until`), an execution's replayed draws (`render/pending.rs`) among them, whose pipelines the commit's settle hands to the pool (a device replay's, one recording for every command, waits until made under either value), then record each such command as nothing: a draw's barriers and visibility query, a dispatch's barrier (a tile dispatch's copies into its scratch and back), no draw or dispatch, the command buffer running on without error. The making goes on, and the command buffers after it draw and dispatch with the pipeline once made. Metal compiles inside `newRenderPipelineState`, so no draw of a made state waits or is dropped; a host that creates a state inside a command buffer's encoding (the consumer creates a guest's state at an execution's first lookup of it) held that execution through the driver's whole compile: 11.59 s inside one execution on an M2 Pro (MoltenVK 1.4.2, a cold Metal compiler service; a sample of such a stall finds the compile's thread waiting in `MVKMetalCompiler::compile` for Metal's compiler), past the guest's 10 s FIFO check, which ended the guest's task. Each bound is 4.5 s: a creation and a commit may fall in one step of the guest's FIFO (a task's jobs run one after another, and a draw's own variant waits under its command buffer's bound), and no runtime call waits for both, so one step waits 9 s at most for makings, under that 10 s check. A creation waits on no command buffer's deadline and a `commit` on no creation's; a `commit` waits until its own deadline at most (it records there what it can, an execution of render commands the CPU writes among them), every other recording on the scheduler's thread. Made until made under either value, in the call that makes them: a draw that records nothing, one in a pass of custom sample positions and one recorded again into another instance of its pass (each in the draw's call or an execution's replay), a device replay's draws (in its `commit`), and a failed making made again (`PipelineWaitPolicy`'s docs). The runtime's: no pipeline differs. | `pipeline_waits = PipelineWaitPolicy::Bounded`, `pipeline_creation_wait = 4.5 s`, `pipeline_commit_wait = 4.5 s` | `pipeline_waits = PipelineWaitPolicy::Exact`: the creation makes its predicted pipeline before it returns (a render state's first key on its own thread, the rest on the pool, joined; a compute state's on its own thread), an execution's settle makes its replayed draws' pipelines at the commit, and a command buffer waits for each draw's and dispatch's pipeline until it is made | A draw whose pipeline was still being made `pipeline_commit_wait` after its command buffer's commit renders nothing in that command buffer (only there: later ones draw it), where Metal's renders: content drawn once (a layer, a glyph cache) stays without it until redrawn. A creation returns after `pipeline_creation_wait` at most with its making in flight (`WorkCounts::creations_left_making`). `DrawDroppedStillMaking` (`draw-dropped-still-making`), at each such draw where `DeviceOptions::announce_each` asks, else once per device; `CommandBuffer::dropped_draw` names the first with `VK_TIMEOUT`; `WorkCounts::draws_dropped_still_making`; `deferred_calls::a_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` and `under_the_exact_wait_a_held_making_holds_its_command_buffer_until_it_lands`. A dispatch whose pipeline was still being made then writes nothing in that command buffer, where Metal's runs: `DispatchDroppedStillMaking` (`dispatch-dropped-still-making`), `WorkCounts::dispatches_dropped_still_making`, the first named by `dropped_draw`; `deferred_calls::a_dispatch_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing`, `a_compute_state_s_creation_waits_its_bound_for_its_predicted_making` and `a_replayed_draw_whose_pipeline_is_still_being_made_at_its_bound_runs_nothing` | No GPU cost. The exact form holds the creating thread, and the command buffer, for the whole compile: up to 11.59 s on the M2 Pro's cold boot (that boot's 2,483 render state creations, translation included: 300 over 16 ms, 151 over 100 ms, 14 over 250 ms, 3 over 1 s, the longest 11.59 s, 5.82 s and 1.17 s), where the default holds a creation for 4.5 s at most and a command buffer for 4.5 s from its commit, which drops the draws of the compiles that outlast those (2 of that boot's 2,483 were over 4.5 s) for the command buffers committed before they land; bounds of 1 s dropped 39 draws in a cold boot on the M2 Pro, and the guest's menu bar, drawn once, stayed half drawn | All at once: `DevicePolicy::exact_answers()` sets every switch above; each row states its own cost. @@ -692,7 +693,9 @@ driver's. Each is open work. integers, which the M3 Max's back end cannot legalize where it lands in the kernel's constant program: MoltenVK, whose SPIRV-Cross writes such a loop in that shape, fails the pipeline's making (`XPC_ERROR_CONNECTION_INTERRUPTED`), and the runtime returns the failure - (`CommandBufferError::PipelineCreation`, or `Error::Vulkan` at an indirect command's commit). + (`CommandBufferError::PipelineCreation` for a dispatch, or `Error::Vulkan` at an indirect + command's commit; a draw whose pipeline it made after the draw returned runs nothing, + `CommandBuffer::dropped_draw`). Metal runs the AIR, which gets no such rewrite (case `authored-four-iteration-loop`). No form of the loop is known that avoids the rewrite for every such loop. - **An anisotropic sampler without a mip filter whose min and mag filters differ, through Metal's