diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 30960124b5cfb..0c85e94fd77cd 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -424,6 +424,46 @@ enum PublicationError { Uncertain(Error), } +/// Why a publication pass stopped at a ready job without publishing it (`Stats::hold_causes`). +/// +/// A drain cause means the job waits for an empty engine; the others wait behind in-flight +/// work for headroom or ordering. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum HoldCause { + /// The job's VM failed, or a flight is doomed or suspect in a recovery. + DrainFailed, + /// A cold `InitBM` render is in flight. + DrainInitbm, + /// Compute behind any flight of another VM, render behind compute of another VM, or an + /// SCS compute conflict. + DrainCross, + /// No warm PB/UMA allocator slot of the VM can take the render behind active flights. + DrainPb, + /// The TA wave window is full. + TaWave, + /// Flight, render pass or compute unit headroom. + Slot, + /// The job's dependency check failed: it fails once it reaches publication. + /// (`Engine::pick()` skips jobs still waiting for a dependency.) + Dependency, + /// Any other admission refusal behind in-flight work. + Other, +} + +impl HoldCause { + pub(crate) const COUNT: usize = 8; + pub(crate) const NAMES: [&'static str; Self::COUNT] = [ + "drain_failed", + "drain_initbm", + "drain_cross", + "drain_pb", + "ta_wave", + "slot", + "dependency", + "other", + ]; +} + /// Engine statistics, printed by `aurora-g16/stats`. #[derive(Default, Zeroable)] pub(crate) struct Stats { @@ -474,6 +514,8 @@ pub(crate) struct Stats { /// Why ready jobs stayed unpublished: both flights published, a channel record unconsumed, /// no free slot. pub(crate) hold: [u64; 3], + /// `hold[0]` split by [`HoldCause`]. + pub(crate) hold_causes: [u64; HoldCause::COUNT], /// Compute commands published behind in-flight ones. pub(crate) behind: u64, /// Most flights in flight at once. @@ -610,6 +652,13 @@ pub(crate) struct Engine { pub(crate) ta_wave_wait: bool, /// An EP 0x20 event arrived with a flight still settling its final receipt: repoll sooner. pub(crate) short_repoll: bool, + /// An idle poll pass inside the housekeeping cadence skipped housekeeping: queue a backup + /// poll so it runs once the cadence elapses. + pub(crate) housekeeping_owed: bool, + /// A ready job is held behind flights that all belong to its own VM, for any cause but a + /// failure, a cross-VM overlap or a failed dependency: one of those flights retiring is + /// what releases it, so repoll soon instead of after `resnap_us`. + pub(crate) held_wait: bool, /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing /// (0 when no batch is held). pub(crate) coalesce_deadline_ns: u64, @@ -657,6 +706,8 @@ impl Engine { slot_wait: false, ta_wave_wait: false, short_repoll: false, + housekeeping_owed: false, + held_wait: false, coalesce_deadline_ns: 0, progress_flight: [0; 3], progress: [None; 4], @@ -1006,6 +1057,7 @@ impl Firmware { self.engine.chan_wait = false; self.engine.slot_wait = false; self.engine.ta_wave_wait = false; + self.engine.held_wait = false; self.engine.coalesce_deadline_ns = 0; while self.recovery.failed().is_none() && !self.engine.frozen @@ -1028,7 +1080,7 @@ impl Firmware { && !self.can_queue_behind_with_ta(&job, &mut ta_pending) { if self.needs_engine_drain(&job) { - self.engine.stats.hold[0] += 1; + self.note_hold(&job, true, 0); break; } let ta_val = *ta_pending.get_or_insert_with(|| self.ta_pending_passes()); @@ -1115,7 +1167,7 @@ impl Firmware { .check_command_dependencies(cand.progress.sent()) .is_ok() }); - self.engine.stats.hold[0] += 1; + self.note_hold(&job, false, ta_val); break; } } @@ -1350,23 +1402,83 @@ impl Firmware { || f.recovery_suspect || f.initbm || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) - || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) + || ((is_compute || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) - || (is_render - && !job - .resources - .pb_slot_mask() - .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(mask, home, blocks)| { - self.pools.can_pipeline_in_mask_blocks_mode( - &job.vm, - mask, - home, - blocks, - job.resources.render_scs(), - ) - })) + || (is_render && !self.render_can_pipeline(job)) + } + + /// Whether `job`'s render can reuse a warm PB/UMA allocator slot of its VM behind active + /// flights, without the drain that a fresh `InitBM` epoch needs. + fn render_can_pipeline(&self, job: &Arc) -> bool { + job.resources + .pb_slot_mask() + .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(mask, home, blocks)| { + self.pools.can_pipeline_in_mask_blocks_mode( + &job.vm, + mask, + home, + blocks, + job.resources.render_scs(), + ) + }) + } + + /// Why a publication pass stopped at `job`: `drain` when [`Self::needs_engine_drain`] + /// held it, otherwise the first refusal of [`Self::can_queue_behind_with_ta`] that + /// applies, with `ta_pending` from that check. Of the drain causes, a failure, an `InitBM` + /// flight and the PB check are tested directly; what remains of `needs_engine_drain()` is a + /// cross-VM or SCS overlap. + fn hold_cause(&self, job: &Arc, drain: bool, ta_pending: usize) -> HoldCause { + let render = command(job, job.progress.sent()); + if drain { + if job.vm.status.get() != 0 + || self + .engine + .flights + .iter() + .any(|f| f.doomed || f.recovery_suspect) + { + HoldCause::DrainFailed + } else if self.engine.flights.iter().any(|f| f.initbm) { + HoldCause::DrainInitbm + } else if matches!(render, Some(Command::Render(_))) && !self.render_can_pipeline(job) { + HoldCause::DrainPb + } else { + HoldCause::DrainCross + } + } else if job.check_command_dependencies(job.progress.sent()).is_err() { + HoldCause::Dependency + } else if matches!(render, Some(Command::Render(r)) + if ta_pending >= self.ta_wave_cap_for(r.is_heavy_ta())) + { + HoldCause::TaWave + } else if self.blocked_on_slot_headroom(job) { + HoldCause::Slot + } else { + HoldCause::Other + } + } + + /// Counts a publication pass that stopped at the ready `job` behind in-flight work, and + /// marks it [`Engine::held_wait`] when only its own VM's flights hold it. + fn note_hold(&mut self, job: &Arc, drain: bool, ta_pending: usize) { + let cause = self.hold_cause(job, drain, ta_pending); + let s = &mut self.engine.stats; + s.hold[0] += 1; + s.hold_causes[cause as usize] += 1; + if !matches!( + cause, + HoldCause::DrainFailed | HoldCause::DrainCross | HoldCause::Dependency + ) && self + .engine + .flights + .iter() + .all(|f| Arc::ptr_eq(&f.job.vm, &job.vm)) + { + self.engine.held_wait = true; + } } /// Whether `job` is ready to run without an engine drain but currently blocked solely on @@ -1478,8 +1590,8 @@ impl Firmware { /// Whether `job`'s next command may be published behind the flights in flight: /// - /// - Compute queues behind healthy non-InitBM compute flights of any VM or same-VM - /// render flights (up to [`params::compute_flights`] active computes), each in its own + /// - Compute queues behind healthy non-InitBM compute and render flights of its own VM + /// (up to [`params::compute_flights`] active computes), each in its own /// `ComputeSlot` and hardware UMA slot (`COMPUTE_UMA_SLOT + index`), unless `query_access` /// is set and a same-queue predecessor in its compute or render barrier prefix has /// CPU-published timestamp outputs that have not retired yet @@ -1495,6 +1607,10 @@ impl Firmware { /// dispatch from one client cannot starve another client's fragment shading into a /// firmware DM1 timeout. Cold InitBM priming renders and every failure or recovery path /// still drain the engine first. + /// - Compute never runs beside compute of another VM, on either pipe: with several clients + /// dispatching barrier-free compute, the overlapped dispatches occasionally lost their + /// results without a fault (loads read zero, readbacks came back empty or partial), + /// which one client alone never does. G15 runs one VM at a time for the same reason. fn can_queue_behind(&self, job: &Arc) -> bool { let mut ta_pending = None; self.can_queue_behind_with_ta(job, &mut ta_pending) @@ -1561,17 +1677,14 @@ impl Firmware { }) }) })); - let cross_vm_render = e - .flights - .iter() - .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let cross_vm = e.flights.iter().any(|f| !Arc::ptr_eq(&f.job.vm, &job.vm)); let scs = job.resources.compute_scs() || c.is_rt(); let scs_conflict = e .flights .iter() .any(|f| scs_compute_conflict(f, &job.vm, scs)); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); - !cross_vm_render + !cross_vm && !scs_conflict && !waits_for_timestamps && compute_count < params::compute_flights() @@ -1595,19 +1708,7 @@ impl Firmware { && !self.slots.render_exhausted() && !self.pools.exhausted() && super::recovery::logic::next_ordinal(e.draw).is_some() - && job - .resources - .pb_slot_mask() - .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(mask, home, blocks)| { - self.pools.can_pipeline_in_mask_blocks_mode( - &job.vm, - mask, - home, - blocks, - job.resources.render_scs(), - ) - }) + && self.render_can_pipeline(job) && job .resources .render_passes() @@ -1628,6 +1729,7 @@ impl Firmware { || self.engine.chan_wait || self.engine.slot_wait || self.engine.ta_wave_wait + || self.engine.held_wait || self .engine .flights diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 3d9cf3793dc03..7f96e6cf1f02d 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -831,8 +831,9 @@ pub(crate) mod sizes { pub(crate) const PB_BLOCKS: u32 = 2048; pub(crate) const PB_LIST_RECORDS: u32 = 4096; pub(crate) const PB_GROW_STEP: u32 = 10; - /// Published prefixes at most. Warm compute and render commands may pipeline across VMs - /// on disjoint hardware UMA slots while cold `InitBM` renders and recovery paths drain. + /// Published prefixes at most. Warm render commands may pipeline across VMs on disjoint + /// hardware UMA slots, compute only behind its own VM's work, while cold `InitBM` renders + /// and recovery paths drain. pub(crate) const FLIGHTS: usize = 32; /// Retained compute units per VM at most; each unit owns its own hardware UMA slot /// (`COMPUTE_UMA_SLOT + index`, fitting in `1..RENDER_UMA_SLOT = 33`). A unit is reused diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e11cfd22168f2..43647519f2202 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -100,6 +100,18 @@ impl Shared { self.mod_poll(kernel::time::msecs_to_jiffies((delay_ns / 1_000_000) as u32).max(1)); } + /// Queues the backup poll for idle housekeeping that a pass skipped inside its cadence, at + /// the end of that cadence. It may replace a later idle power poll: that pass runs the + /// housekeeping, including `service_power()`, and arms the power poll again. + fn queue_owed_housekeeping(self: &Arc, firmware: &Firmware) { + if !firmware.engine.housekeeping_owed || firmware.recovery.failed().is_some() { + return; + } + let elapsed = now_ns().wrapping_sub(firmware.last_housekeeping_ns); + let ms = HOUSEKEEPING_NS.saturating_sub(elapsed).div_ceil(1_000_000) as u32; + self.mod_poll(kernel::time::msecs_to_jiffies(ms).max(1)); + } + /// One poll pass (the poll work item). pub(crate) fn run_poll(self: Arc) { // The domain may be off. The sleep's end queues a pass. @@ -158,6 +170,7 @@ impl Shared { // floor hold is still pending so both expire cleanly to idle power. Ok(false) => { self.arm_idle_power_poll(firmware); + self.queue_owed_housekeeping(firmware); if firmware.recovery.failed().is_some() { self.cancel_resnap(); } else { @@ -316,13 +329,21 @@ impl Shared { if !firmware.engine.flights.is_empty() || firmware.engine.chan_wait { // If an EP 0x20 event retired an older flight while later flights remain active, // or arrived before the oldest receipt became visible, arm a short repoll so - // trailing completions never fall back to `resnap_us`. + // trailing completions never fall back to `resnap_us`. A ready job this + // publication left waiting on TA wave or slot headroom repolls as soon as + // `poll_step()` would rearm it, not a full `resnap_us` later. if let Some(us) = coalesce_us { self.rearm_after(us.min(self.rearm_us(false))); } else { + let paced = !firmware.engine.frozen + && !firmware.engine.pending.is_empty() + && (firmware.engine.slot_wait + || firmware.engine.ta_wave_wait + || firmware.engine.held_wait); self.rearm( firmware.engine.chan_wait || restored_event + || paced || (was_evented && retired_any && !firmware.engine.flights.is_empty()), ); } @@ -664,14 +685,29 @@ impl Firmware { // failure of the next prefix. Drain the receive rings before deciding, published or // not, so the error count is current and idle log/trace/stats traffic is consumed. With // prefixes published the retirement loop below drains first. + // + // Inside the housekeeping cadence, with no recovery pending, an idle pass drains only + // the event and statistics rings, which carry completion and recovery notifications. + // The session, object, power and auxiliary ring checks then wait for the cadence, so + // back-to-back shallow submissions do not repeat them, under the device lock, between + // one completion and the next SUBMIT. `run_poll()` queues a backup poll for them. if !had_flights { - self.session.check()?; - self.objects.health()?; - self.service_power()?; - self.last_housekeeping_ns = now; - self.last_aux_drain_ns = now; - ran_housekeeping = true; - self.drain_rings()?; + let full = housekeeping_due || self.recovery.receipt_fault || { + self.drain_events_and_stats()?; + self.recovery_pending()? + }; + if full { + self.session.check()?; + self.objects.health()?; + self.service_power()?; + self.last_housekeeping_ns = now; + self.last_aux_drain_ns = now; + ran_housekeeping = true; + self.engine.housekeeping_owed = false; + self.drain_rings()?; + } else { + self.engine.housekeeping_owed = true; + } self.reclaim_closed_vm_slots(); if self.recovery_idle()? && self.engine.pending.is_empty() { let _ = self.slots.take_scrub_woke(); @@ -743,7 +779,8 @@ impl Firmware { published?; // A TA-only (0x70) EP 0x20 interrupt while FS is still running does not signal flight // retirement: avoid burning the receipt-tail spin or arming a short repoll storm for it, - // unless a render queue is actively waiting on TA wave headroom (`ta_wave_wait`). + // unless a render queue is actively waiting on TA wave headroom (`ta_wave_wait`) or a + // ready job waits behind its own VM's flights (`held_wait`). let non_terminal_only = !retired_any && term_before.is_some() && self.events.stage_events != stage_before @@ -751,7 +788,8 @@ impl Firmware { && !self.oldest_stamp_reached() && !self.recovery.receipt_fault && !recovery_pending - && !self.engine.ta_wave_wait; + && !self.engine.ta_wave_wait + && !self.engine.held_wait; // After an EP 0x20 event, retry up to `EVENT_RETIRE_POLLS` times (outside the device // lock) only while no flight has retired yet and flights remain in flight. Once any // flight retires, stop spinning so deeper queues do not burn tail waits per interrupt. @@ -777,13 +815,16 @@ impl Firmware { } // If a terminal EP 0x20 event arrived with flights outstanding and nothing retired within // the trailing polls, or a ready same-VM pending job is blocked on slot/flight/work-ring - // or TA-wave headroom, repoll at `repoll_us` instead of sleeping `resnap_us`. + // or TA-wave headroom, or held behind its own VM's flights, repoll at `repoll_us` + // instead of sleeping `resnap_us`. self.engine.short_repoll = !self.engine.flights.is_empty() && !self.engine.frozen && !non_terminal_only && ((evented && had_flights && !retired_any) || (!self.engine.pending.is_empty() - && (self.engine.slot_wait || self.engine.ta_wave_wait))); + && (self.engine.slot_wait + || self.engine.ta_wave_wait + || self.engine.held_wait))); Ok(!self.engine.flights.is_empty() || self.engine.chan_wait || self.recovery.needs_repoll() @@ -811,6 +852,7 @@ impl Firmware { self.last_aux_drain_ns = now; } self.last_housekeeping_ns = now; + self.engine.housekeeping_owed = false; self.reclaim_closed_vm_slots(); if !self.engine.flights.is_empty() || recovery_pending { self.check_hangs(done)?; @@ -2226,6 +2268,11 @@ impl Firmware { s.hold[1], s.hold[2] )?; + write!(f, "hold_causes:")?; + for (name, n) in super::engine::HoldCause::NAMES.iter().zip(s.hold_causes) { + write!(f, " {} {}", name, n)?; + } + writeln!(f)?; } let p = &self.engine.prof; writeln!( diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index df5d84c420362..4634f0cc2bd0e 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -163,6 +163,8 @@ def item(declaration, text=source): slot_wait: bool, ta_wave_wait: bool, short_repoll: bool, + housekeeping_owed: bool, + held_wait: bool, coalesce_deadline_ns: u64, frozen: bool, stats: Stats, @@ -327,12 +329,14 @@ def item(declaration, text=source): ta_pending: usize, ta_wave_cap: usize, coalesce_us: Option, + publish_waits: Option<(bool, bool, bool)>, retire_calls: u32, publish_full_calls: u32, publish_checked_calls: u32, housekeeping_calls: u32, aux_drain_calls: u32, power_calls: u32, + hot_drain_calls: u32, } impl Firmware { @@ -363,6 +367,8 @@ def item(declaration, text=source): slot_wait: false, ta_wave_wait: false, short_repoll: false, + housekeeping_owed: false, + held_wait: false, coalesce_deadline_ns: 0, frozen: false, stats: Stats::default(), @@ -383,12 +389,14 @@ def item(declaration, text=source): ta_pending: 0, ta_wave_cap: hw::sizes::TA_WAVE_PASSES, coalesce_us: None, + publish_waits: None, retire_calls: 0, publish_full_calls: 0, publish_checked_calls: 0, housekeeping_calls: 0, aux_drain_calls: 0, power_calls: 0, + hot_drain_calls: 0, } } @@ -409,6 +417,10 @@ def item(declaration, text=source): fn drain_rings(&mut self) -> Result { Ok(()) } + fn drain_events_and_stats(&mut self) -> Result { + self.hot_drain_calls += 1; + Ok(()) + } fn drain_auxiliary_rings(&mut self) -> Result { self.aux_drain_calls += 1; Ok(()) @@ -445,6 +457,11 @@ def item(declaration, text=source): } fn publish_checked(&mut self, _done: &mut Completions) -> Result { self.engine.coalesce_deadline_ns = 0; + if let Some((slot_wait, ta_wave_wait, held_wait)) = self.publish_waits { + self.engine.slot_wait = slot_wait; + self.engine.ta_wave_wait = ta_wave_wait; + self.engine.held_wait = held_wait; + } self.publish_checked_calls += 1; Ok(()) } @@ -465,6 +482,52 @@ def item(declaration, text=source): __OLDEST_STAMP_REACHED__ } +#[test] +fn idle_poll_step_runs_full_housekeeping_only_on_its_cadence() { + let mut fw = Firmware::new(); + let (mut retry_tail, mut hk_deferred, mut done) = (false, false, vec![]); + let mut idle_pass = |fw: &mut Firmware, now: u64| { + CLOCK.with(|c| c.set(now)); + fw.poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap() + }; + // Due: the full idle housekeeping runs and owes nothing. + assert!(!idle_pass(&mut fw, 2_000_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (1, 0)); + assert_eq!(fw.last_housekeeping_ns, 2_000_000); + assert!(!fw.engine.housekeeping_owed); + // Inside the cadence: only the event and statistics rings drain; the rest is owed. + assert!(!idle_pass(&mut fw, 2_300_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (1, 1)); + assert_eq!(fw.last_housekeeping_ns, 2_000_000); + assert!(fw.engine.housekeeping_owed); + // A recovery found by that drain runs the full pass inside the cadence. + fw.recovery.pending = true; + assert!(idle_pass(&mut fw, 2_400_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (2, 2)); + assert_eq!(fw.last_housekeeping_ns, 2_400_000); + assert!(!fw.engine.housekeeping_owed); + fw.recovery.pending = false; + // So does a receipt fault, without a hot drain first. + fw.recovery.receipt_fault = true; + assert!(!idle_pass(&mut fw, 2_500_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (3, 2)); + fw.recovery.receipt_fault = false; + assert!(!idle_pass(&mut fw, 2_600_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (3, 3)); + assert!(fw.engine.housekeeping_owed); + // Once the cadence elapses the owed housekeeping runs. + assert!(!idle_pass(&mut fw, 3_500_000)); + assert_eq!((fw.power_calls, fw.hot_drain_calls), (4, 3)); + assert!(!fw.engine.housekeeping_owed); + // Periodic housekeeping also settles what an idle pass owed. + assert!(!idle_pass(&mut fw, 3_600_000)); + assert!(fw.engine.housekeeping_owed); + CLOCK.with(|c| c.set(4_600_000)); + fw.run_housekeeping(&mut done).unwrap(); + assert!(!fw.engine.housekeeping_owed); +} + #[test] fn idle_poll_step_reclaims_closed_vm_slots_and_rearms_while_remaining() { CLOCK.with(|c| c.set(1_000_000)); @@ -984,6 +1047,49 @@ def item(declaration, text=source): assert!(!fw.engine.short_repoll); } +#[test] +fn held_wait_spins_stage_events_and_repolls_soon_until_a_retirement() { + CLOCK.with(|c| c.set(100_000)); + let mut fw = Firmware::new(); + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 2, + target: 0, + fs_target: 0x200, + }); + fw.engine.fs_target = 0x200; + fw.engine.pending.push(Arc::new(Job { id: 2 })); + fw.drain_stage_delta = 1; + let (mut retry_tail, mut deferred, mut done) = (false, false, vec![]); + // Nothing held: a stage-only event is non-terminal, with no tail spin and no short repoll. + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(!retry_tail); + assert!(!fw.engine.short_repoll); + // A ready job held behind its own VM's flights spins the receipt tail on the same event... + fw.engine.held_wait = true; + assert!(fw + .poll_step(true, EVENT_RETIRE_POLLS, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(retry_tail); + // ...and a timer pass repolls at repoll_us while the hold lasts, without publishing. + retry_tail = false; + fw.drain_stage_delta = 0; + assert!(fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap()); + assert!(fw.engine.short_repoll); + assert_eq!(fw.publish_checked_calls, 0); + // The retirement that can release it reaches publish_checked(). + fw.retire_on_call = true; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut deferred, &mut done) + .unwrap(); + assert_eq!(fw.publish_checked_calls, 1); +} + #[test] fn ta_only_irq_wakes_ta_wave_wait_with_hysteresis_and_short_repoll() { CLOCK.with(|c| c.set(100_000)); @@ -1055,6 +1161,43 @@ def item(declaration, text=source): assert!(!fw.engine.short_repoll); } +#[test] +fn submit_locked_repolls_soon_when_its_publication_leaves_a_paced_job() { + // publish_checked() leaves a ready job on TA wave or slot headroom: SUBMIT arms the same + // short repoll poll_step() arms for it, unless the engine is frozen. + CLOCK.with(|c| c.set(100_000)); + for (slot_wait, ta_wave_wait, held_wait, frozen, soon) in [ + (false, false, false, false, 0), + (true, false, false, false, 1), + (false, true, false, false, 1), + (false, false, true, false, 1), + (false, true, false, true, 0), + ] { + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.last_housekeeping_ns = 100_000; + fw.engine.flights.push(Flight { + computes: 0, + compute_pipe: 0, + renders: 1, + target: 0, + fs_target: 0x100, + }); + fw.engine.fs_target = 0x100; + fw.engine.frozen = frozen; + fw.publish_waits = Some((slot_wait, ta_wave_wait, held_wait)); + let mut done = vec![]; + shared + .submit_locked(&mut fw, Arc::new(Job { id: 2 }), &mut done) + .unwrap(); + assert_eq!(fw.retire_calls, 0); + assert_eq!(fw.publish_checked_calls, 1); + assert_eq!(shared.rearmed.get(), 1); + assert_eq!(shared.rearm_soon.get(), soon); + assert_eq!(shared.poll_now_calls.get(), 0); + } +} + #[test] fn submit_locked_and_poll_step_micro_coalesce_busy_horizons() { CLOCK.with(|c| c.set(100_000)); @@ -1707,7 +1850,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 22, + 'tests': 25, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index ad2fac33e3c92..73dbb31f2a668 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -133,12 +133,15 @@ def item(declaration): fn command(job:&Job,k:u32)->Option<&Command>{job.commands.get(k as usize)} type Completions=Vec<(u32,Result)>; fn complete(done:&mut Completions,job:&Arc,result:Result){done.push((job.id,result));} -#[derive(Default)]struct Stats{hold:[u64;3],grouped:u64} +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +__HOLD_CAUSE__ +__HOLD_CAUSE_IMPL__ +#[derive(Default)]struct Stats{hold:[u64;3],hold_causes:[u64;HoldCause::COUNT],grouped:u64} struct Claims; struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,doomed:bool,recovery_suspect:bool,initbm:bool,heavy_render:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,doomed:false,recovery_suspect:false,initbm:false,heavy_render:false}}} __SCS_COMPUTE_CONFLICT__ -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,coalesce_deadline_ns:u64} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,ta_wave_wait:bool,held_wait:bool,coalesce_deadline_ns:u64} impl Engine { __PICK__ __UNPEND__ @@ -230,6 +233,9 @@ def item(declaration): fn mark_class_unavailable(&mut self,class:usize,error:Error){self.unavailable.push((class,error));} fn sync_quarantine_hints(&self){} __NEEDS_ENGINE_DRAIN__ + __RENDER_CAN_PIPELINE__ + __HOLD_CAUSE_FN__ + __NOTE_HOLD__ __TA_WAVE_CAP_FOR__ __ACTIVE_TA_WAVE_CAP__ fn blocked_on_slot_headroom(&self,job:&Arc)->bool{ @@ -310,7 +316,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, - engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,coalesce_deadline_ns:0}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,ta_wave_wait:false,held_wait:false,coalesce_deadline_ns:0}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false, @@ -499,6 +505,55 @@ def item(declaration): assert_eq!(f.publish_checked(&mut done),Ok(())); assert_eq!(f.attempted,[2,3]); } + #[test]fn hold_causes_split_hold0_by_the_gate_that_stopped_publication(){ + let vm1=mk_vm(1); + let vm2=mk_vm(2); + // One held publication pass per case: (in-flight job and kind, its flags, held job, + // host knobs) -> exactly one hold[0] of the expected cause. + let run=|flight:Arc,renders:u32,initbm:bool,doomed:bool,held:Arc, + allow_behind:bool,block_pipeline:Option,block_render:bool,expect:HoldCause, + held_wait:bool|{ + let mut f=firmware(vec![held],vec![]); + let mut fl=Flight::new(flight); + if renders==0{fl.computes=1;}else{fl.renders=renders;} + fl.initbm=initbm; + fl.doomed=doomed; + f.engine.flights.push(fl); + f.allow_behind=allow_behind; + f.pools.block_pipeline_vm=block_pipeline; + f.block_render_behind=block_render; + let mut done=vec![]; + assert_eq!(f.publish_checked(&mut done),Ok(())); + assert!(f.attempted.is_empty(),"{:?}",expect); + assert_eq!(f.engine.stats.hold[0],1,"{:?}",expect); + let mut want=[0u64;HoldCause::COUNT]; + want[expect as usize]=1; + assert_eq!(f.engine.stats.hold_causes,want,"{:?}",expect); + // Only a hold behind the job's own VM's flights asks for the short repoll. + assert_eq!(f.engine.held_wait,held_wait,"{:?}",expect); + }; + let r=|id:u32,vm:&Arc,dep:Result|job_on_vm(id,vm.clone(),true,0,dep); + // A warm same-VM render whose allocator cannot pipeline waits for an empty engine. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,Some(vm1.slot),false,HoldCause::DrainPb,true); + // A cold InitBM flight drains first. + run(r(1,&vm1,Ok(())),1,true,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainInitbm,true); + // Another VM's compute in flight: no cross-VM render/compute overlap. + run(job_on_vm(1,vm2.clone(),false,0,Ok(())),0,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainCross,false); + // A doomed flight drains first. + run(r(1,&vm1,Ok(())),1,false,true,r(2,&vm1,Ok(())),true,None,false,HoldCause::DrainFailed,false); + // A full light TA wave (8 renders) pauses the next light render. + run(r(1,&vm1,Ok(())),8,false,false,r(2,&vm1,Ok(())),true,None,false,HoldCause::TaWave,true); + // Pass, flight or unit headroom. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),true,None,true,HoldCause::Slot,true); + // A failed dependency (pick() skips jobs still waiting for one). + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Err(ECANCELED)),false,None,false,HoldCause::Dependency,false); + // Any other refusal. + run(r(1,&vm1,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other,true); + // Behind another VM's render (warm cross-VM renders overlap): counted, but no short repoll. + run(r(1,&vm2,Ok(())),1,false,false,r(2,&vm1,Ok(())),false,None,false,HoldCause::Other,false); + assert_eq!(HoldCause::NAMES.len(),HoldCause::COUNT); + assert_eq!(HoldCause::Other as usize,HoldCause::COUNT-1); + } #[test]fn alt_bypass_does_not_starve_cold_cross_vm_initbm_while_warm_overlaps(){ let vm1=mk_vm(1); let vm2=mk_vm(2); @@ -534,7 +589,7 @@ def item(declaration): assert_eq!(fw.attempted,[11]); assert_eq!(fw.engine.stats.hold[0],0); - // Cross-VM compute queues immediately behind another VM's active compute without drain. + // Cross-VM compute drains behind another VM's active compute (no cross-VM C<->C overlap). let vm1_c=job_on_vm(12,vm1.clone(),false,0,Ok(())); let vm2_c=job_on_vm(13,vm2.clone(),false,0,Ok(())); let mut fc=firmware(vec![vm2_c],vec![(Ok(()),true)]); @@ -543,8 +598,8 @@ def item(declaration): fc.engine.flights.push(flc); fc.allow_behind=true; assert_eq!(fc.publish_checked(&mut done),Ok(())); - assert_eq!(fc.attempted,[13]); - assert_eq!(fc.engine.stats.hold[0],0); + assert!(fc.attempted.is_empty()); + assert_eq!(fc.engine.stats.hold[0],1); // Cross-VM compute drains behind another VM's active render (no cross-VM R<->C overlap). let vm1_r2=job_on_vm(14,vm1.clone(),true,0,Ok(())); @@ -849,6 +904,7 @@ def item(declaration): __SCS_COMPUTE_CONFLICT__ impl QueueBehindHost { __NEEDS_ENGINE_DRAIN__ + __RENDER_CAN_PIPELINE__ __BLOCKED_ON_SLOT_HEADROOM__ __TA_PENDING_PASSES__ __TA_WAVE_CAP_FOR__ @@ -882,10 +938,9 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert!(p.can_queue_behind(&j2)); - // Cross-VM compute queues behind another VM's healthy compute, but drains behind - // another VM's render. - assert!(p.can_queue_behind(&j_other_vm)); - assert!(!p.needs_engine_drain(&j_other_vm)); + // Cross-VM compute drains behind another VM's compute as behind its render. + assert!(!p.can_queue_behind(&j_other_vm)); + assert!(p.needs_engine_drain(&j_other_vm)); assert!(p.can_queue_behind(&j_render)); p.engine.flights[0].doomed=true; assert!(!p.can_queue_behind(&j2)); @@ -939,13 +994,17 @@ def item(declaration): assert!(!p.can_queue_behind(j)); assert!(p.needs_engine_drain(j)); } - // SCS compute does not start beside non-SCS compute on either pipe. + // SCS compute does not start beside non-SCS compute on either pipe, and no compute + // starts beside another VM's compute. for pipe in [0u8,1] { p.engine.flights=vec![flight(alu.clone(),false,pipe)]; assert!(!p.can_queue_behind(&rq)); assert!(p.needs_engine_drain(&rq)); - assert!(p.can_queue_behind(&rq_post)); - assert!(!p.needs_engine_drain(&rq_post)); + assert!(!p.can_queue_behind(&rq_post)); + assert!(p.needs_engine_drain(&rq_post)); + p.engine.flights=vec![flight(rq_post.clone(),false,pipe)]; + assert!(!p.can_queue_behind(&rq)); + assert!(p.needs_engine_drain(&rq)); } // A render flight of its own VM does not hold it; once SCS compute is gone, the rest // overlaps as before. @@ -956,8 +1015,10 @@ def item(declaration): assert!(!p.needs_engine_drain(&rq)); assert!(p.can_queue_behind(&rq)); p.engine.flights=vec![flight(rq_post.clone(),false,0)]; - assert!(p.can_queue_behind(&alu)); - assert!(!p.needs_engine_drain(&alu)); + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); + assert!(!p.can_queue_behind(&alu)); + assert!(p.needs_engine_drain(&alu)); } #[test]fn compute_query_access_waits_for_timed_predecessor_unless_no_query_access(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); @@ -1078,11 +1139,11 @@ def item(declaration): assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); - // Active VM1 Compute: same-VM R & C allowed; cross-VM C allowed; cross-VM R blocked + drains. + // Active VM1 Compute: same-VM R & C allowed; cross-VM C and R blocked + drain. p.engine.flights=vec![mk_flight(vm1_c.clone(),1,0)]; assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); - assert!(p.can_queue_behind(&vm2_c) && !p.needs_engine_drain(&vm2_c)); + assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); // Mixed active VM1 Render + VM1 Compute: both cross-VM R and cross-VM C blocked + drain. p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1),mk_flight(vm1_c.clone(),1,0)]; @@ -1824,9 +1885,13 @@ def item(declaration): host.engine.next_compute_pipe=0; assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 0); assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 0); - assert!(host.can_queue_behind(&c_vm2)); + // No compute queues beside another VM's compute flight, on either pipe. + assert!(!host.can_queue_behind(&c_vm2)); + assert!(!host.can_queue_behind(&c2)); // Same-VM compute still pipelines without draining. + host.engine.flights.pop(); assert!(host.can_queue_behind(&c2)); + assert!(!host.can_queue_behind(&c_vm2)); } #[test]fn two_pipe_compute_barriers_reuse_single_pipe_and_serialize_across_both_pipes(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); @@ -2667,6 +2732,7 @@ def item(declaration): chan_wait: bool, slot_wait: bool, ta_wave_wait: bool, + held_wait: bool, coalesce_deadline_ns: u64, } struct Slots { free_c: u32 } @@ -2720,6 +2786,7 @@ def item(declaration): chan_wait: false, slot_wait: false, ta_wave_wait: false, + held_wait: false, coalesce_deadline_ns: 0, }, slots: Slots { free_c: 20 }, @@ -2744,6 +2811,12 @@ def item(declaration): assert_eq!(h.defer_busy_coalesce(110_000), None); assert_eq!(h.engine.coalesce_deadline_ns, 0); + // A job held behind the VM's own flights is never coalesced behind them. + h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; + h.engine.held_wait = true; + assert_eq!(h.defer_busy_coalesce(150_000), None); + h.engine.held_wait = false; + // Deadline expiry flushes even with 1 pending command. h.engine.pending = vec![mk_job(&vm1, &q1, false, 3, [None, None])]; assert_eq!(h.defer_busy_coalesce(200_000), Some(18)); @@ -2848,6 +2921,11 @@ def item(declaration): '__PUBLISH__': 'pub(crate) fn publish(&mut self', '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', '__NEEDS_ENGINE_DRAIN__': 'fn needs_engine_drain(', + '__RENDER_CAN_PIPELINE__': 'fn render_can_pipeline(', + '__HOLD_CAUSE__': 'enum HoldCause {', + '__HOLD_CAUSE_IMPL__': 'impl HoldCause {', + '__HOLD_CAUSE_FN__': 'fn hold_cause(', + '__NOTE_HOLD__': 'fn note_hold(', '__BLOCKED_ON_SLOT_HEADROOM__': 'fn blocked_on_slot_headroom(', '__DESCRIPTOR_CONTAINMENT__': 'if encode::preserve_compute_descriptor(', '__PUBLISH_PRODUCER__': 'fn publish_producer(',