From 56cdcb707557ebac7839bd0c6ea06085850cf59e Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 22 Nov 2026 10:16:20 -0800 Subject: [PATCH] Runtime: a command buffer's compute work goes in pieces of 4 ms, and the device's room goes to the queue that waited longest What: each command buffer's compute work is cut into pieces before a dispatch that would take the piece's expected GPU run past GROUP_RUN (now 4 ms, was 16 ms), and where a compute or blit encoder opens after a full piece; never inside or before a render pass. A dispatch's expected run is its kernel's rate (picoseconds per threadgroup, on the kernel's compiled content, shared by its states) times its threadgroups; a kernel with no rate yet goes in a piece of its own, and an indirect dispatch counts as one threadgroup and feeds no rate. Each piece is timed by its own pair of timestamps, from its first dispatch to its end, and that run alone feeds the rates (never the command buffer's span, which holds the runs of what passed between its pieces). Each piece is a submission of its own and waits for room. Room is the device's: room() over the device's submissions not seen complete, and among the queues that want room the one that last submitted earliest takes it, so a passed piece goes before the passer's queue's next. A command buffer of another queue committed after a cut one passes its pieces unless it holds a buffer or texture the cut one holds (by tracked id), waits on a fence it updates, or either reaches memory outside its resources: then it is held behind every piece. A cut command buffer whose later pieces wait for no event is scheduled as its first piece is staged. The rate is scheduling data of the same kind as a queue's measured expected run (QueueInner::expected_run, next_run): it bounds where a piece ends and never chooses between two forms of the work (rule 4's "no calibration"). Why: on the Iris Xe the guest's screen-frame writers waited behind a background service's running command buffer: 96.2 of 112.3 ms of each late writer's wait. The Mac runs a second queue's command buffer beside a running one (Radeon Pro 5300M at any priority, job m3-max-68137; UHD 630 where the number is lower, m3-max-68129). Verified: compile job pending (this commit carries no tests yet). --- crates/metal2vulkan-runtime/src/blit.rs | 2 +- crates/metal2vulkan-runtime/src/command.rs | 171 ++++++++++++- crates/metal2vulkan-runtime/src/counters.rs | 32 +++ crates/metal2vulkan-runtime/src/encoder.rs | 11 +- crates/metal2vulkan-runtime/src/kept.rs | 23 +- crates/metal2vulkan-runtime/src/lib.rs | 1 + crates/metal2vulkan-runtime/src/piece.rs | 130 ++++++++++ crates/metal2vulkan-runtime/src/pipeline.rs | 5 + .../src/render_encoder.rs | 2 +- crates/metal2vulkan-runtime/src/submit.rs | 239 ++++++++++++++---- 10 files changed, 545 insertions(+), 71 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/piece.rs diff --git a/crates/metal2vulkan-runtime/src/blit.rs b/crates/metal2vulkan-runtime/src/blit.rs index f051c9905..2e8a50d91 100644 --- a/crates/metal2vulkan-runtime/src/blit.rs +++ b/crates/metal2vulkan-runtime/src/blit.rs @@ -137,7 +137,7 @@ impl CommandBuffer { /// Err: [`Refusal::Committed`]; [`Refusal::EncoderOpen`] while another encoder of the command /// buffer is open. pub fn blit_command_encoder(&self) -> Result { - let mut building = self.open_encoder()?; + let mut building = self.open_encoder(true, false)?; building.count(Metric::Passes); Ok(BlitCommandEncoder { command_buffer: self.clone(), diff --git a/crates/metal2vulkan-runtime/src/command.rs b/crates/metal2vulkan-runtime/src/command.rs index 11912e463..2c1840040 100644 --- a/crates/metal2vulkan-runtime/src/command.rs +++ b/crates/metal2vulkan-runtime/src/command.rs @@ -13,7 +13,8 @@ use crate::hazard::{Access, Hazards}; use crate::kept::{Lent, Objects}; use crate::memory::Block; use crate::over::{self, Overs, Reached}; -use crate::pipeline::ComputePipelineState; +use crate::piece::Work; +use crate::pipeline::{Compiled, ComputePipelineState}; use crate::queue::QueueInner; use crate::record::{self, Reach, Recorder}; use crate::render::RenderPipelineState; @@ -34,7 +35,13 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; /// operations between them. The submit thread holds a segment whose waits are not yet met, and its /// queue's later command buffers behind it, while the segments before it run: an event the held /// part waits for can be signalled by the part before it. Each segment's commands end with one -/// barrier that makes their writes visible to every later command and to the host. +/// barrier that makes their writes visible to every later command and to the host. Its compute +/// work is cut into pieces too, before a dispatch that would take a piece's expected GPU run past +/// 4 ms and where a compute or blit encoder opens after a full piece, never inside a render pass +/// (`crate::piece`): each piece is a submission of its own, and a command buffer of another queue +/// committed meanwhile goes between two pieces unless it holds a buffer or texture the cut one +/// holds. It is scheduled as its first piece is submitted where its later pieces wait for no +/// event. /// /// Its GPU times come from two timestamps, written where its first commands begin and as the last /// command of its last segment, after the copies back of the images its commands wrote and its end @@ -289,6 +296,14 @@ pub(crate) struct Gpu { /// The occlusion queries of its render encoders' visibility results, from pools of its own, /// each given back to the device as it retires (`crate::visibility`). pub(crate) queries: Queries, + /// Its recording was cut into pieces (`crate::piece`), each a submission of its own. + pub(crate) cut: bool, + /// A dispatch reached memory through an address outside its resources: it shares every + /// resource with another queue's command buffer (`crate::submit`). + pub(crate) unbound: bool, + /// Of a cut command buffer, from its commit: the ids its buffers and textures are tracked by + /// (`crate::kept::ByKind::tracked`), sorted. + pub(crate) ids: Vec, } impl Gpu { @@ -310,6 +325,17 @@ impl Gpu { pub(crate) fn presents(&self) -> bool { (self.segments.last()).is_some_and(|segment| !segment.binary.is_empty()) } + + /// Whether `self`, committed after `cut`, a cut command buffer of another queue, holds a + /// resource `cut` holds, by the ids the hazards track them by (a view's is its texture's, a + /// heap's resources' the heap's), waits on a fence `cut` updates, or either reaches memory + /// outside its resources: then `cut`'s pieces go first (`crate::submit`). + pub(crate) fn shares(&self, cut: &Gpu) -> bool { + self.unbound + || cut.unbound + || self.kept.meets(&cut.ids) + || cut.fences.updates_for(&self.fences) + } } /// One submission's part of a command buffer: its waits, its commands and its signals. @@ -336,6 +362,13 @@ pub(crate) struct Segment { /// upload that leads its submission takes the copies back owed to them by writes submitted /// before it (`crate::over::ManagedOvers`). pub(crate) managed_reached: Vec>, + /// Its dispatches, which bound it as a piece (`crate::piece`). + pub(crate) work: Work, + /// Its own pair of timestamp queries, from its first dispatch to its end, whose span feeds + /// its kernels' rates; None where it dispatches nothing or found no pair. + pub(crate) stamps: Option, + /// A submission carried it, so its pair was written. + pub(crate) sent: bool, } pub(crate) struct Handlers { @@ -405,6 +438,9 @@ impl CommandBuffer { fences: Fences::default(), executed: Vec::new(), queries: Queries::default(), + cut: false, + unbound: false, + ids: Vec::new(), }, handlers: Handlers { scheduled: Vec::new(), @@ -444,11 +480,21 @@ impl CommandBuffer { f(state.open()?) } - /// Takes what is being recorded for an encoder, until [`close_encoder`](Self::close_encoder). - /// Err: [`Refusal::Committed`]; [`Refusal::EncoderOpen`]. - pub(crate) fn open_encoder(&self) -> Result { + /// Takes what is being recorded for an encoder, until [`close_encoder`](Self::close_encoder): + /// for a compute or blit encoder (`cut`), past the end of a full piece + /// ([`Building::cut`]); the commands of any other than a compute encoder follow the + /// segment's dispatches ([`Building::other_commands`]). + /// Err: [`Refusal::Committed`]; [`Refusal::EncoderOpen`]; [`Error::Vulkan`] where ending the + /// piece's commands fails. + pub(crate) fn open_encoder(&self, cut: bool, compute: bool) -> Result { let mut state = self.state(); - state.open()?; + let building = state.open()?; + if cut { + building.cut(Some(0))?; + } + if !compute { + building.other_commands(); + } state.encoding = true; Ok(state .building @@ -668,12 +714,15 @@ impl CommandBuffer { (building.device.core().counters).add(&mut building.tally); let Building { device, - gpu, + mut gpu, handlers, stamps, presents, .. } = building; + if gpu.cut { + gpu.ids = gpu.kept.tracked(); + } state.times.kernel_start = times::host_time(); state.stamps = stamps; // Its drawables are presented: the presentation engine's once it has run. @@ -844,7 +893,11 @@ impl CommandBuffer { /// observed. 0 until it completes, and for one that ended with an error. One whose segments /// hold no commands, no event wait and no event signal writes no timestamp: its start and end /// are one time, the latest GPU end of its queue's command buffers before it, or its kernel - /// end where that is later, as Metal reports for a command buffer that does no work. + /// end where that is later, as Metal reports for a command buffer that does no work. Of a + /// command buffer cut into pieces ([`Metrics::cuts`](crate::Metrics::cuts)), the span to + /// [`gpu_end_time`](Self::gpu_end_time) holds the runs of other queues' command buffers that + /// went between its pieces, as on the UHD 630 under macOS 26.7.1 the running command + /// buffer's end moved by the run of one that started beside it (job m3-max-68129). pub fn gpu_start_time(&self) -> u64 { self.state().times.gpu_start } @@ -859,7 +912,9 @@ impl CommandBuffer { /// uploads and copy-ins the runtime submits ahead of it are not in it /// ([`Metrics::runtime_command_buffer_gpu_nanos`](crate::Metrics::runtime_command_buffer_gpu_nanos)). /// 0 until it completes, and for one that ended with an error; its start time for one that - /// writes no timestamp. + /// writes no timestamp. Of a command buffer cut into pieces, it is later by the runs of other + /// queues' command buffers that went between its pieces + /// ([`gpu_start_time`](Self::gpu_start_time)). pub fn gpu_end_time(&self) -> u64 { self.state().times.gpu_end } @@ -1003,6 +1058,10 @@ impl Building { }; self.host_written |= back.iter().any(|copy| copy.shared); } + // The end of its own pair once its commands completed, before its end barrier. + if let Some(pair) = self.last().stamps { + times::write_end(&core.device, command, pair.pool, pair.first); + } // Its end barrier pays what is owed and starts the hazard sets again. self.owed = false; self.owed_all = false; @@ -1027,6 +1086,60 @@ impl Building { Ok(()) } + /// Before a dispatch expected to run `run` (None: its kernel's rate unknown), and with + /// `Some(0)` where a compute or blit encoder opens: where the segment's dispatches are a full + /// piece ([`Work::full`]), the commands after begin a new segment, the command buffer's next + /// piece, counted (`Metrics::cuts`). Not where a texture over a buffer in an image of its own, + /// or over a Managed buffer's device copy, was used in the segment: a cut there would add a + /// copy (`crate::over`). + pub(crate) fn cut(&mut self, run: Option) -> Result<(), Error> { + let last = self.last(); + // Commands after a signal go in a new segment anyway (`current`). + if !last.signals.is_empty() { + return self.split(); + } + let overs = last.overs.ahead() || last.overs.leaning().next().is_some(); + if !last.work.full(run) || overs || !last.managed_wrote.is_empty() { + return Ok(()); + } + self.split()?; + self.gpu.cut = true; + self.tally.count(Metric::Cuts); + Ok(()) + } + + /// A dispatch of `kernel`, of `groups` threadgroups (None for an indirect one), goes in the + /// current segment, after [`cut`](Self::cut); a dispatch reaching memory outside its resources + /// is `unbound`. + pub(crate) fn dispatched( + &mut self, + kernel: &Arc, + groups: Option, + unbound: bool, + ) { + self.gpu.unbound |= unbound; + self.last().work.add(kernel, groups); + } + + /// Commands of a blit or render encoder follow: the segment's run tells no rate. + pub(crate) fn other_commands(&mut self) { + self.last().work.blind(); + } + + /// Writes the start of the current segment's own pair into `command`, its command buffer, + /// before its first dispatch, where the device gives a pair. + pub(crate) fn stamp_piece(&mut self, command: vk::CommandBuffer) { + if self.last().stamps.is_some() { + return; + } + let core = self.device.core(); + let pair = core.stamps.take(&core.device, &core.counters); + if let Some(pair) = pair { + times::write_start(&core.device, command, pair.pool, pair.first); + } + self.last().stamps = pair; + } + fn wait(&mut self, event: &Arc, value: u64) -> Result<(), Error> { let last = self.last(); if last.command.is_some() || !last.signals.is_empty() { @@ -1629,10 +1742,35 @@ pub(crate) fn retire( } = completion; // Where its retirement begins, the step before its handlers (`Round::steps`): one clock read. let retiring = times::host_time(); - // Its own GPU run, by its timestamps, sets what its queue expects of the next - // (`QueueInner::expected_run`, which bounds the groups `submit.rs` joins). + // Each piece's own run, by its own pair, sets its kernels' rates (`crate::piece`), and its + // pair goes back, reset where a submission wrote it. + let mut pieces = 0; + for segment in &gpu.segments { + let Some(pair) = segment.stamps else { + continue; + }; + if let (true, None) = (segment.sent, error) { + // SAFETY: the pair's pool is the device's, and only this retirement resets its two + // queries, after this read. + if let Some((start, end)) = unsafe { pair.times(&core.device, &core.counters) } { + let run = core.ticks.span(start, end); + segment.work.ran(run); + pieces += run; + } + } + if segment.sent { + times::reset(&core.device, pair.pool, pair.first, 2); + } + core.stamps.give_back(pair); + } + // Its own GPU run sets what its queue expects of the next (`QueueInner::expected_run`, which + // bounds the groups `submit.rs` joins): by its timestamps, or where it was cut, its pieces' + // runs summed, without what other queues ran between them. if let Some((start, end)) = gpu_times { - inner.queue.ran(end.saturating_sub(start)); + inner.queue.ran(match gpu.cut { + true => pieces, + false => end.saturating_sub(start), + }); } // What was released while it was in flight may go (`crate::memory::Wait`). core.pool.ended(); @@ -1672,12 +1810,15 @@ pub(crate) fn retire( fences, executed, queries, + cut: _, + unbound: _, + ids, } = gpu; if let Some(recorder) = recorder { core.recorders.give_back(core, recorder); } ring.give_back(core); - drop((segments, blocks, images, fences, executed)); + drop((segments, blocks, images, fences, executed, ids)); queries.give_back(core); kept.clear(); if let Some(pair) = stamps { @@ -1741,6 +1882,7 @@ impl Drop for CbInner { let core = device.core(); let Gpu { recorder, + segments, mut kept, ring, queries, @@ -1749,6 +1891,9 @@ impl Drop for CbInner { if let Some(recorder) = recorder { core.recorders.give_back(core, recorder); } + for pair in segments.iter().filter_map(|segment| segment.stamps) { + core.stamps.give_back(pair); + } ring.give_back(core); if let Some(pair) = stamps { core.stamps.give_back(pair); diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index 2b870fc60..1bc123354 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -268,6 +268,12 @@ pub(crate) enum Metric { SubmissionsDuringFrees, /// [`Metrics::untimed_command_buffers`]. UntimedCommandBuffers, + /// [`Metrics::cuts`]. + Cuts, + /// [`Metrics::pieces_passed`]. + PiecesPassed, + /// [`Metrics::shared_holds`]. + SharedHolds, /// [`Metrics::sampler_element_writes`]. SamplerElementWrites, /// [`Metrics::stamps_not_available`]. @@ -340,6 +346,9 @@ const METRIC_ORDER: [Metric; METRICS] = [ Metric::AllocationsFreed, Metric::SubmissionsDuringFrees, Metric::UntimedCommandBuffers, + Metric::Cuts, + Metric::PiecesPassed, + Metric::SharedHolds, Metric::SamplerElementWrites, Metric::StampsNotAvailable, Metric::WaitsBehindCounter, @@ -723,6 +732,9 @@ struct Atomics { held_release_bytes: AtomicU64, held_release_starts: AtomicU64, untimed_command_buffers: AtomicU64, + cuts: AtomicU64, + pieces_passed: AtomicU64, + shared_holds: AtomicU64, sampler_element_writes: AtomicU64, stamps_not_available: AtomicU64, runtime_command_buffers: AtomicU64, @@ -890,6 +902,9 @@ impl Counters { Metric::AllocationsFreed => &a.allocations_freed, Metric::SubmissionsDuringFrees => &a.submissions_during_frees, Metric::UntimedCommandBuffers => &a.untimed_command_buffers, + Metric::Cuts => &a.cuts, + Metric::PiecesPassed => &a.pieces_passed, + Metric::SharedHolds => &a.shared_holds, Metric::SamplerElementWrites => &a.sampler_element_writes, Metric::StampsNotAvailable => &a.stamps_not_available, Metric::WaitsBehindCounter => &a.waits_behind_counter, @@ -1792,6 +1807,9 @@ impl Counters { held_release_bytes: a.held_release_bytes.load(Relaxed), held_release_starts: a.held_release_starts.load(Relaxed), untimed_command_buffers: a.untimed_command_buffers.load(Relaxed), + cuts: a.cuts.load(Relaxed), + pieces_passed: a.pieces_passed.load(Relaxed), + shared_holds: a.shared_holds.load(Relaxed), sampler_element_writes: a.sampler_element_writes.load(Relaxed), stamps_not_available: a.stamps_not_available.load(Relaxed), runtime_command_buffers: a.runtime_command_buffers.load(Relaxed), @@ -2615,6 +2633,20 @@ pub struct Metrics { /// as they began count here too, and their time in /// [`runtime_command_buffer_gpu_nanos`](Self::runtime_command_buffer_gpu_nanos) is lost. pub untimed_command_buffers: u64, + /// No Metal counterpart: the cuts that ended a piece of a command buffer, before a compute + /// dispatch that would take the piece's expected GPU run past 4 ms, or that follows one of a + /// kernel with no measured rate yet, or where a compute or blit encoder opens after a full + /// piece. Each piece is a submission of its own, so a command buffer of another queue + /// committed meanwhile goes between two pieces ([`CommandBuffer`](crate::CommandBuffer)). + pub cuts: u64, + /// Submissions of a queue's command buffers that went to the `VkQueue` while a cut command + /// buffer of another queue had pieces not yet submitted: they run before those pieces. + pub pieces_passed: u64, + /// Command buffers held behind every piece of a cut command buffer of another queue, + /// committed before them, as they hold a buffer or texture it holds (by the ids the hazards + /// track them by), wait on a fence it updates, or either reaches memory outside its + /// resources. + pub shared_holds: u64, /// Elements of set 1's sampler arrays written (`vkUpdateDescriptorSets`): a sampler state's or /// a constexpr sampler's placement and its going write only the elements whose sampler /// differs from what the index's element holds, so an equal state made at the index of one diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 729758965..a951f8833 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -13,6 +13,7 @@ use crate::indirect::IndirectCommandBuffer; use crate::kept::{Handle, Lent, Uncounted}; use crate::memory::BlockId; use crate::over::{self, Reached, Span}; +use crate::piece::Work; use crate::pipeline::{ address_word, Compiled, ComputePipelineState, FieldValue, Form, Interface, Kernel, Place, Which, PUSH_STAGES, SQUARE, @@ -448,7 +449,7 @@ impl CommandBuffer { &self, dispatch_type: DispatchType, ) -> Result { - let mut building = self.open_encoder()?; + let mut building = self.open_encoder(true, true)?; // SAFETY: the encoder holds `building`, whose device handle keeps the core, until it ends; // nothing uses the borrow after that. let core = unsafe { Uncounted::of(building.device.core()) }; @@ -1076,6 +1077,13 @@ impl ComputeCommandEncoder { pipeline: vk_pipeline, }); let interface = &kernel.interface; + // A dispatch that would take its piece past the bound begins the command buffer's next + // piece (`crate::piece`). + let groups = direct.map(|(_, groups, _)| groups.iter().map(|&n| u64::from(n)).product()); + let building = recording(&mut self.building); + building.cut(Work::expected(inner, groups))?; + let unbound = interface.reads_unbound || interface.writes_unbound; + building.dispatched(inner, groups, unbound); if self.facts.module != Some(module) { self.facts.managed = self.reaches_managed(interface); self.facts.host = self.writes_host(interface); @@ -1761,6 +1769,7 @@ impl Building { let command = self.command(Reach::Dispatches { indirect: matches!(launch, Launch::Indirect(..)), })?; + self.stamp_piece(command); // SAFETY: the command buffer is the current segment's, recording outside any render pass; // the pipeline is the device's, of its layout, and the window lies in the layout's one // push range, of `PUSH_STAGES`. diff --git a/crates/metal2vulkan-runtime/src/kept.rs b/crates/metal2vulkan-runtime/src/kept.rs index 1b449402d..d0876ee58 100644 --- a/crates/metal2vulkan-runtime/src/kept.rs +++ b/crates/metal2vulkan-runtime/src/kept.rs @@ -10,11 +10,11 @@ //! than the bound. They live in one allocation that moves whole between the queue and its command //! buffers ([`Objects`]), so a command buffer allocates and frees none of it. -use crate::buffer::Buffer; +use crate::buffer::{Buffer, BufferObject}; use crate::pipeline::ComputePipelineState; use crate::render::RenderPipelineState; use crate::sampler::SamplerState; -use crate::texture::Texture; +use crate::texture::{Texture, TextureObject}; use std::collections::HashSet; use std::hash::{BuildHasherDefault, Hasher}; use std::mem::ManuallyDrop; @@ -237,6 +237,25 @@ pub(crate) struct ByKind { } impl ByKind { + /// The ids the hazards track its buffers and textures by, a view's being its texture's and a + /// heap's resources' the heap's, each once, sorted. + pub(crate) fn tracked(&self) -> Vec { + let mut ids: Vec = self.ids().collect(); + ids.sort_unstable(); + ids.dedup(); + ids + } + + /// Whether one of its buffers or textures is tracked by one of `ids`, sorted. + pub(crate) fn meets(&self, ids: &[u32]) -> bool { + !ids.is_empty() && self.ids().any(|id| ids.binary_search(&id).is_ok()) + } + + fn ids(&self) -> impl Iterator + '_ { + let buffers = self.buffers.iter().map(BufferObject::tracked_id); + buffers.chain(self.textures.iter().map(TextureObject::tracked_id)) + } + /// Releases every object, keeping each list's capacity, within [`KEPT_BOUND`], for the next /// recording. pub(crate) fn clear(&mut self) { diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index d61ce0010..9cd212166 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -44,6 +44,7 @@ mod memory; mod over; mod own; mod pass; +mod piece; mod pipeline; mod pixel_format_info; mod places; diff --git a/crates/metal2vulkan-runtime/src/piece.rs b/crates/metal2vulkan-runtime/src/piece.rs new file mode 100644 index 000000000..926d87679 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/piece.rs @@ -0,0 +1,130 @@ +//! Pieces: a command buffer's compute work goes to the device's `VkQueue` in pieces, each one +//! segment, whose dispatches are expected to run on the GPU for at most +//! [`GROUP_RUN`](crate::submit::GROUP_RUN) together, so a command buffer of another queue committed +//! while one runs waits for that piece rather than for the whole command buffer +//! (`crate::submit`). A dispatch's expected run is its kernel's rate, the run of one of its +//! threadgroups, times its threadgroups. Each rate comes from the runs of the pieces that ran the +//! kernel, each piece timed by its own pair of timestamps, so the work of another queue's command +//! buffer that went between two pieces is in no rate. The rate is scheduling data, as a queue's +//! expected run is (`QueueInner::expected_run`): it bounds where a piece ends, and never chooses +//! between two forms of the work. + +use crate::pipeline::Compiled; +use crate::queue::next_run; +use crate::submit::GROUP_RUN; +use std::sync::atomic::{AtomicU64, Ordering::Relaxed}; +use std::sync::Arc; + +/// A kernel's rate: the GPU run of one threadgroup of its dispatches, in picoseconds, as the +/// pieces that ran it measured, rising at once to a longer one and halving the way toward a +/// shorter one ([`next_run`]); unknown until the first such piece completed. +pub(crate) struct Rate(AtomicU64); + +impl Default for Rate { + fn default() -> Rate { + Rate(AtomicU64::new(u64::MAX)) + } +} + +impl Rate { + /// The expected run, in nanoseconds, of `groups` threadgroups; None while the rate is + /// unknown. + pub(crate) fn expected(&self, groups: u64) -> Option { + let rate = self.0.load(Relaxed); + let nanos = u128::from(groups) * u128::from(rate) / 1000; + (rate != u64::MAX).then(|| u64::try_from(nanos).unwrap_or(u64::MAX)) + } + + /// A piece measured `picos` for each threadgroup of this kernel. + fn ran(&self, picos: u64) { + let _ = self.0.try_update(Relaxed, Relaxed, |rate| { + Some(next_run((rate != u64::MAX).then_some(rate), picos)) + }); + } +} + +/// The dispatches of one piece: each kernel once, with its threadgroups summed, and their expected +/// run. +#[derive(Default)] +pub(crate) struct Work { + kernels: Vec<(Arc, u64)>, + /// The expected GPU run of its dispatches, in nanoseconds, summed. + pub(crate) run: u64, + /// It holds a dispatch of a kernel whose rate was unknown: that dispatch is its only one, so + /// its run sets the kernel's rate. + alone: bool, + /// Its run tells no rate: it holds an indirect dispatch, whose threadgroups the GPU reads and + /// which counts as one, a dispatch of a kernel of unknown rate beside others, or commands of + /// a blit or render encoder after its first dispatch. + blind: bool, +} + +impl Work { + /// Whether it holds a dispatch. + pub(crate) fn is_empty(&self) -> bool { + self.kernels.is_empty() + } + + /// Whether a dispatch expected to run `run` (None: its kernel's rate unknown) begins a new + /// piece: this one holds a dispatch, and holds one of unknown rate, or has none to give, or + /// would pass the bound with it. + pub(crate) fn full(&self, run: Option) -> bool { + !self.is_empty() + && (self.alone || run.is_none_or(|run| self.run.saturating_add(run) > GROUP_RUN)) + } + + /// The expected run of a dispatch of `kernel` of `groups` threadgroups; None where its rate + /// is unknown. An indirect dispatch (`groups` None) counts as one threadgroup, and as none of + /// a kernel of unknown rate: its run, of threadgroups only the GPU reads, sets no rate. + pub(crate) fn expected(kernel: &Compiled, groups: Option) -> Option { + match groups { + Some(groups) => kernel.rate.expected(groups), + None => Some(kernel.rate.expected(1).unwrap_or(0)), + } + } + + /// Adds a dispatch of `kernel`: `groups` threadgroups, None for an indirect dispatch. + pub(crate) fn add(&mut self, kernel: &Arc, groups: Option) { + let expected = Work::expected(kernel, groups); + self.blind |= groups.is_none() || (expected.is_none() && !self.is_empty()); + self.alone |= expected.is_none(); + self.run = self.run.saturating_add(expected.unwrap_or(0)); + let groups = groups.unwrap_or(1); + match self + .kernels + .iter_mut() + .find(|(kept, _)| Arc::ptr_eq(kept, kernel)) + { + Some((_, summed)) => *summed = summed.saturating_add(groups), + None => self.kernels.push((Arc::clone(kernel), groups)), + } + } + + /// Commands of another encoder follow its dispatches in the piece. + pub(crate) fn blind(&mut self) { + self.blind |= !self.is_empty(); + } + + /// The piece ran `nanos` on the GPU: a kernel alone in it takes its rate from that run, and + /// several each scale theirs by the run against what they expected. + pub(crate) fn ran(&self, nanos: u64) { + if self.blind { + return; + } + let picos = u128::from(nanos) * 1000; + let rate = |kernel: &Compiled| u128::from(kernel.rate.0.load(Relaxed)); + let expected: u128 = (self.kernels.iter()) + .map(|(kernel, groups)| rate(kernel) * u128::from(*groups)) + .sum(); + for (kernel, groups) in &self.kernels { + let picos = match self.kernels.len() { + 1 => picos / u128::from((*groups).max(1)), + _ if expected == 0 => continue, + _ => rate(kernel).saturating_mul(picos) / expected, + }; + kernel + .rate + .ran(u64::try_from(picos).unwrap_or(u64::MAX - 1)); + } + } +} diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 6dc87859f..94ce5bd88 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -66,6 +66,7 @@ use crate::encoder::{ use crate::error::{Error, Gap, IndirectCommandsKind, KernelInputKind, Refusal}; use crate::hazard::Access; use crate::kernel_map::KernelKey; +use crate::piece::Rate; use crate::reaper::{Free, Job}; use crate::ring::CHUNK; use crate::sampler::{canonical, constexpr_notes, hold_constexpr, release_constexpr}; @@ -185,6 +186,9 @@ pub(crate) struct Compiled { /// [`ComputePipelineState::finish_pipeline`] makes, or its creation for a kernel past the /// stage bound; none where its descriptor holds no key of a `VkPipeline`. main: Option, + /// The GPU run of one threadgroup of its dispatches, which bounds the pieces their command + /// buffers go in (`crate::piece`), shared by every state of the content. + pub(crate) rate: Rate, } /// What Metal's compute state answers of a content beside its threads, from its whole module's @@ -1183,6 +1187,7 @@ impl Compiled { notes, answers, main: None, + rate: Rate::default(), } } } diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index cd1eec883..02d71dc97 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -717,7 +717,7 @@ impl CommandBuffer { &self, descriptor: &RenderPassDescriptor, ) -> Result { - let mut building = self.open_encoder()?; + let mut building = self.open_encoder(false, false)?; // SAFETY: the encoder holds `building`, whose device handle keeps the core, until it ends; // nothing uses the borrow after that, and a refused descriptor drops it with no use. let core = unsafe { Uncounted::of(building.device.core()) }; diff --git a/crates/metal2vulkan-runtime/src/submit.rs b/crates/metal2vulkan-runtime/src/submit.rs index 226c415e1..8c9e11837 100644 --- a/crates/metal2vulkan-runtime/src/submit.rs +++ b/crates/metal2vulkan-runtime/src/submit.rs @@ -85,13 +85,15 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, Weak}; /// command buffers in half the time no bound did (probe 06860a3848, job m3-max-44105). pub(crate) const GROUP: usize = 16; -/// The most expected GPU run, in nanoseconds, of the command buffers one group holds, summed, and -/// of a queue's submissions behind its oldest not seen complete ([`room`]): 16 ms, the owner's -/// line for an intolerable wait. Each command buffer's -/// expected run is its queue's (`QueueInner::expected_run`), from the GPU times of the queue's -/// command buffers as they retire. Command buffers each within the driver's job timeout may pass -/// it summed in one job. -pub(crate) const GROUP_RUN: u64 = 16_000_000; +/// The most expected GPU run, in nanoseconds, of the command buffers one group holds, summed, of +/// the dispatches of one piece of a command buffer (`crate::piece`), and of the device's +/// submissions behind its oldest not seen complete ([`room`]): 4 ms. So a command buffer +/// committed while others run waits behind the running submission and about 4 ms more, inside +/// the 16 ms that is the owner's line for an intolerable wait. Each command buffer's expected run +/// is its queue's (`QueueInner::expected_run`), from the GPU times of the queue's command buffers +/// as they retire; a piece's is its dispatches' kernels' rates. Command buffers each within the +/// driver's job timeout may pass it summed in one job. +pub(crate) const GROUP_RUN: u64 = 4_000_000; /// The most command buffers that join one group while none of their queue's retires with its GPU /// times: they join on an expected run no completion has updated, so a program whose command @@ -126,8 +128,8 @@ pub(crate) fn apart(members: u64, run: Option) -> bool { members > 1 && run.is_none_or(|run| run.saturating_mul(members) > GROUP_RUN) } -/// The submissions of a queue not yet seen complete at which its command buffers are held in a -/// group ([`room`]). Three, not two: with two, the GPU idles between a group's end and the next +/// The submissions of the device not yet seen complete at which its command buffers are held in +/// a group or for room ([`room`]). Three, not two: with two, the GPU idles between a group's end and the next /// submission's start whenever the completion that sends the held group comes late. Behind three, /// the frame of five command buffers on the UHD 630 completed in 420-429 us against 895-1137 us, /// and the second of four long command buffers was seen complete 74.7 ms after its commit against @@ -140,13 +142,14 @@ pub(crate) fn apart(members: u64, run: Option) -> bool { /// 78.1-78.2 ms against 42.8-43.2 ms (jobs m3-max-44442 and m3-max-44443). pub(crate) const IN_FLIGHT: usize = 3; -/// Whether a queue whose submissions not seen complete have the expected runs `in_flight`, oldest -/// first (`u64::MAX` for one not known), has room for a group whose expected run is `run`: with -/// fewer than two of them always, so one waits on the GPU behind the one running and long command -/// buffers run back to back; with fewer than [`IN_FLIGHT`] while the runs behind the oldest, the -/// group's with them, stay within [`GROUP_RUN`]. So a queue keeps on the device's one `VkQueue` -/// no more than about that bound behind what runs, and another queue's command buffer committed -/// later waits behind no more of it. +/// Whether a device whose submissions not seen complete have the expected runs `in_flight`, oldest +/// first (`u64::MAX` for one not known), has room for a group or a piece whose expected run is +/// `run`: with fewer than two of them always, so one waits on the GPU behind the one running and +/// long command buffers run back to back; with fewer than [`IN_FLIGHT`] while the runs behind the +/// oldest, the group's with them, stay within [`GROUP_RUN`]. So the device's one `VkQueue` holds +/// no more than about that bound behind what runs, whatever the queues, and a command buffer +/// committed later waits behind no more of it. Which queue takes the room is +/// [`WorkState::has_room`]'s. pub(crate) fn room(in_flight: &VecDeque<(u64, u64)>, run: u64) -> bool { let behind = (in_flight.iter().skip(1)).fold(run, |sum, &(_, run)| sum.saturating_add(run)); in_flight.len() < 2 || (in_flight.len() < IN_FLIGHT && behind <= GROUP_RUN) @@ -217,6 +220,11 @@ pub(crate) struct WorkState { next_place: u64, /// The progress value of the last submission. progress: u64, + /// The progress values of the queues' submissions not yet seen complete, in order, each with + /// its expected run ([`room`]). + in_flight: VecDeque<(u64, u64)>, + /// The submissions of the queues' work so far: each FIFO's turn is the count at its last. + turns: u64, /// The command buffers whose last segment a submission not seen complete when the submit /// thread last looked carried, in the order submitted: each one's place in the commit order /// and that submission's progress value ([`Work::settled`]). At most the command buffers @@ -265,8 +273,14 @@ struct Fifo { /// The group staged and not yet submitted. group: Option, /// The progress values of the queue's submissions not yet seen complete, in order, each with - /// its expected run ([`room`]). + /// its expected run. in_flight: VecDeque<(u64, u64)>, + /// When it last submitted ([`WorkState::turns`]), 0 before: the device's room goes first to + /// the queue that waited longest ([`WorkState::has_room`]). + turn: u64, + /// Its head is held behind every piece of a cut command buffer of another queue committed + /// before it, with which it shares a resource ([`WorkState::block_shared`]). + blocked: bool, /// A host wait is to come for the command buffer at this place: a group from it or before /// goes at once. send_through: u64, @@ -564,6 +578,8 @@ impl Work { next_seq: 0, next_place: 0, progress: 0, + in_flight: VecDeque::new(), + turns: 0, carried: VecDeque::new(), uploaded: 0, upload: None, @@ -1502,6 +1518,8 @@ impl WorkState { entries: VecDeque::new(), group: None, in_flight: VecDeque::new(), + turn: 0, + blocked: false, send_through: 0, behind: 0, held_since: None, @@ -1583,7 +1601,10 @@ impl WorkState { let mut held: Option<(u64, usize)> = None; let mut best: Option<(usize, bool, u64)> = None; for (index, fifo) in self.fifos.iter().enumerate() { - let waits = self.waits_for_room(fifo); + let waits = self.waits_for_room(index); + if fifo.blocked && !waits { + continue; + } if let (false, Some(at)) = (waits, fifo.entries.front().and_then(|head| head.held)) { held = held.filter(|&(first, _)| first < at).or(Some((at, index))); continue; @@ -1616,39 +1637,120 @@ impl WorkState { (held.map(|(_, index)| (index, false))).or(best.map(|(index, waits, _)| (index, waits))) } - /// Whether the head of `fifo` waits in its list, not staged, for room: committed, with - /// commands or a copy-in for the GPU, its first segment not yet staged, behind a group held - /// that does not go ([`Fifo::goes`]) nor conflict with it, and that does not take it - /// ([`Batch::takes`]) or would go at its signal. With no group held, one that signals an event - /// in any segment, which would send its group at once, waits where its queue has no room for - /// it. The command buffers behind it wait with it. - fn waits_for_room(&self, fifo: &Fifo) -> bool { + /// Whether the head of the FIFO at `index` waits in its list, not staged, for room: committed, + /// with commands or a copy-in for the GPU, its first segment not yet staged, behind a group + /// held that does not go ([`goes`](Self::goes)) nor conflict with it, and that does not take + /// it ([`Batch::takes`]) or would go at its signal. With no group held, one that signals an + /// event in any segment, which would send its group at once, waits where its queue has no room + /// for it. A cut command buffer's every piece waits for room, as no group takes it. The command + /// buffers behind it wait with it. + fn waits_for_room(&self, index: usize) -> bool { + let fifo = &self.fifos[index]; let Some(head) = fifo.entries.front() else { return false; }; let (Some(pending), None) = (&head.pending, head.error) else { return false; }; + let cut = pending.gpu.cut; let empty = pending.gpu.is_empty() && !self.changes.captured.waits_for(pending.seq); - if pending.next != 0 || empty { + if (pending.next != 0 && !cut) || empty { return false; } let segments = &pending.gpu.segments; - let signals = (segments.iter()).any(|segment| !segment.signals.is_empty()); - let (segment, run) = (&segments[0], fifo.queue.expected_run()); + let signals = cut || (segments.iter()).any(|segment| !segment.signals.is_empty()); + let (segment, run) = (&segments[pending.next], fifo.queue.expected_run()); match &fifo.group { Some(group) => { !group.leans.conflicts(&segment.overs) && (signals || !group.takes(run, fifo.queue.retired())) - && !fifo.goes(self.stop) + && !self.goes(index) } None => { - let room = room(&fifo.in_flight, run.unwrap_or(u64::MAX)); - signals && !(self.stop || fifo.send_through >= head.place || room) + let run = match cut { + true => segment.work.run, + false => run.unwrap_or(u64::MAX), + }; + let through = fifo.send_through >= head.place && !cut; + signals && !(self.stop || through || self.has_room(index, run)) } } } + /// Whether the FIFO at `index` has room on the device for a submission expected to run `run` + /// ([`room`]), no FIFO that last submitted before it wanting room that fits + /// ([`wants`](Self::wants)): so the queue that waited longest goes first, and a command + /// buffer passed by another queue's goes before that queue's next. + fn has_room(&self, index: usize, run: u64) -> bool { + let turn = self.fifos[index].turn; + room(&self.in_flight, run) + && !(self.fifos.iter().enumerate()).any(|(other, fifo)| { + other != index + && fifo.turn < turn + && (self.wants(fifo)).is_some_and(|run| room(&self.in_flight, run)) + }) + } + + /// The expected run of what `fifo` would submit with room: its group held, else its head's + /// next piece or the command buffer, where it is committed, with something for the GPU, its + /// next segment's waits met, and not held behind a cut command buffer it shares with. + fn wants(&self, fifo: &Fifo) -> Option { + if let Some(group) = &fifo.group { + return Some(group.run); + } + let head = fifo.entries.front().filter(|_| !fifo.blocked)?; + let pending = head.pending.as_ref().filter(|_| head.error.is_none())?; + let empty = pending.gpu.is_empty() && !self.changes.captured.waits_for(pending.seq); + let segment = &pending.gpu.segments[pending.next]; + if empty || !ready(segment) { + return None; + } + Some(match pending.gpu.cut { + true => segment.work.run, + false => fifo.queue.expected_run().unwrap_or(u64::MAX), + }) + } + + /// Whether the FIFO at `index` holds a group that goes now: at teardown, where a host wait is + /// to come for one of its command buffers or one behind it, or with room + /// ([`has_room`](Self::has_room)). A round of the completion thread sends none: it holds what + /// it saw complete when it began, so held work waits for the round to end. + fn goes(&self, index: usize) -> bool { + let fifo = &self.fifos[index]; + fifo.group.as_ref().is_some_and(|group| { + self.stop || fifo.send_through >= group.first || self.has_room(index, group.run) + }) + } + + /// Marks each FIFO whose head, committed after a cut command buffer of another queue, the head + /// of its own with pieces not yet staged, shares a resource with it (`Gpu::shares`): held until that + /// command buffer's every piece is staged, counted once a head + /// (`Metrics::shared_holds`). + fn block_shared(&mut self, counters: &Counters) { + let cuts: Vec<(usize, u64)> = (self.fifos.iter().enumerate()) + .filter_map(|(index, fifo)| { + let pending = fifo.head()?; + pending.gpu.cut.then_some((index, pending.seq)) + }) + .collect(); + for index in 0..self.fifos.len() { + let shares = (self.fifos[index].head()).is_some_and(|pending| { + pending.next == 0 + && cuts.iter().any(|&(other, seq)| { + let cut = self.fifos[other].head().map(|cut| &cut.gpu); + other != index + && seq < pending.seq + && cut.is_some_and(|cut| pending.gpu.shares(cut)) + }) + }); + let fifo = &mut self.fifos[index]; + if shares && !fifo.blocked { + counters.count(Metric::SharedHolds); + } + fifo.blocked = shares; + } + } + /// The first command buffer not yet scheduled of the FIFO at `index`, whose head waits for /// room, every wait of its met: scheduled now, as it would be in a group held, its scheduled /// handlers going to `joined`, and counted. One that presents a drawable (scheduled once @@ -1689,7 +1791,10 @@ impl WorkState { return None; } let before = head.held.unwrap_or(u64::MAX); - let updates = |pending: &Pending| pending.gpu.fences.updates_for(waiter); + // A cut command buffer's pieces go at the room's pace, never sent through: a waiter + // committed after it is held behind them as one that shares with it (`block_shared`). + let updates = + |pending: &Pending| !pending.gpu.cut && pending.gpu.fences.updates_for(waiter); let mut others = (self.fifos.iter().enumerate()).filter(|&(other, _)| other != index); others.find_map(|(other, fifo)| { let held = (fifo.entries.iter()) @@ -1711,6 +1816,9 @@ impl WorkState { while (self.carried.front()).is_some_and(|&(_, value)| value <= completed) { self.carried.pop_front(); } + while (self.in_flight.front()).is_some_and(|&(value, _)| value <= completed) { + self.in_flight.pop_front(); + } self.fifos.retain_mut(|fifo| { while (fifo.in_flight.front()).is_some_and(|&(value, _)| value <= completed) { fifo.in_flight.pop_front(); @@ -1732,6 +1840,7 @@ impl WorkState { joined: &mut Vec, ended: &mut Vec, ) -> Step { + self.block_shared(counters); let Some((index, waits)) = self.next_ready() else { return Step::Idle; }; @@ -1739,7 +1848,6 @@ impl WorkState { self.hold(index, now, counters, joined); return Step::Staged; } - let stop = self.stop; let fifo = &mut self.fifos[index]; let Some(entry) = fifo.entries.front_mut() else { return Step::Idle; @@ -1785,6 +1893,7 @@ impl WorkState { } return Step::Staged; } + let cut = pending.gpu.cut; let segment = &pending.gpu.segments[pending.next]; // A segment that leans on the leading copy for a buffer an earlier segment of the group // wrote leads its group, so its copy follows the write (`crate::over`); so does one that @@ -1806,7 +1915,8 @@ impl WorkState { let leads = pending.next == 0; if let (true, Some(group)) = (leads, &fifo.group) { let after = group.leads.last().copied().unwrap_or(0); - if !group.takes(run, retired) + if cut + || !group.takes(run, retired) || (!group.wrote.is_empty() && (self.changes.captured).names_written(after, pending.seq, &group.wrote)) { @@ -1836,8 +1946,14 @@ impl WorkState { wrote: Vec::new(), reached: Vec::new(), }); + // A cut command buffer's piece goes alone, its run its dispatches' (`crate::piece`). + let piece = match (cut, leads) { + (true, _) => segment.work.run, + (false, true) => run.unwrap_or(u64::MAX), + (false, false) => 0, + }; + group.run = group.run.saturating_add(piece); if leads { - group.run = group.run.saturating_add(run.unwrap_or(u64::MAX)); group.starts.push(group.segments.len()); group.leads.push(pending.seq); if group.seen != retired { @@ -1876,10 +1992,25 @@ impl WorkState { // once the command buffer is scheduled. let signals = !staged.signals.is_empty(); group.segments.push(staged); + pending.gpu.segments[pending.next].sent = true; pending.next += 1; + // A cut command buffer whose later pieces wait only for room is scheduled with its first, + // as one held for room is ([`hold`](Self::hold)). + if cut && leads && entry.held.is_none() && !pending.gpu.presents() { + let later = &pending.gpu.segments[pending.next..]; + if later.iter().all(|segment| segment.waits.is_empty()) { + let scheduled = std::mem::take(&mut pending.handlers.scheduled); + entry.cb.scheduled(now, !scheduled.is_empty()); + if !scheduled.is_empty() { + joined.push((Arc::clone(&entry.cb), scheduled)); + } + self.holds += 1; + entry.held = Some(self.holds); + } + } if pending.next < pending.gpu.segments.len() { group.partial = true; - return if signals { + return if signals || cut { Step::Goes(index) } else { Step::Staged @@ -1907,7 +2038,7 @@ impl WorkState { // A command buffer held for room behind it joins it or, not taken, sends it first: with // room the two would have been staged together. let held_behind = (fifo.entries.front()).is_some_and(|entry| entry.held.is_some()); - match signals || (fifo.goes(stop) && !held_behind) { + match signals || (self.goes(index) && !held_behind) { true => Step::Goes(index), false => Step::Staged, } @@ -1922,14 +2053,20 @@ impl WorkState { core: &Core, released: &AtomicU64, ) -> Option<(u64, Vec, Batch)> { + // It goes before the pieces not yet submitted of another queue's cut command buffer. + let passes = (self.fifos.iter().enumerate()) + .any(|(other, fifo)| other != index && fifo.head().is_some_and(|head| head.gpu.cut)); let fifo = &mut self.fifos[index]; let mut batch = fifo.group.take()?; + if passes { + core.counters.count(Metric::PiecesPassed); + } // The bound again, with the expected run as it now stands: a completion since a join may // have raised it. batch.apart = apart(batch.starts.len() as u64, fifo.queue.expected_run()); // A group held that goes with room goes as a completion left it, whatever else would have // sent it now. - batch.held &= room(&fifo.in_flight, batch.run); + batch.held &= room(&self.in_flight, batch.run); if batch.held { core.counters.held_start(); } @@ -1979,6 +2116,9 @@ impl WorkState { self.progress += 1; let value = self.progress; fifo.in_flight.push_back((value, batch.run)); + self.in_flight.push_back((value, batch.run)); + self.turns += 1; + fifo.turn = self.turns; if batch.partial { if let Some(Entry { pending: Some(pending), @@ -2000,9 +2140,12 @@ impl WorkState { Some((value, uploads, batch)) } - /// The first FIFO whose group goes at the end of a pass ([`Fifo::goes`]). + /// The FIFO whose group goes at the end of a pass ([`goes`](Self::goes)): of those that go, + /// the one that last submitted first. fn unheld(&self) -> Option { - (self.fifos.iter()).position(|fifo| fifo.goes(self.stop)) + (0..self.fifos.len()) + .filter(|&index| self.goes(index)) + .min_by_key(|&index| self.fifos[index].turn) } } @@ -2034,16 +2177,6 @@ impl Fifo { (self.entries.front()).and_then(|entry| entry.pending.as_ref()) } - /// Whether it holds a group that goes now: at teardown (`stop`), where a host wait is to come - /// for one of its command buffers or one behind it, or with room ([`room`]). A round of the - /// completion thread sends none: it holds what it saw complete when it began, so held work - /// waits for the round to end. - fn goes(&self, stop: bool) -> bool { - self.group.as_ref().is_some_and(|group| { - stop || self.send_through >= group.first || room(&self.in_flight, group.run) - }) - } - /// Ends `entry` with `error` (its own, where it has one): behind the group held, which it /// joins to retire with; else once the queue's submissions in flight and the command buffers /// it ended before complete, at once where none is. One not committed ends at its commit. @@ -2281,9 +2414,9 @@ fn pass<'a>(core: &'a Core, mut state: MutexGuard<'a, WorkState>) -> MutexGuard< } } let holds = |fifo: &Fifo| { - fifo.entries - .front() - .is_some_and(|entry| entry.held.is_some()) + fifo.entries.front().is_some_and(|entry| { + entry.held.is_some() || entry.pending.as_ref().is_some_and(|head| head.gpu.cut) + }) }; if (state.fifos.iter()).all(|fifo| fifo.group.is_none() && !holds(fifo)) { work.keeping.store(false, Ordering::SeqCst);