diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 5a689c60e37f7..046910905418b 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -681,15 +681,17 @@ impl InitData { } /// M5 TA, fragment and compute share the compute outer ring per priority. - /// The physical queue claim prevents reassignment while this credit lives. + /// The caller must hold `Port::m5_outer`; the physical queue claim prevents + /// reassignment while this credit lives. pub(crate) fn reserve_outer(&self, priority: u8, count: u32) -> Result { if !self.m5 { return Err(EINVAL); } let cursors = self.work_cursors(priority, super::fw::queue::DataMaster::Compute)?; self.outer_credits.as_ref().ok_or(EIO)?.reserve(priority, count, cursors) } - /// Hold the device mutex for this scope, including its Drop. The result - /// borrows only the claim, allowing the caller to publish through Firmware. + /// Hold the device mutex for this scope, including its Drop, and serialize entry + /// and Drop under `Port::m5_outer` via `Port::outer_scope`. The result borrows + /// only the claim, allowing the caller to publish through Firmware. pub(crate) fn outer_scope<'a>(&self, claim: &'a mut OuterClaim) -> Result> { self.outer_credits.as_ref().ok_or(EINVAL)?.scope(claim) } @@ -1074,6 +1076,8 @@ impl InitData { // The word recovery_state() reads: the status block moves with the firmware build. recovery: self.object(self.cluster)?.word(self.recovery_state_offset())?, mailbox, + m5_credits: self.outer_credits.clone(), + m5_history: self.m5_history_view()?, }) } diff --git a/drivers/gpu/drm/asahi/g17/initdata/m5.rs b/drivers/gpu/drm/asahi/g17/initdata/m5.rs index a5ec8476745f5..7fc5443f44a7f 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/m5.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/m5.rs @@ -52,6 +52,32 @@ impl InitData { ring(0), ring(1), ring(2), ring(3), page(canonical.start)] } + /// Direct-port view of the M5 submission-history table (none off M5 or on common 26A428). + pub(super) fn m5_history_view(&self) -> Result> { + if !self.m5 || self.graph.is_common26() { + return Ok(None); + } + let private = self.object(self.cluster)?; + let base = self.graph.private.status_config; + let field = |offset| { + self.m5_status_config + .relocate(offset) + .map(|at| base + at) + .ok_or(EINVAL) + }; + let history = field(m::M5_STATUS_CONFIG_HISTORY)?; + Ok(Some(crate::g17::port::M5HistoryView { + generation: private.word(field(m::M5_STATUS_CONFIG_HISTORY_GENERATION)?)?, + config: [ + private.word(history)?, + private.word(history + 4)?, + private.word(history + 8)?, + private.word(history + 12)?, + ], + slots: private.pointer(field(m::M5_STATUS_CONFIG_HISTORY_SLOTS)?, 256)?, + })) + } + /// Selects the power-policy layout of the M5 firmware build `build_m5` encodes for. pub(in crate::g17) fn set_m5_policy_layouts( &mut self, diff --git a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs index 08804ff1fc498..58d0822f53dde 100644 --- a/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs +++ b/drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs @@ -9,7 +9,7 @@ use kernel::{prelude::*, sync::Arc}; const PRIORITIES: usize = 4; -pub(super) struct Credits { +pub(crate) struct Credits { reserved: [AtomicU32; PRIORITIES], published: [AtomicU64; PRIORITIES], consumers: [AtomicU64; PRIORITIES], @@ -24,7 +24,8 @@ pub(crate) struct OuterClaim { } /// Borrows the claim only. The caller must hold the device mutex from entry -/// through Drop: its temporarily lent credits are available to that publisher. +/// through Drop and serialize entry and Drop under `Port::m5_outer` (via +/// `Port::outer_scope`): its temporarily lent credits are available to that publisher. pub(crate) struct OuterScope<'a> { claim: &'a mut OuterClaim, before: u64, @@ -49,19 +50,23 @@ impl Credits { }, GFP_KERNEL)?) } - pub(super) fn available(&self) -> Arc { self.available.clone() } + pub(crate) fn available(&self) -> Arc { self.available.clone() } pub(super) fn waiting(&self) -> bool { self.available.has_waiters() } - pub(super) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result { + pub(crate) fn is_scoped(&self) -> bool { + self.scoped.load(Ordering::Acquire) + } + + pub(crate) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result { let pending = self.reserved.get(usize::from(priority)).ok_or(EINVAL)? .load(Ordering::Acquire); Ok(free(cursors)?.saturating_sub(pending)) } - /// Reserve under the sole publisher mutex. Off-lock cancellation may only + /// Reserve under the outer-ring lock. Off-lock cancellation may only /// reduce reserved counts, so the sampled capacity is conservative. - pub(super) fn reserve(self: &Arc, priority: u8, count: u32, + pub(crate) fn reserve(self: &Arc, priority: u8, count: u32, cursors: [u32; 3]) -> Result { if count == 0 || count >= WORK_RING_SLOTS { return Err(EINVAL); } @@ -75,6 +80,26 @@ impl Credits { Ok(OuterClaim { domain: self.clone(), priority: index, remaining: count }) } + /// Consumes one reserved slot for a direct M5 publication without touching + /// `published[]`, so an enclosing device-mutex `OuterScope` never debits a direct slot. + pub(crate) fn consume_direct(&self, claim: &mut OuterClaim) -> Result { + self.consume_direct_count(claim, 1) + } + + /// Consumes `count` reserved slots for a direct M5 publication without touching + /// `published[]`, so an enclosing device-mutex `OuterScope` never debits direct slots. + pub(crate) fn consume_direct_count(&self, claim: &mut OuterClaim, count: u32) -> Result { + if count == 0 || !core::ptr::eq(self, &*claim.domain) { + return Err(EINVAL); + } + if claim.remaining < count { + return Err(EIO); + } + claim.remaining -= count; + self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel); + Ok(()) + } + pub(super) fn scope<'a>(self: &Arc, claim: &'a mut OuterClaim) -> Result> { if !Arc::ptr_eq(self, &claim.domain) { return Err(EINVAL); } if self.scoped.swap(true, Ordering::AcqRel) { return Err(EBUSY); } @@ -116,6 +141,11 @@ impl OuterClaim { pub(crate) fn remaining(&self) -> u32 { self.remaining } + + /// Priority class of the reserved outer work ring. + pub(crate) fn priority(&self) -> usize { + self.priority + } } impl Drop for OuterClaim { @@ -128,3 +158,108 @@ impl Drop for OuterClaim { } } } + +#[kernel::macros::kunit_tests(asahi_g17_outer_credit)] +mod tests { + use super::*; + + #[test] + fn direct_consumption_does_not_debit_outer_scope() { + let credits = Credits::new().unwrap(); + let cursors = [0, 0, 0]; + let full = free(cursors).unwrap(); + let mut scoped_claim = credits.reserve(1, 2, cursors).unwrap(); + let mut direct_claim = credits.reserve(1, 1, cursors).unwrap(); + let mut direct_pair = credits.reserve(1, 2, cursors).unwrap(); + assert_eq!(credits.capacity(1, cursors).unwrap(), full - 5); + + // Direct publish consumes only its own reserved slots and leaves published[] untouched. + assert!(!credits.is_scoped()); + credits.consume_direct(&mut direct_claim).unwrap(); + assert_eq!(direct_claim.remaining(), 0); + credits.consume_direct_count(&mut direct_pair, 2).unwrap(); + assert_eq!(direct_pair.remaining(), 0); + assert_eq!(credits.capacity(1, cursors).unwrap(), full - 2); + assert_eq!(credits.counter(1).unwrap().load(Ordering::Acquire), 0); + + // An OuterScope taken afterward keeps its full 2 credits when nothing published via it. + { + let _scope = credits.scope(&mut scoped_claim).unwrap(); + assert!(credits.is_scoped()); + assert!(credits.reserve(1, 1, cursors).is_err()); + } + assert!(!credits.is_scoped()); + assert_eq!(scoped_claim.remaining(), 2); + drop(direct_claim); + drop(direct_pair); + drop(scoped_claim); + assert_eq!(credits.capacity(1, cursors).unwrap(), full); + } + + #[test] + fn mixed_render_compute_wrap_and_generation_change_with_queued_claim() { + let credits = Credits::new().unwrap(); + let n = WORK_RING_SLOTS; + // Producer sits two slots before wrap while both consumers lag 4 slots behind + // (free = WORK_RING_SLOTS - 5). + let mut consumer_a = n - 6; + let mut consumer_b = n - 6; + let mut producer = n - 2; + let cursors = [consumer_a, consumer_b, producer]; + let initial_free = free(cursors).unwrap(); + assert_eq!(initial_free, n - 5); + + // Interleave a queued 2-slot render claim with 1-slot compute claims across ring wrap. + let mut queued_render = credits.reserve(2, 2, cursors).unwrap(); + let mut compute_a = credits.reserve(2, 1, cursors).unwrap(); + credits.consume_direct(&mut compute_a).unwrap(); + producer = (producer + 1) % n; // n - 1 + assert_eq!( + credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), + initial_free - 3, + ); + + let mut compute_b = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap(); + credits.consume_direct(&mut compute_b).unwrap(); + producer = (producer + 1) % n; // 0 (wrapped!) + assert_eq!(producer, 0); + + // Fill remaining capacity so exactly 1 free slot remains; 2-slot render must fail EBUSY + // while 1-slot compute still succeeds across the wrap boundary. + let rem = credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(); + let filler = credits.reserve(2, rem - 1, [consumer_a, consumer_b, producer]).unwrap(); + assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 1); + assert_eq!(credits.reserve(2, 2, [consumer_a, consumer_b, producer]).err(), Some(EBUSY)); + let mut edge_compute = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap(); + credits.consume_direct(&mut edge_compute).unwrap(); + producer = (producer + 1) % n; // 1 + assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 0); + drop(filler); + + // Consumers advance across the wrap boundary and report progress. + consumer_a = 1; + consumer_b = 1; + let wrapped = [consumer_a, consumer_b, producer]; + assert!(credits.progressed(2, wrapped).unwrap()); + assert_eq!(credits.capacity(2, wrapped).unwrap(), (n - 1) - 2); + + // Simulate locked render / recovery entering OuterScope while a queued compute claim + // waits across a generation change: new reserves fail EBUSY and direct consumption never + // debits OuterScope's published counter; dropping the queued claim after the generation + // change releases its reserved credits cleanly. + let queued_compute = credits.reserve(2, 1, wrapped).unwrap(); + { + let _scope = credits.scope(&mut queued_render).unwrap(); + assert!(credits.is_scoped()); + assert_eq!(credits.reserve(2, 1, wrapped).err(), Some(EBUSY)); + credits.counter(2).unwrap().fetch_add(2, Ordering::AcqRel); + } + assert!(!credits.is_scoped()); + assert_eq!(queued_render.remaining(), 0); + // Generation changed before queued_compute published: dropping it returns its credit. + assert_eq!(queued_compute.remaining(), 1); + drop(queued_compute); + drop(queued_render); + assert_eq!(credits.capacity(2, wrapped).unwrap(), n - 1); + } +} diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 41e39c9b84b89..eb16b78da6098 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1286,6 +1286,13 @@ struct Shared { /// wherever the completion IRQ thread first ran (see `queue_event_records`). On M5 it is /// unbound, so a worker of that CPU's affinity pod (its L2) runs it; elsewhere it is per-CPU. events: Arc, + /// Preallocated completion collector owned exclusively by `run_runtime_events`. + #[pin] + worker_deferred: Mutex>, + /// Restrict each scheduler's ordered submit queue to the creating CPU's cluster, beside the + /// event work. Single-die M5 parts leave schedulers unrestricted so queues created on one + /// thread do not contend on a single cluster under multi-queue load. + pin_scheduler_cluster: bool, /// The CPU of the last publication, `u32::MAX` before the first. submitter: AtomicU32, #[pin] @@ -1640,6 +1647,12 @@ impl Shared { self.events.clone() } + /// Whether each scheduler's submit queue should be restricted to the creating CPU's cluster + /// (all but single-die M5). + pub(super) fn pin_scheduler_cluster(&self) -> bool { + self.pin_scheduler_cluster + } + /// Records the publishing CPU for the event work's placement. fn note_submitter(&self) { let cpu = kernel::cpu::CpuId::current().as_u32(); @@ -1949,6 +1962,7 @@ impl Gpu { let max_pstate = frequencies .as_ref() .map_or(0, stats::StateFrequencies::max_pstate); + let worker_deferred = runtime::DeferredBatch::worker()?; let shared = Arc::pin_init( pin_init!(Shared { drm <- new_mutex!(Some(dev.into()), "g17::Shared::drm"), @@ -1992,6 +2006,11 @@ impl Gpu { governor_armed: AtomicBool::new(false), governor_activity_ns: AtomicU64::new(0), events, + worker_deferred <- new_mutex!( + Some(worker_deferred), + "g17::Shared::worker_deferred" + ), + pin_scheduler_cluster: !m5 || id.num_dies > 1, submitter: AtomicU32::new(u32::MAX), grow <- new_work!("g17::Shared::grow"), reclaim_work <- new_work!("g17::Shared::reclaim_work"), diff --git a/drivers/gpu/drm/asahi/g17/port.rs b/drivers/gpu/drm/asahi/g17/port.rs index ebd1ba7071882..7083cf028a403 100644 --- a/drivers/gpu/drm/asahi/g17/port.rs +++ b/drivers/gpu/drm/asahi/g17/port.rs @@ -7,9 +7,9 @@ //! through a preparation lease ([`super::Shared::port`]): shutdown and device loss join every //! lease before they detach the session. Each piece below is atomic or has its own lock. //! -//! Lock order: device mutex -> compute queue cell -> the locks of this port. The render -//! publication lock comes first among the port's locks: device mutex -> render publication -//! lock -> admission pool, QoS, mailbox. Its holder never takes the device mutex. +//! Lock order: device mutex -> outer_{compute,render} -> compute queue cell -> the locks of +//! this port. Among the port's locks: render publication lock -> M5 outer-ring lock -> +//! admission pool, QoS, mailbox. None of their holders ever takes the device mutex. use super::{ fw::{ @@ -73,6 +73,14 @@ impl RingView { } } +/// Raw pointers to the M5 submission-history table in firmware-shared memory. +#[derive(Clone, Copy)] +pub(super) struct M5HistoryView { + pub(super) generation: *const AtomicU32, + pub(super) config: [*const AtomicU32; 4], + pub(super) slots: *mut u8, +} + /// Raw views of the session's firmware-shared memory, fixed once the firmware is built. pub(super) struct Views { pub(super) compute: [RingView; PRIORITIES], @@ -83,6 +91,8 @@ pub(super) struct Views { pub(super) qos: *mut u8, pub(super) recovery: *const AtomicU32, pub(super) mailbox: *const super::Mailbox, + pub(super) m5_credits: Option>, + pub(super) m5_history: Option, } // SAFETY: The views only name memory and a mailbox owned by the firmware session, which outlives @@ -114,6 +124,10 @@ pub(super) struct Port { /// overlaps are ordered by publication order (see hazard.rs). #[pin] render: Mutex<()>, + /// Serializes M5 shared outer-ring writes, host-port gating transactions, and submission + /// history geometry/updates across direct compute publishers and device-mutex publishers. + #[pin] + m5_outer: Mutex>, /// The accepted recovery generation, mirrored for publishers without the device mutex. generation: AtomicU64, /// Device publication order shared by compute and render commands. @@ -149,6 +163,37 @@ impl RenderRoom { } } +/// Room for two slots on M5's shared outer work ring of one priority, reserved under +/// both the render publication lock and `m5_outer`. +#[derive(Clone, Copy)] +pub(super) struct M5RenderRoom { + priority: u8, + start: u32, + next: [u32; 2], +} + +impl M5RenderRoom { + pub(super) fn priority(&self) -> u8 { + self.priority + } +} + +/// Serializes entry and Drop of an M5 [`super::initdata::OuterScope`] under `Port::m5_outer` +/// so `Credits::scoped` and `reserved[]` cannot race with direct M5 reservations or publications. +pub(super) struct PortOuterScope<'a> { + scope: Option>, + port: Arc, +} + +impl Drop for PortOuterScope<'_> { + fn drop(&mut self) { + if let Some(scope) = self.scope.take() { + let _m5_outer = self.port.m5_outer_lock(); + drop(scope); + } + } +} + /// A compute work-ring slot reserved before any command becomes visible. Dropping an unused /// claim returns the slot. pub(super) struct OuterClaim<'a> { @@ -183,6 +228,7 @@ impl Port { rx_applied <- new_spinlock!(None, "g17::Port::rx_applied"), rx_state: AtomicU8::new(RX_STATE_UNSET), render <- new_mutex!((), "g17::Port::render"), + m5_outer <- new_mutex!(None, "g17::Port::m5_outer"), generation: AtomicU64::new(0), publications: AtomicU64::new(0), effort_full: AtomicBool::new(false), @@ -313,6 +359,298 @@ impl Port { self.render.lock() } + /// Serializes M5 shared outer-ring and host-port updates with direct M5 compute publishers. + pub(super) fn m5_outer_lock(&self) -> MutexGuard<'_, Option<(u32, u64, u64)>> { + self.m5_outer.lock() + } + + /// Enters an M5 `OuterScope` under `m5_outer` and returns a guard that re-acquires + /// `m5_outer` around the inner scope's Drop, preventing races with direct M5 reservations. + pub(super) fn outer_scope<'a>( + self: &Arc, + init: &super::initdata::InitData, + claim: &'a mut super::initdata::OuterClaim, + ) -> Result> { + let _m5_outer = self.m5_outer.lock(); + let scope = init.outer_scope(claim)?; + Ok(PortOuterScope { + scope: Some(scope), + port: self.clone(), + }) + } + + /// Clears the cached M5 submission-history geometry after firmware recovery restarts. + pub(super) fn reset_m5_history(&self) { + *self.m5_outer.lock() = None; + } + + /// M5: the availability domain outer-ring claims wait on. None off M5 or before attach. + pub(super) fn outer_domain(&self) -> Option> { + self.views() + .ok()? + .m5_credits + .as_ref() + .map(|credits| credits.available()) + } + + /// Reserves `count` slots on M5's shared outer ring without taking the device mutex. + /// Returns EBUSY if a device-mutex OuterScope is active or fewer than `count` slots are free. + pub(super) fn reserve_m5_outer( + &self, + priority: u8, + count: u32, + ) -> Result { + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + let _guard = self.m5_outer.lock(); + if credits.is_scoped() { + return Err(EBUSY); + } + let cursors = ring.cursors()?; + credits.reserve(priority, count, cursors) + } + + /// Reserves one slot on M5's shared outer ring for a direct compute publisher without + /// taking the device mutex. Returns EBUSY if a device-mutex OuterScope is active or full. + pub(super) fn reserve_m5_compute(&self, priority: u8) -> Result { + self.reserve_m5_outer(priority, 1) + } + + /// Publishes one compute slot on M5's shared outer ring while the caller holds `m5_outer`, + /// consuming the caller's direct reservation. + pub(super) fn publish_m5_compute_locked( + &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, + priority: u8, + claim: &mut super::initdata::OuterClaim, + record: &WorkSlot, + ) -> Result { + if record.data_master != DataMaster::Compute as u32 { + return Err(EINVAL); + } + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + let [first, second, producer] = ring.cursors()?; + let next = (producer + 1) % WORK_RING_SLOTS; + if next == first || next == second { + return Err(EIO); + } + // SAFETY: The ring view spans WORK_RING_SLOTS records, checked when the session built + // it; `producer` is in range. The reservation proves firmware does not own this slot and + // `m5_outer` excludes every other host writer on M5's shared outer ring. + unsafe { + core::ptr::copy_nonoverlapping( + core::ptr::from_ref(record).cast::(), + ring.slots + .add(producer as usize * core::mem::size_of::()), + core::mem::size_of::(), + ); + } + fence(Ordering::SeqCst); + // SAFETY: As for `RingView::cursors`. + unsafe { (*ring.producer).store(next, Ordering::Relaxed) }; + fence(Ordering::SeqCst); + credits.consume_direct(claim)?; + Ok(next) + } + + /// Issues an M5 host-port compute submission with gating held off while `m5_outer` is held. + pub(super) fn submit_m5_work_held_locked( + &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, + submission: &super::fw::m5::queue::HardwareSubmission, + ) -> Result { + self.regs.as_ref().ok_or(ENODEV)?.submit_m5_work_held(submission) + } + + /// Counts `submissions` in the M5 submission-history table without taking the device mutex, + /// while the caller holds `m5_outer`. + pub(super) fn note_m5_submission_history_locked( + &self, + geometry: &mut MutexGuard<'_, Option<(u32, u64, u64)>>, + submissions: u8, + ) -> Result { + let Some(history) = self.views()?.m5_history else { + return Ok(()); + }; + for _ in 0..64 { + // SAFETY: Pointers name retained, bounds-checked firmware-shared words. + let generation = unsafe { (*history.generation).load(Ordering::Acquire) }; + if generation & 1 != 0 { + core::hint::spin_loop(); + continue; + } + let (period, count) = match **geometry { + Some((seen, period, count)) if seen == generation => (period, count), + _ => { + // SAFETY: As above; seqlock generation recheck validates consistency. + let c = unsafe { + [ + (*history.config[0]).load(Ordering::Relaxed), + (*history.config[1]).load(Ordering::Relaxed), + (*history.config[2]).load(Ordering::Relaxed), + (*history.config[3]).load(Ordering::Relaxed), + ] + }; + fence(Ordering::Acquire); + // SAFETY: As above. + if generation != unsafe { (*history.generation).load(Ordering::Acquire) } { + core::hint::spin_loop(); + continue; + } + let period = u64::from(c[0]) | (u64::from(c[1]) << 32); + let count = u64::from(c[2]) | (u64::from(c[3]) << 32); + **geometry = Some((generation, period, count)); + (period, count) + } + }; + if period == 0 || count == 0 || count > 256 { + return Err(EINVAL); + } + let (counter, frequency) = qos::clock(); + let ticks = qos::time_from_host(counter, frequency)?; + let index = (ticks % period) / 25_000; + if index >= count { + return Err(ERANGE); + } + // SAFETY: `slots` spans 256 WC bytes and `index < count <= 256`. + unsafe { + let byte = history.slots.add(index as usize); + let value = core::ptr::read_volatile(byte).wrapping_add(submissions); + core::ptr::write_volatile(byte, value); + } + fence(Ordering::SeqCst); + return Ok(()); + } + Err(EBUSY) + } + + /// Reserves two slots on M5's shared outer ring for a direct render pair while + /// `m5_outer` is already held. Returns EBUSY if a device-mutex OuterScope is active + /// or fewer than two slots are free. + pub(super) fn reserve_m5_render_locked( + &self, + _guard: &MutexGuard<'_, Option<(u32, u64, u64)>>, + priority: u8, + ) -> Result<(M5RenderRoom, super::initdata::OuterClaim)> { + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(priority)?; + if credits.is_scoped() { + return Err(EBUSY); + } + let cursors = ring.cursors()?; + let start = cursors[2]; + let next = [(start + 1) % WORK_RING_SLOTS, (start + 2) % WORK_RING_SLOTS]; + if next.iter().any(|&p| p == cursors[0] || p == cursors[1]) { + return Err(EBUSY); + } + let claim = credits.reserve(priority, 2, cursors)?; + Ok(( + M5RenderRoom { + priority, + start, + next, + }, + claim, + )) + } + + /// Copies an M5 render pair's fragment, then tiling record into the two reserved slots + /// of M5's shared outer ring without exposing them, commits accounting, issues the + /// host-port advance, and publishes inner producers (as `Firmware::submit_m5_render_pair`). + #[expect( + clippy::too_many_arguments, + reason = "Mirrors write_render_pair with the held M5 outer lock." + )] + pub(super) fn write_m5_render_pair( + &self, + _render: &MutexGuard<'_, ()>, + _m5_outer: &MutexGuard<'_, Option<(u32, u64, u64)>>, + room: &M5RenderRoom, + fragment: &WorkSlot, + tiling: &WorkSlot, + commit_accounting: impl FnOnce() -> Result, + publish_inner: impl FnOnce(), + ) -> Result<[u32; 2]> { + if !matches!(fragment.data_master, 1 | 2) || !matches!(tiling.data_master, 0 | 2) { + return Err(EINVAL); + } + let regs = self.regs.as_ref().ok_or(ENODEV)?; + let (_, ring) = self.ring(room.priority)?; + let records = [ + WorkSlot::new( + DataMaster::Compute, + fragment.queue_va, + fragment.qid, + fragment.items_end, + fragment.first != 0, + )?, + WorkSlot::new( + DataMaster::Compute, + tiling.queue_va, + tiling.qid, + tiling.items_end, + tiling.first != 0, + )?, + ]; + let submission = super::fw::m5::queue::HardwareSubmission::advance_pair( + fragment.qid, + tiling.qid, + )?; + let destinations = [room.start, room.next[0]].map(|index| { + // SAFETY: The ring view spans WORK_RING_SLOTS records; `reserve_m5_render_locked` + // validated both indices are in range and host-owned while `m5_outer` stays held. + unsafe { + ring.slots + .add(index as usize * core::mem::size_of::()) + } + }); + for (record, destination) in records.iter().zip(destinations) { + // SAFETY: Both slots are distinct, reserved, and protected by `m5_outer`. + unsafe { + core::ptr::copy_nonoverlapping( + core::ptr::from_ref(record).cast::(), + destination, + core::mem::size_of::(), + ); + } + } + commit_accounting()?; + regs.submit_m5_work(&submission)?; + publish_inner(); + Ok(room.next) + } + + /// Exposes a retained M5 render pair written by `write_m5_render_pair` with one + /// producer update and consumes its two direct outer-ring credits. + pub(super) fn expose_m5_render_pair( + &self, + _render: &MutexGuard<'_, ()>, + _m5_outer: &MutexGuard<'_, Option<(u32, u64, u64)>>, + room: &M5RenderRoom, + claim: &mut super::initdata::OuterClaim, + next: [u32; 2], + ) -> Result { + if next != room.next { + return Err(EBUSY); + } + let views = self.views()?; + let credits = views.m5_credits.as_ref().ok_or(EINVAL)?; + let (_, ring) = self.ring(room.priority)?; + if ring.cursors()?[2] != room.start { + return Err(EBUSY); + } + fence(Ordering::SeqCst); + // SAFETY: As for `RingView::cursors`; `m5_outer` has been held continuously + // since `reserve_m5_render_locked` and `write_m5_render_pair`. + unsafe { (*ring.producer).store(room.next[1], Ordering::Relaxed) }; + fence(Ordering::SeqCst); + credits.consume_direct_count(claim, 2) + } + fn render_rings(&self, priority: u8) -> Result<(RingView, RingView)> { let views = self.views()?; let index = usize::from(priority); diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index afc1ee221567a..cbd7eb407c34e 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -1045,6 +1045,18 @@ impl Queue { || self.retire_pending || masks.is_none_or(|m| m[self.qid() as usize / 64] & (1 << (self.qid() % 64)) != 0) } + + pub(crate) fn needs_scan_retire(&self, masks: Option<[u64; 2]>) -> bool { + self.configuration.is_some() || (!self.quarantined && self.selected(masks)) + } + + pub(crate) fn has_terminal(&self) -> bool { + self.terminal.is_some() + } + + pub(crate) fn awaiting_witness(&self) -> bool { + self.awaiting_witness + } /// Stage every unlatched exact identity before the device's single shared-ring scan, /// whichever queues the scan's batch retires. pub(crate) fn request_observations(&self, batch: &mut Batch) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 208b4862ba20f..d5d0d8a603a07 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -182,7 +182,6 @@ pub(super) struct Registry { completion_cursor: usize, /// Control word of each completion-ring slot as of the last scan that read it. completion_seen: KVVec, - worker_deferred: Option, teardown: super::teardown::Pending, } @@ -240,7 +239,6 @@ impl Registry { } seen }, - worker_deferred: Some(DeferredBatch::worker()?), teardown: super::teardown::Pending::new()?, }) } @@ -1473,7 +1471,7 @@ impl DeferredBatch { }; /// Reused by the sole event work item; no allocation on a completion pass. - fn worker() -> Result { + pub(super) fn worker() -> Result { Self::with_capacity(2 * QIDS * Self::DEPTH, QIDS) } /// One publication can quarantine only its selected physical queue/pair. @@ -1718,6 +1716,9 @@ impl compute::Host for ComputeHost<'_> { struct DirectHost<'a> { port: &'a super::port::Port, outer: Option>, + m5_outer: Option<&'a mut super::initdata::OuterClaim>, + m5_outer_guard: Option>>, + m5: bool, generation: u64, } impl compute::Host for DirectHost<'_> { @@ -1748,18 +1749,44 @@ impl compute::Host for DirectHost<'_> { fn register_queue(&mut self, _queue: &super::fw::kick::KsmQueue) -> Result { Err(EAGAIN) } - fn publish_outer(&mut self, _priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { + fn publish_outer(&mut self, priority: u8, slot: &super::fw::channels::WorkSlot) -> Result { + if self.m5 { + let claim = self.m5_outer.as_deref_mut().ok_or(EIO)?; + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + return self + .port + .publish_m5_compute_locked(guard, priority, claim, slot) + .map(|_| ()); + } self.port.publish_compute(self.outer.take().ok_or(EIO)?, slot).map(|_| ()) } fn notify(&mut self, message: u64) -> Result { + if self.m5 && message >> super::MSG_TYPE_SHIFT == 0x83 && message & 3 == 2 { + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + if let Err(error) = self.port.note_m5_submission_history_locked(guard, 1) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + // Drop `m5_outer` before ringing the mailbox doorbell so competing M5 submitters + // do not wait behind mailbox I/O. + self.m5_outer_guard = None; + } self.port.notify(message) } fn note_submission(&mut self) -> Result { Ok(()) } - fn submit_m5(&mut self, _submission: &super::fw::m5::queue::HardwareSubmission) -> Result { - // M5 never publishes without the device mutex (see compute_direct). - Err(EINVAL) + fn submit_m5(&mut self, submission: &super::fw::m5::queue::HardwareSubmission) -> Result { + if !self.m5 { + return Err(EINVAL); + } + let guard = self + .m5_outer_guard + .get_or_insert_with(|| self.port.m5_outer_lock()); + self.port.submit_m5_work_held_locked(guard, submission) } } @@ -1851,21 +1878,6 @@ impl super::Firmware { if self.recovery.pending() { return Err(EAGAIN); } - // No descriptor, accounting or inner producer changes precede this - // reservation; dropping it unused returns the work-ring slot. M5 compute takes its - // slot on the work ring M5 render shares, under this mutex (InitData::publish_work_at): - // a full ring is refused here, before a queue install or kick changes any state. - let mut outer_cursors = None; - let outer = if self.init.is_m5() { - let priority = packet.context.policy().priority(); - let Some(cursors) = self.init.m5_compute_room(priority)? else { - return Err(EAGAIN); - }; - outer_cursors = Some((priority, cursors)); - None - } else { - Some(self.port.reserve_compute(packet.context.policy().priority())?) - }; let queues = &mut self.queues; let mut queue = queues .compute @@ -1883,6 +1895,22 @@ impl super::Firmware { { return Err(EAGAIN); } + // No descriptor, accounting or inner producer changes precede this + // reservation; dropping it unused returns the work-ring slot. M5 compute + // serializes the shared outer ring and host-port updates under `m5_outer` + // (after the compute cell lock, matching direct M5 publishers). + let _m5_outer = self.init.is_m5().then(|| self.port.m5_outer_lock()); + let mut outer_cursors = None; + let outer = if self.init.is_m5() { + let priority = packet.context.policy().priority(); + let Some(cursors) = self.init.m5_compute_room(priority)? else { + return Err(EAGAIN); + }; + outer_cursors = Some((priority, cursors)); + None + } else { + Some(self.port.reserve_compute(packet.context.policy().priority())?) + }; let mut host = ComputeHost { shared: &self.primary.state.shared, init: &self.init, @@ -1990,25 +2018,66 @@ impl Registry { } } +/// Post-scan compute state collected while `scan_compute_summary` already holds each cell lock, +/// allowing the event worker to avoid redundant full-registry cell scans. +#[derive(Clone, Copy, Default)] +pub(super) struct ComputeScan { + pub(super) in_flight: bool, + pub(super) replay: bool, + pub(super) polling: bool, +} + impl super::Firmware { + fn scan_compute(&mut self, masks: Option<[u64; 2]>, deferred: &mut DeferredBatch) -> Result { + self.scan_compute_summary(masks, deferred).map(|_| ()) + } + /// Latch one shared snapshot for all selected queues before settling any VM. /// A later queue's exact success in this batch wins over a peer's failure. - fn scan_compute(&mut self, masks: Option<[u64; 2]>, deferred: &mut DeferredBatch) -> Result { + fn scan_compute_summary( + &mut self, + masks: Option<[u64; 2]>, + deferred: &mut DeferredBatch, + ) -> Result { let state = super::recovery::Memory::recovery_state(&self.init)?; let generation = self.recovery.generation(); let registry = &mut self.queues; registry.observations.clear(); let mut requested = false; + let mut retire_mask = 0u128; + let mut terminal_mask = 0u128; + let mut witness_mask = 0u128; + let mut in_flight_mask = 0u128; + let mut replay_mask = 0u128; + let mut polling_mask = 0u128; // Every queue's pending identities are staged, not only the ones this batch // retires: the scan passes each new record once, and a queue retired by a later // batch finds its observation already latched. - for queue in registry - .compute - .iter() - .flatten() - .filter_map(|entry| entry.queue.as_deref()) - { - requested |= queue.request_observations(&mut registry.observations)?; + for (index, entry) in registry.compute.iter().enumerate() { + let Some(queue) = entry.as_ref().and_then(|entry| entry.queue.as_deref()) else { + continue; + }; + let bit = 1u128.checked_shl(index as u32).unwrap_or(0); + let slot_requested = queue.request_observations(&mut registry.observations)?; + requested |= slot_requested; + if slot_requested || queue.needs_scan_retire(masks) { + retire_mask |= bit; + } + if queue.has_terminal() { + terminal_mask |= bit; + } + if queue.awaiting_witness() { + witness_mask |= bit; + } + if queue.in_flight() { + in_flight_mask |= bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } } // Completion records are appended in order: fold only the records written since // the previous scan. A request whose stamp already covers it has its record in the @@ -2030,14 +2099,21 @@ impl super::Firmware { let port = &self.port; let retired = deferred.pending(); let mut freed = false; - for mut queue in registry - .compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - { + let mut pending = retire_mask; + while pending != 0 { + let index = pending.trailing_zeros() as usize; + let bit = 1u128 << index; + pending &= !bit; + let Some(mut queue) = registry.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + else { + continue; + }; let busy = !queue.channel_free(); - queue.latch_observations(&mut registry.observations)?; + if requested { + queue.latch_observations(&mut registry.observations)?; + } queue.retire( masks, generation, @@ -2046,35 +2122,79 @@ impl super::Firmware { &mut |event| deferred.push(event), )?; freed |= busy && queue.channel_free(); + if queue.has_terminal() { + terminal_mask |= bit; + } + if queue.awaiting_witness() { + witness_mask |= bit; + } + if queue.in_flight() { + in_flight_mask |= bit; + } else { + in_flight_mask &= !bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } else { + replay_mask &= !bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } else { + polling_mask &= !bit; + } } // All compute observations in this batch are latched before a VM // failure can settle its render peers. Exact successes win first. - for index in 0..self.queues.compute.len() { - let terminal = self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .and_then(|mut queue| queue.take_terminal()); - if let Some((status, error)) = terminal { - status.record(error); - self.settle_render_vm(&status, error, deferred)?; - self.queues.fail_compute_vm(&status, error, deferred)?; + let had_terminal = terminal_mask != 0; + if had_terminal { + for index in 0..self.queues.compute.len() { + let terminal = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .and_then(|mut queue| queue.take_terminal()); + if let Some((status, error)) = terminal { + status.record(error); + self.settle_render_vm(&status, error, deferred)?; + self.queues.fail_compute_vm(&status, error, deferred)?; + } } } - let port = &self.port; - let registry = &mut self.queues; - for mut queue in registry - .compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - { - let busy = !queue.channel_free(); - queue.release_witnessed( - state, - |owner| port.qos_complete(&[owner]), - &mut |event| deferred.push(event), - )?; - freed |= busy && queue.channel_free(); + if witness_mask != 0 || had_terminal { + let port = &self.port; + let registry = &mut self.queues; + for (index, entry) in registry.compute.iter_mut().enumerate() { + let bit = 1u128.checked_shl(index as u32).unwrap_or(0); + if !had_terminal && (witness_mask & bit) == 0 { + continue; + } + let Some(mut queue) = entry.as_mut().and_then(|entry| entry.queue.as_deref_mut()) + else { + continue; + }; + let busy = !queue.channel_free(); + queue.release_witnessed( + state, + |owner| port.qos_complete(&[owner]), + &mut |event| deferred.push(event), + )?; + freed |= busy && queue.channel_free(); + if queue.in_flight() { + in_flight_mask |= bit; + } else { + in_flight_mask &= !bit; + } + if queue.replay_commands() != 0 { + replay_mask |= bit; + } else { + replay_mask &= !bit; + } + if queue.retirement_polling() || queue.pool_release_pending() { + polling_mask |= bit; + } else { + polling_mask &= !bit; + } + } } // Wake only the admission waits this batch can end. The fences gate // scheduler entities alone; their callbacks never take the device mutex. @@ -2085,7 +2205,11 @@ impl super::Firmware { if deferred.pending() != retired { shared.progress.notify(); } - Ok(()) + Ok(ComputeScan { + in_flight: in_flight_mask != 0, + replay: replay_mask != 0, + polling: polling_mask != 0, + }) } } @@ -2144,10 +2268,7 @@ impl Backend { required: super::freelist::ComputeCapacity, deferred: &mut DeferredBatch, ) -> Option { - // M5 compute is a shared-ring submission on the ring M5 render shares: it is published only - // under the device mutex, never through the classic compute ring producer. - if self.context.is_m5() - || packet.completion.sources().is_some() + if packet.completion.sources().is_some() || self.context.render_seen() || packet.cancel_requested() || packet.completion.status().get() != 0 @@ -2172,26 +2293,76 @@ impl Backend { Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } - let mut queue = cell.lock()?; - if !queue.installed() - || queue.spared_pending() - || !queue.pool_fits(required) - || queue.pending_switch_from().is_some() - || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) - || !lease.is_current() - { - return None; - } - let outer = port.reserve_compute(packet.context.policy().priority()).ok()?; - let mut host = DirectHost { - port, - outer: Some(outer), - generation: port.generation(), + let m5 = self.context.is_m5(); + let priority = packet.context.policy().priority(); + // Reuse the M5 outer claim already reserved during prepare_compute() when present and + // matching priority, avoiding a redundant Port::m5_outer lock trip and unused-claim drop + // notification; otherwise reserve before locking the compute cell. + let (mut m5_outer, from_held) = if m5 { + let claimed = { + let mut held = self.outer_compute.lock(); + if held.as_ref().is_some_and(|claim| { + claim.remaining() != 0 && claim.priority() == usize::from(priority) + }) { + held.take() + } else { + None + } + }; + match claimed { + Some(claim) => (Some(claim), true), + None => (Some(port.reserve_m5_compute(priority).ok()?), false), + } + } else { + (None, false) + }; + let result = (|| { + let mut queue = cell.lock()?; + if !queue.installed() + || queue.spared_pending() + || !queue.pool_fits(required) + || queue.pending_switch_from().is_some() + || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) + || !lease.is_current() + { + return None; + } + let outer = if m5 { + None + } else { + Some(port.reserve_compute(priority).ok()?) + }; + let mut host = DirectHost { + port, + outer, + m5_outer: m5_outer.as_mut(), + m5_outer_guard: None, + m5, + generation: port.generation(), + }; + Some(queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event))) + })(); + let outcome = match result { + None => None, + Some(Err(error)) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => { + None + } + Some(result) => Some(result), }; - match queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event)) { - Err(error) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => None, - result => Some(result), + if outcome.is_none() && from_held { + if let Some(claim) = m5_outer.take().filter(|claim| claim.remaining() != 0) { + let mut held = self.outer_compute.lock(); + if !held.as_ref().is_some_and(|existing| existing.remaining() != 0) { + // Replace None or an already-spent claim (whose drop notifies nobody). + *held = Some(claim); + } else { + drop(held); + drop(claim); + } + } } + drop(m5_outer); + outcome } /// Scheduler admission of a compute packet. Shared capacity the packet lacks (a channel, a @@ -2236,7 +2407,31 @@ impl Backend { if !self.context.is_m5() { return None; } - self.shared.state.lock().as_deref().and_then(|firmware| firmware.init.outer_available().ok()) + let lease = self.shared.preparations.try_enter().ok()?; + self.shared.port(&lease)?.outer_domain() + } + + /// M5: holds this owner's compute outer-ring claim through `Port` without taking the device + /// mutex, for a channel already bound and installed. + fn claim_compute_outer_direct(&self, count: u32) -> Result { + let mut held = self.outer_compute.lock(); + if held.as_ref().is_some_and(|claim| claim.remaining() != 0) { + return Ok(true); + } + let Ok(lease) = self.shared.preparations.try_enter() else { + return Ok(true); + }; + let Some(port) = self.shared.port(&lease) else { + return Ok(true); + }; + match port.reserve_m5_outer(self.context.policy().priority(), count) { + Ok(claim) => { + *held = Some(claim); + Ok(true) + } + Err(error) if error == EBUSY => Ok(false), + Err(error) => Err(error), + } } /// M5: holds this owner's claim on the shared work ring for the next compute or render @@ -2259,6 +2454,7 @@ impl Backend { if held.as_ref().is_some_and(|claim| claim.remaining() != 0) { return Ok(true); } + let _m5_outer = firmware.port.m5_outer_lock(); match firmware.init.reserve_outer(self.context.policy().priority(), count) { Ok(claim) => { // Replaces only a spent claim, whose drop notifies nobody. @@ -2285,7 +2481,7 @@ impl Backend { let _scope = (*held) .as_mut() .filter(|claim| claim.remaining() != 0) - .map(|claim| firmware.init.outer_scope(claim)) + .map(|claim| firmware.port.outer_scope(&firmware.init, claim)) .transpose()?; firmware.publish_compute(self.owner, packet.clone(), dependencies, deferred) } @@ -2313,24 +2509,24 @@ impl Backend { // The steady state: this owner's channel is bound and installed. if packet.completion.sources().is_none() { if let Some(cell) = self.direct.lock().clone() { - let bound = cell.lock().is_some_and(|mut queue| { + let bound = cell.lock().and_then(|mut queue| { let bound = queue.installed() && !queue.spared_pending() && queue.pool_fits(required) && matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)); if bound { queue.claim(); + Some(queue.outer_slots()) + } else { + None } - bound }); - if bound { + if let Some(outer_slots) = bound { self.hold_claim(Some(cell)); if !self.context.is_m5() { return Readiness::Ready; } - let state = self.shared.state.lock(); - let Some(firmware) = state.as_deref() else { return Readiness::Ready; }; - return match self.claim_outer(firmware, crate::g17::job::Engine::Compute) { + return match self.claim_compute_outer_direct(outer_slots) { Ok(false) => Readiness::Outer, _ => Readiness::Ready, }; diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 5c6ce67b6c40e..35ddab8134ff5 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -123,7 +123,7 @@ impl Backend { impl job::Backend for Backend { fn creator_cluster_scheduling(&self) -> bool { - true + self.shared.pin_scheduler_cluster() } fn host_producer_waits(&self) -> bool { self.shared.m5_board.is_some_and(|board| !board.g17d_forms() && !board.completion_inputs()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 8619f16377c5b..044b064dda9a4 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -23,6 +23,7 @@ struct Service<'a> { firmware: &'a mut Firmware, deferred: &'a mut DeferredBatch, render_masks: [u64; 2], + compute_scan: Option, settlement_error: Option, } @@ -100,15 +101,16 @@ impl event::Queues for Service<'_> { fn retain_render_completions(&mut self, masks: [u64; 2]) { // Inline timeout and drain callers may discard the worker hints. The // queue owner retains stamps until its borrowed pair returns to scan. - self.firmware.queues.retain_render_completions(masks); - self.render_masks[0] |= masks[0]; - self.render_masks[1] |= masks[1]; + let matched = self.firmware.queues.retain_render_completions(masks); + self.render_masks[0] |= matched[0]; + self.render_masks[1] |= matched[1]; } fn complete_compute(&mut self, masks: [u64; 2]) -> Result { // A batch without a queue identity still observes completions whose // notification was coalesced; identified batches retain QID filtering. let selected = (masks != [0; 2]).then_some(masks); - self.firmware.scan_compute(selected, self.deferred) + self.compute_scan = Some(self.firmware.scan_compute_summary(selected, self.deferred)?); + Ok(()) } } @@ -326,6 +328,8 @@ impl Firmware { /// Drains every role's trace ring, then their statistics rings. The event worker calls this /// after it has signalled the completions of its pass: the reports are not scheduling inputs. + /// While work stays in flight it does so at the housekeeping cadence, and a recovery pass + /// does so before the restart resets the report rings. fn drain_reports(&mut self) { let dev = &self.primary.state.shared.dev; for &role in self.roles() { @@ -340,8 +344,8 @@ impl Firmware { } } - /// A step of the event pass is waiting on the firmware with no event to wake it. - fn runtime_polling(&self, now: u64) -> bool { + /// Non-compute checks of [`Self::runtime_polling`], reused on the single-lock fast path. + fn non_compute_runtime_polling(&self, now: u64) -> bool { self.render_control_backpressured() || self.init.outer_waiting() || self.queues.replay_outer_wait.is_some() @@ -349,6 +353,11 @@ impl Firmware { || self.queues.render.replay_polling() || self.queues.teardown.polling(now) || self.compute_exit_polling(now) + } + + /// A step of the event pass is waiting on the firmware with no event to wake it. + fn runtime_polling(&self, now: u64) -> bool { + self.non_compute_runtime_polling(now) || self .queues .compute @@ -398,10 +407,19 @@ impl Firmware { &mut self, deferred: &mut DeferredBatch, ) -> Result<(event::Pending, [u64; 2])> { + let (pending, masks, _) = self.service_runtime_events_scan(deferred)?; + Ok((pending, masks)) + } + + fn service_runtime_events_scan( + &mut self, + deferred: &mut DeferredBatch, + ) -> Result<(event::Pending, [u64; 2], Option)> { let mut service = Service { firmware: self, deferred, render_masks: [0; 2], + compute_scan: None, settlement_error: None, }; let pending = event::service(&mut service)?; @@ -413,7 +431,7 @@ impl Firmware { shared.preparations.close(); shared.queue_events(); } - Ok((pending, service.render_masks)) + Ok((pending, service.render_masks, service.compute_scan)) } /// Preparation admission is already closed and all builders have joined. @@ -424,6 +442,7 @@ impl Firmware { firmware: self, deferred, render_masks: [0; 2], + compute_scan: None, settlement_error: None, }; let result = recovery::service(&mut service, || { @@ -435,6 +454,7 @@ impl Firmware { .firmware .port .set_generation(service.firmware.recovery.generation()); + service.firmware.port.reset_m5_history(); service.firmware.rings.invalidate_statistics(); let result = result?; // Counted once the restart is classified, so the restart that reaches the limit has @@ -485,26 +505,16 @@ impl crate::g17::Shared { self.stop_runtime(); return; } - let mut deferred = { - let mut state = self.state.lock(); - let Some(firmware) = (*state).as_deref_mut() else { - return; - }; - let Some(deferred) = firmware.queues.worker_deferred.take() else { - drop(state); - self.lose_device_quietly(); - return; - }; - deferred + let Some(mut deferred) = self.worker_deferred.lock().take() else { + self.lose_device_quietly(); + return; }; crate::g17::trace::event(0); let result = self.runtime_event_turn(&mut deferred); deferred.finish(); crate::g17::trace::event(2); self.queue_feed(); - if let Some(firmware) = (*self.state.lock()).as_deref_mut() { - firmware.queues.worker_deferred = Some(deferred); - } + *self.worker_deferred.lock() = Some(deferred); if let Err(error) = result { dev_err!(self.dev.as_ref(), "GPU event service failed: {:?}\n", error); self.lose_device_quietly(); @@ -517,22 +527,68 @@ impl crate::g17::Shared { let requested = self .housekeeping .swap(false, core::sync::atomic::Ordering::AcqRel); - let (recover, masks) = { + let (recover, masks, fast_done) = { let mut state = self.state.lock(); let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - let (pending, masks) = firmware.service_runtime_events(deferred)?; + let (pending, masks, compute_scan) = firmware.service_runtime_events_scan(deferred)?; let recover = pending.recovery || firmware.recovery.pending(); if recover { // Epoch closure and event consumption are serialized with every // publisher. Joining builders must happen after unlocking. self.preparations.close(); } - (recover, masks) + // Steady-state pure-compute completions with work still in flight, no render work + // to observe, no replays, no waiters and housekeeping not yet due finish in this + // single device-mutex hold; fences are signalled right after unlocking. + let mut fast_done = false; + if !recover + && !requested + && !self.crashed.load(core::sync::atomic::Ordering::Acquire) + && masks == [0; 2] + && !firmware.render_observation_needed() + { + if let Some(scan) = compute_scan { + let now = super::now_ns(); + let in_flight = scan.in_flight || firmware.queues.render_in_flight(); + let no_replay = !scan.replay && !firmware.queues.render.replay_parked(); + let no_housekeeping = in_flight + && firmware.queues.teardown.is_empty() + && !self.channels.has_waiters() + && !self.progress.has_waiters() + && !self.queues.has_waiters() + && !self.renders.has_waiters() + && now.saturating_sub( + self.housekeeping_ns + .load(core::sync::atomic::Ordering::Relaxed), + ) < HOUSEKEEPING_NS; + let no_outer_or_grow = + !firmware.init.outer_waiting() && !firmware.render_grow_ready(); + if no_replay && no_housekeeping && no_outer_or_grow { + if let Some(delay) = firmware.idle_check(now, true)? { + self.queue_idle(delay); + } + let polling = scan.polling || firmware.non_compute_runtime_polling(now); + if polling { + self.queue_poll(); + } else if channel::Events::pending(&firmware.init, Role::Primary)? + || (firmware.secondary.is_some() + && channel::Events::pending(&firmware.init, Role::Secondary)?) + { + self.queue_event_records(); + } + fast_done = true; + } + } + } + (recover, masks, fast_done) }; deferred.finish(); crate::g17::trace::event(1); + if fast_done { + return Ok(()); + } if recover { self.preparations .wait_drained_until(super::now_ns().saturating_add(super::WORK_RING_WAIT_NS))?; @@ -544,9 +600,12 @@ impl crate::g17::Shared { if self.crashed.load(core::sync::atomic::Ordering::Acquire) { return Err(EIO); } - // The completions above are signalled; the reports that arrived with them come after. - firmware.drain_reports(); + // Capture pre-recovery trace/statistics reports before firmware restart resets the + // report rings, matching the non-throttled post-signal ordering. + let mut reports_drained = false; if recover { + firmware.drain_reports(); + reports_drained = true; firmware.service_runtime_recovery(deferred)?; if !firmware.recovery.pending() && !self.sleep_gate.load(core::sync::atomic::Ordering::Acquire) @@ -563,15 +622,18 @@ impl crate::g17::Shared { // Publication may service events but must never recurse into replay. firmware.replay_compute(deferred)?; firmware.replay_render(deferred)?; - drop(state); - self.observe_renders(masks, deferred)?; - let mut state = self.state.lock(); + // Skip dropping and re-acquiring the device mutex around a no-op render observation. + if masks != [0; 2] || firmware.render_observation_needed() { + drop(state); + self.observe_renders(masks, deferred)?; + state = self.state.lock(); + if self.crashed.load(core::sync::atomic::Ordering::Acquire) { + return Err(EIO); + } + } let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - if self.crashed.load(core::sync::atomic::Ordering::Acquire) { - return Err(EIO); - } let now = super::now_ns(); let compute = firmware .queues @@ -582,11 +644,12 @@ impl crate::g17::Shared { .any(|queue| queue.in_flight()); let in_flight = compute || firmware.queues.render_in_flight(); let idle = firmware.idle_check(now, in_flight)?; - // Expiries, drained pairs, exits, pool and heap trimming and teardown give back what - // retirement freed; a completion needs none of them to retire or to signal. While work - // is in flight and nothing waits for capacity, a pass for firmware records alone skips - // them. Any requested pass, recovery, teardown, a waiter, the last retirement and, at - // the latest, the first pass after HOUSEKEEPING_NS run them all. + // Expiries, drained pairs, exits, pool and heap trimming, teardown and M5 report + // drains give back what retirement freed; a completion needs none of them to retire + // or to signal. While work is in flight and nothing waits for capacity, a pass for + // firmware records alone skips them. Any requested pass, recovery, teardown, a waiter, + // the last retirement and, at the latest, the first pass after HOUSEKEEPING_NS run + // them all. let housekeeping = requested || recover || !in_flight @@ -608,6 +671,11 @@ impl crate::g17::Shared { if housekeeping { self.housekeeping_ns .store(now, core::sync::atomic::Ordering::Relaxed); + if !reports_drained { + // The completions above are signalled; reports are throttled to the + // housekeeping cadence while work stays in flight. + firmware.drain_reports(); + } if !firmware.recovery.pending() { lingers = firmware.expire_render_lingers(now)?; } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index 0a0a527ac1bf8..f8c1cffb59dcf 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -876,6 +876,23 @@ impl Host<'_> { } } } +/// Encodes the G17 render mailbox doorbell (0x83, priority in bits 3:2, pipe in bits 1:0). +/// +/// Firmware queue contract across both locked and direct render publishers: +/// - Non-M5 G17 submits render pairs to the dedicated tiling/fragment rings and rings pipe 0. +/// - M5 Pro/Max/Ultra (!J813_FORMS) submits render pairs into the shared compute work ring paired +/// with host-port gating writes and submission-history accounting, and rings pipe 2. +/// - J813 (J813_FORMS, common 26A428 firmware) uses the mailbox-only G17P queue forms (no +/// host-port or KSM register writes) and rings pipe 0. +fn render_doorbell_message(m5: bool, priority: u8) -> u64 { + let pipe = if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed) { + 2 + } else { + 0 + }; + (0x83 << crate::g17::MSG_TYPE_SHIFT) | u64::from(priority) << 2 | pipe +} + impl crate::g17::queue::render::Host for Host<'_> { fn generation(&self) -> u64 { self.firmware.recovery.generation() @@ -1039,11 +1056,10 @@ impl crate::g17::queue::render::Host for Host<'_> { self.firmware.bridge.regs.g17_core_power() }); } - let result = self.firmware.primary.notify( - (0x83 << crate::g17::MSG_TYPE_SHIFT) - | u64::from(priority) << 2 - | if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed) { 2 } else { 0 }, - ); + let result = self + .firmware + .primary + .notify(render_doorbell_message(m5, priority)); if result.is_err() { self.firmware.primary.state.shared.lose_device_quietly(); } @@ -1506,13 +1522,15 @@ impl Registry { ) }) } - pub(in crate::g17) fn retain_render_completions(&mut self, masks: [u64; 2]) { + pub(in crate::g17) fn retain_render_completions(&mut self, masks: [u64; 2]) -> [u64; 2] { + let mut matched = [0u64; 2]; for entry in self.render.entries.iter_mut().flatten() { let mut hit = false; for id in entry.reservation.ids { let qid = usize::from(id.qid()); let bit = masks[qid / 64] & (1u64 << (qid % 64)); entry.event_masks[qid / 64] |= bit; + matched[qid / 64] |= bit; hit |= bit != 0; } // Event passes skip a pair while preparation, growth or an @@ -1523,6 +1541,7 @@ impl Registry { entry.missed_event = true; } } + matched } pub(in crate::g17) fn render_needs_rescan(&self) -> bool { self.render.entries.iter().flatten().any(|entry| { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index e87fc21fe61e1..682dbdd6aaaaa 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -14,7 +14,7 @@ use super::super::{Backend, DeferredBatch}; use crate::g17::{ job::Packet, object::Allocator, - port::{Port, RenderRoom}, + port::{M5RenderRoom, Port, RenderRoom}, queue::render::{Pair, PublicationLease, RenderAddresses}, }; use core::sync::atomic::Ordering; @@ -33,13 +33,20 @@ pub(in crate::g17::runtime) struct Loan { uat: Arc, } +enum DirectTarget { + Legacy(RenderRoom), + M5(M5RenderRoom), +} + /// Publication host of a lent pair. Registration, first-publication and /// growth paths never run here: the loan requires an installed, registered /// graph that needs no growth. struct DirectHost<'a> { port: &'a Port, render: &'a MutexGuard<'a, ()>, - room: RenderRoom, + m5_outer: Option>>, + m5_claim: Option<&'a mut crate::g17::initdata::OuterClaim>, + target: DirectTarget, generation: u64, activation: Option<(u16, u64)>, } @@ -83,11 +90,36 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { commit: impl FnOnce() -> Result, late_tiling: impl FnOnce(), ) -> Result<[u32; 2]> { - if priority != self.room.priority() { - return Err(EINVAL); + match &self.target { + DirectTarget::Legacy(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + self.port.write_render_pair( + self.render, + room, + fragment, + tiling, + commit, + late_tiling, + ) + } + DirectTarget::M5(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; + self.port.write_m5_render_pair( + self.render, + m5_outer, + room, + fragment, + tiling, + commit, + late_tiling, + ) + } } - self.port - .write_render_pair(self.render, &self.room, fragment, tiling, commit, late_tiling) } fn publish_configuration_pair( &mut self, @@ -96,7 +128,7 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { _tiling: &crate::g17::fw::channels::WorkSlot, _prepare: impl FnOnce(), ) -> Result { - // Only M5 publishes configuration pairs, never on this path. + // Cold-install configuration pairs never run on an already-registered pair. Err(EINVAL) } fn activate_render_pool(&mut self, id: u16, generation: u64) -> Result { @@ -112,15 +144,34 @@ impl crate::g17::queue::render::Host for DirectHost<'_> { _tiling: &crate::g17::fw::channels::WorkSlot, next: [u32; 2], ) -> Result { - if priority != self.room.priority() { - return Err(EINVAL); + match &self.target { + DirectTarget::Legacy(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + self.port.expose_render_pair(self.render, room, next) + } + DirectTarget::M5(room) => { + if priority != room.priority() { + return Err(EINVAL); + } + let m5_outer = self.m5_outer.as_ref().ok_or(EIO)?; + let claim = self.m5_claim.as_deref_mut().ok_or(EIO)?; + self.port + .expose_m5_render_pair(self.render, m5_outer, room, claim, next) + } } - self.port.expose_render_pair(self.render, &self.room, next) } - /// Pipe 0 (tiling) in bits 1:0, priority class in bits 3:2. + /// Rings the shared render doorbell contract ([`super::render_doorbell_message`]). fn notify_render(&mut self, priority: u8) -> Result { - self.port - .notify((0x83 << crate::g17::MSG_TYPE_SHIFT) | u64::from(priority) << 2) + let m5 = matches!(self.target, DirectTarget::M5(_)); + if m5 { + let geometry = self.m5_outer.as_mut().ok_or(EIO)?; + if let Err(error) = self.port.note_m5_submission_history_locked(geometry, 2) { + pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); + } + } + self.port.notify(super::render_doorbell_message(m5, priority)) } fn note_submission(&mut self) -> Result { // Counted, with full effort witnessed, before the pair was lent. @@ -178,13 +229,24 @@ impl crate::g17::Firmware { let qids = pair.qids(); let pool = pair.pool().clone(); let buffer_id = pair.buffer_id(); + // An M5 PB token is bound to the hardware context and PB state it names. + let buffer_context = pair + .m5_pb_state_va() + .map(|pb_va| (packet.context.id(), pb_va)); let addresses = RenderAddresses { stamps: [ self.init.stamp_addresses(qids[0])?, self.init.stamp_addresses(qids[1])?, ], }; - let (buffer, buffer_token) = self.queues.buffers.acquire_owner(buffer_id)?; + let (buffer, buffer_token) = match buffer_context { + Some((context, pb_va)) => { + self.queues + .buffers + .acquire_owner_bound(buffer_id, context, pb_va)? + } + None => self.queues.buffers.acquire_owner(buffer_id)?, + }; let preparation = match self.queues.render.pools.prepare(&self.init, &pool) { Ok(preparation) => preparation, Err(error) => { @@ -199,7 +261,7 @@ impl crate::g17::Firmware { let lease = PublicationLease { free_list_generation: preparation.generation, buffer_token, - buffer_context: None, + buffer_context: buffer_context.map(|(context, _)| context), }; let pair = match self.queues.render.take_pair(slot, owner, packet) { Ok(pair) => pair, @@ -285,10 +347,8 @@ impl Backend { deferred: &mut DeferredBatch, ) -> Option { // A compute prefix needs the compute queue's state; leave it to the - // device-mutex path. M5 renders publish through the device mutex - // only: their host-port transaction is part of the publication. - if packet.context.is_m5() - || packet.is_published() + // device-mutex path. + if packet.is_published() || packet.cancel_requested() || packet.completion.status().get() != 0 || packet.order.wait_through[1].unwrap_or(0) != 0 @@ -315,6 +375,7 @@ impl Backend { Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } + let m5 = packet.context.is_m5(); let priority = packet.context.policy().priority(); let generation = port.generation(); let dev = self.shared.drm().ok()?; @@ -331,6 +392,10 @@ impl Backend { } }; let mut activation = None; + let mut recovery_started = false; + // Declared outside the publication closure so any unspent M5 outer claim drops + // after `m5_outer` and `render` are released (dropping an unspent claim can wake fences). + let mut m5_claim = None; let result = (|| { let pair = loan.pair.as_mut().ok_or(EIO)?; let alloc = Allocator { @@ -342,7 +407,14 @@ impl Backend { if !lease.is_current() { return Err(EBUSY); } - let room = port.observe_render_room(&render, priority)?.ok_or(EBUSY)?; + let m5_outer = m5.then(|| port.m5_outer_lock()); + let target = if let Some(guard) = m5_outer.as_ref() { + let (room, claim) = port.reserve_m5_render_locked(guard, priority)?; + m5_claim = Some(claim); + DirectTarget::M5(room) + } else { + DirectTarget::Legacy(port.observe_render_room(&render, priority)?.ok_or(EBUSY)?) + }; let mut dependencies = pair.own_dependencies(self.owner, packet)?; if let Some(footprint) = packet.footprint.as_ref() { dependencies.hazard_count = self.admission.publication_barriers( @@ -356,7 +428,9 @@ impl Backend { let mut host = DirectHost { port, render: &render, - room, + m5_outer, + m5_claim: m5_claim.as_mut(), + target, generation, activation: None, }; @@ -368,13 +442,22 @@ impl Backend { &mut |event| deferred.push(event), ); activation = host.activation; + drop(host); result?; - // A recovery that started meanwhile may have discarded the commands. - if port.generation() != generation || port.recovery_state()? != 0 { + // A generation advance while lent means the commands belong to a closed epoch. + if port.generation() != generation { return Err(EIO); } + // If recovery started during publication while our preparation lease still held + // the same generation, return_render() hands the published pair back before lease + // drops so the existing recovery pass settles or replays it once without failing + // an unrelated client's VM. + if port.recovery_state()? != 0 { + recovery_started = true; + } Ok(()) })(); + drop(m5_claim); let returned = { let mut state = self.shared.state.lock(); match (*state).as_deref_mut() { @@ -394,6 +477,9 @@ impl Backend { }; self.shared.note_changed(); drop(lease); + if recovery_started { + self.shared.queue_events(); + } if let Err(error) = returned { self.shared.lose_device_quietly(); return Some(Err(error)); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs index 57543be54e835..63bae4052b14e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/observe.rs @@ -8,6 +8,32 @@ use core::sync::atomic::Ordering; use kernel::{prelude::*, sync::Arc}; impl crate::g17::Firmware { + /// Whether `observe_renders` has any deferred settlement or in-flight render observation + /// pending. Pure compute passes can skip dropping and re-acquiring the device mutex when false. + pub(in crate::g17) fn render_observation_needed(&self) -> bool { + for slot in 1..self.queues.render.entries.len() { + let Some(entry) = self.queues.render.entries[slot].as_ref() else { + continue; + }; + let Some(pair) = entry.pair.as_ref() else { + continue; + }; + if entry.pending_error.is_some() || entry.pending_timeout || entry.closed { + return true; + } + if !self.recovery.pending() + && entry.preparing.is_none() + && !entry.growing + && pair.published_in_flight() + && (crate::g17::queue::render::completion_noted(pair.qids(), entry.event_masks) + || pair.stamp_waiting()) + { + return true; + } + } + false + } + /// The first slot from `start` whose pair has news to observe: published work in flight, the /// fragment queue's notification seen (`completion_noted`), and an observation the pair accepts. fn next_render_observation(&mut self, start: usize) -> Result> { @@ -83,7 +109,7 @@ impl crate::g17::Shared { let Some(firmware) = (*state).as_deref_mut() else { return Ok(()); }; - firmware.queues.retain_render_completions(masks); + let _ = firmware.queues.retain_render_completions(masks); // Returned preparers can have deferred a VM failure or timeout. // Only this full worker collector runs their final observations. for slot in 1..firmware.queues.render.entries.len() { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 406497094979e..c5e2f0b9348fa 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -994,7 +994,7 @@ impl super::super::Backend { let _scope = (*held) .as_mut() .filter(|claim| claim.remaining() != 0) - .map(|claim| firmware.init.outer_scope(claim)) + .map(|claim| firmware.port.outer_scope(&firmware.init, claim)) .transpose()?; firmware.publish_render(self.owner, slot, packet, deferred) })(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index dda6ebf5b9eb7..0954496803d9a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -761,6 +761,7 @@ impl crate::g17::Firmware { // time and attachment overlaps are ordered by publication order. let port = self.port.clone(); let _render = port.render_lock(); + let _m5_outer = self.init.is_m5().then(|| port.m5_outer_lock()); // Both outer destinations must have room before pool accounting or // either inner queue becomes visible. On M5 both are the shared compute ring: one // check covers the pair, and the pair is written against its cursors (this hold diff --git a/tools/asahi/g17-m5-direct-compute-tests.py b/tools/asahi/g17-m5-direct-compute-tests.py new file mode 100755 index 0000000000000..0f3f7cd50f60a --- /dev/null +++ b/tools/asahi/g17-m5-direct-compute-tests.py @@ -0,0 +1,259 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 direct compute outer-ring credits and post-signal report ordering. + +Compiles the real `Credits`, `OuterClaim`, `OuterScope`, and `free` implementation +from `drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs` on the host and tests: +1. Mixed render (2-slot) and compute (1-slot) reservations/consumptions across + `WORK_RING_SLOTS` ring wrap and exact capacity boundaries. +2. Queued claims held across a generation change and `OuterScope` (locked render / + recovery), verifying waiters wake on drop and direct consumption never debits + `OuterScope`'s `published[]` counter. +3. Multi-threaded contention between concurrent direct compute reservations/consumptions + and periodic locked `OuterScope` transitions. +4. Structural verification of `runtime_event_turn()` in `runtime/events.rs`: + completions signal (`batch.finish()`) before report drains, recovery drains + reports before `service_runtime_recovery()` regardless of `HOUSEKEEPING_NS`, + and steady-state passes throttle report drains without double-draining on recovery. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + outer_src = (G17 / 'initdata/outer_credit.rs').read_text() + events_src = (G17 / 'runtime/events.rs').read_text() + + turn = item(events_src, 'fn runtime_event_turn(') + if mutation == 'no-pre-recovery-drain': + turn = turn.replace( + 'firmware.drain_reports();\n reports_drained = true;\n' + ' firmware.service_runtime_recovery(deferred)?;', + 'firmware.service_runtime_recovery(deferred)?;', + 1, + ) + + # Verify report-drain ordering contract in production runtime_event_turn(). + ordering_ok = ordered_ok( + turn, + 'deferred.finish();', + 'let mut reports_drained = false;', + 'firmware.drain_reports();\n reports_drained = true;', + 'firmware.service_runtime_recovery(deferred)?;', + 'if housekeeping {', + 'if !reports_drained {', + ) + + # Strip kernel imports, inner doc comments, and kunit module from outer_credit.rs for host compilation. + kunit_idx = outer_src.index('#[kernel::macros::kunit_tests(') + prod = outer_src[:kunit_idx] + prod = re.sub(r'^//!.*$', '', prod, flags=re.M) + prod = re.sub(r'^use crate::g17::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use core::sync::atomic::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use kernel::.*$', '', prod, flags=re.M) + prod = prod.replace('Arc::new(', 'HostArc::new(') + prod = prod.replace(', GFP_KERNEL)?', ')?') + prod = prod.replace('pub(crate)', 'pub') + prod = prod.replace('pub(super)', 'pub') + + if mutation == 'direct-debits-published': + prod = prod.replace( + 'self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel);', + 'self.reserved[claim.priority].fetch_sub(count, Ordering::AcqRel);\n' + ' self.published[claim.priority].fetch_add(u64::from(count), Ordering::AcqRel);', + 1, + ) + elif mutation == 'scope-allows-reserve': + prod = prod.replace( + 'if self.scoped.load(Ordering::Acquire) { return Err(EBUSY); }', + '', + 1, + ) + + return f''' +use std::sync::{{Arc, atomic::{{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const WORK_RING_SLOTS: u32 = 128; +type Result = std::result::Result; + +struct HostArc; +impl HostArc {{ + fn new(v: T) -> Result> {{ Ok(Arc::new(v)) }} +}} + +pub struct Availability {{ + waiters: AtomicUsize, + notifications: AtomicUsize, +}} +impl Availability {{ + pub fn new() -> Result> {{ + Ok(Arc::new(Self {{ + waiters: AtomicUsize::new(0), + notifications: AtomicUsize::new(0), + }})) + }} + pub fn has_waiters(&self) -> bool {{ self.waiters.load(Ordering::Acquire) != 0 }} + pub fn notify(&self) {{ self.notifications.fetch_add(1, Ordering::AcqRel); }} + pub fn notifications(&self) -> usize {{ self.notifications.load(Ordering::Acquire) }} +}} + +{prod} + +fn test_mixed_wrap_and_generation_change() {{ + let credits = Credits::new().unwrap(); + let n = WORK_RING_SLOTS; + let mut ca = n - 6; + let mut cb = n - 6; + let mut prod_idx = n - 2; + + let mut render_claim = credits.reserve(2, 2, [ca, cb, prod_idx]).unwrap(); + let mut comp_a = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut comp_a).unwrap(); + prod_idx = (prod_idx + 1) % n; + + let mut comp_b = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut comp_b).unwrap(); + prod_idx = (prod_idx + 1) % n; + assert_eq!(prod_idx, 0); + + let rem = credits.capacity(2, [ca, cb, prod_idx]).unwrap(); + let filler = credits.reserve(2, rem - 1, [ca, cb, prod_idx]).unwrap(); + assert_eq!(credits.capacity(2, [ca, cb, prod_idx]).unwrap(), 1); + assert_eq!(credits.reserve(2, 2, [ca, cb, prod_idx]).err(), Some(EBUSY)); + let mut edge = credits.reserve(2, 1, [ca, cb, prod_idx]).unwrap(); + credits.consume_direct(&mut edge).unwrap(); + prod_idx = (prod_idx + 1) % n; + assert_eq!(credits.capacity(2, [ca, cb, prod_idx]).unwrap(), 0); + drop(filler); + + ca = 1; + cb = 1; + let wrapped = [ca, cb, prod_idx]; + assert!(credits.progressed(2, wrapped).unwrap()); + + // Hold a queued compute claim across OuterScope + generation change. + let queued_comp = credits.reserve(2, 1, wrapped).unwrap(); + let mut pre_direct = credits.reserve(2, 1, wrapped).unwrap(); + let notes_before = credits.available().notifications(); + {{ + let _scope = credits.scope(&mut render_claim).unwrap(); + assert!(credits.is_scoped()); + assert_eq!(credits.reserve(2, 1, wrapped).err(), Some(EBUSY)); + // A direct compute claim already reserved before OuterScope must not debit OuterScope. + credits.consume_direct(&mut pre_direct).unwrap(); + }} + assert!(!credits.is_scoped()); + assert_eq!(render_claim.remaining(), 2, "direct compute must not debit OuterScope"); + assert_eq!(credits.counter(2).unwrap().load(Ordering::Acquire), 0); + + // Generation changed: dropping the queued compute claim restores its credit and wakes waiters. + drop(queued_comp); + assert!(credits.available().notifications() > notes_before); + drop(render_claim); + assert_eq!(credits.capacity(2, wrapped).unwrap(), n - 1); +}} + +fn test_concurrent_direct_and_scoped() {{ + let credits = Credits::new().unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let mut threads = Vec::new(); + for _ in 0..4 {{ + let c = credits.clone(); + let s = stop.clone(); + threads.push(std::thread::spawn(move || {{ + let mut iters = 0u32; + while !s.load(Ordering::Acquire) && iters < 2000 {{ + if let Ok(mut claim) = c.reserve(1, 1, [0, 0, 0]) {{ + if iters % 5 == 0 {{ + drop(claim); + }} else {{ + c.consume_direct(&mut claim).unwrap(); + }} + }} + iters += 1; + }} + }})); + }} + for _ in 0..200 {{ + if let Ok(mut render_claim) = credits.reserve(1, 2, [0, 0, 0]) {{ + let mut scoped = false; + if let Ok(scope) = credits.scope(&mut render_claim) {{ + assert_eq!(credits.reserve(1, 1, [0, 0, 0]).err(), Some(EBUSY)); + credits.counter(1).unwrap().fetch_add(2, Ordering::AcqRel); + drop(scope); + scoped = true; + }} + if scoped {{ + assert_eq!(render_claim.remaining(), 0); + }} + }} + }} + stop.store(true, Ordering::Release); + for t in threads {{ + t.join().unwrap(); + }} + assert_eq!(credits.capacity(1, [0, 0, 0]).unwrap(), WORK_RING_SLOTS - 1); +}} + +fn main() {{ + assert!({str(ordering_ok).lower()}, "runtime_event_turn must drain reports post-signal and pre-recovery"); + test_mixed_wrap_and_generation_change(); + test_concurrent_direct_and_scoped(); + println!("PASS g17-m5-direct-compute-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['no-pre-recovery-drain', + 'direct-debits-published', + 'scope-allows-reserve']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-dc-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-multiqueue-contention-tests.py b/tools/asahi/g17-m5-multiqueue-contention-tests.py new file mode 100755 index 0000000000000..43b34c9e056a2 --- /dev/null +++ b/tools/asahi/g17-m5-multiqueue-contention-tests.py @@ -0,0 +1,401 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 multi-queue cluster pinning and outer-credit locking. + +Compiles the real `Credits`, `OuterClaim`, `OuterScope`, and `free` implementation +from `drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs` on the host and tests: +1. Tight-ring multi-threaded serialization of `claim_outer()` (`reserve` under + `Port::m5_outer`), `PortOuterScope` (entry and `Drop` under `Port::m5_outer`), + and concurrent direct compute/render reservations and consumptions — verifying + zero ring overcommits, zero `EIO`, and exact credit accounting. +2. Structural verification of the production G17 M5 sources: + - `Shared::new()` leaves single-die M5 schedulers unrestricted + (`pin_scheduler_cluster: !m5 || id.num_dies > 1`). + - `Backend::claim_outer()` holds `firmware.port.m5_outer_lock()` around + `firmware.init.reserve_outer()`. + - `Backend::publish_claimed()` and `runtime/render/prepare.rs` enter + `OuterScope` via `firmware.port.outer_scope(&firmware.init, claim)`. + - `Port::outer_scope()` and `Drop for PortOuterScope` serialize both scope + entry and exit under `Port::m5_outer`. + - `Backend::compute_direct()` reuses a matching `self.outer_compute` claim and + restores any unspent claim back into `self.outer_compute` outside + `cell.lock()` when returning `None` to fall back to the device-mutex path. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + if source.count(part) != 1: + return False + idx = source.index(part) + if idx <= at: + return False + at = idx + return True + + +def build_harness(mutation=None): + outer_src = (G17 / 'initdata/outer_credit.rs').read_text() + port_src = (G17 / 'port.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + prepare_src = (G17 / 'runtime/render/prepare.rs').read_text() + mod_src = (G17 / 'mod.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + + claim_outer = item(runtime_src, 'fn claim_outer(') + publish_claimed = item(runtime_src, 'fn publish_claimed(') + compute_direct = item(runtime_src, 'fn compute_direct(') + port_outer_scope = item(port_src, 'pub(super) fn outer_scope<') + port_outer_scope_drop = item(port_src, 'impl Drop for PortOuterScope<') + creator_cluster = item(backend_src, 'fn creator_cluster_scheduling(') + + if mutation == 'unlocked-claim-outer': + claim_outer = claim_outer.replace( + 'let _m5_outer = firmware.port.m5_outer_lock();', + '', + 1, + ) + elif mutation == 'raw-compute-scope': + publish_claimed = publish_claimed.replace( + 'firmware.port.outer_scope(&firmware.init, claim)', + 'firmware.init.outer_scope(claim)', + 1, + ) + elif mutation == 'raw-render-scope': + prepare_src = prepare_src.replace( + 'firmware.port.outer_scope(&firmware.init, claim)', + 'firmware.init.outer_scope(claim)', + 1, + ) + elif mutation == 'unlocked-scope-drop': + port_outer_scope_drop = port_outer_scope_drop.replace( + 'let _m5_outer = self.port.m5_outer_lock();', + '', + 1, + ) + elif mutation == 'drop-direct-claim-on-fallback': + compute_direct = compute_direct.replace( + 'if outcome.is_none() && from_held {', + 'if false {', + 1, + ) + elif mutation == 'pin-single-die': + mod_src = mod_src.replace( + 'pin_scheduler_cluster: !m5 || id.num_dies > 1,', + 'pin_scheduler_cluster: true,', + 1, + ) + + claim_outer_ok = ordered_ok( + claim_outer, + 'let _m5_outer = firmware.port.m5_outer_lock();', + 'firmware.init.reserve_outer(', + ) + publish_claimed_ok = ( + 'firmware.port.outer_scope(&firmware.init, claim)' in publish_claimed + and 'firmware.init.outer_scope(' not in publish_claimed + ) + render_scope_ok = ( + 'firmware.port.outer_scope(&firmware.init, claim)' in prepare_src + and 'firmware.init.outer_scope(' not in prepare_src + ) + port_scope_ok = ( + ordered_ok( + port_outer_scope, + 'let _m5_outer = self.m5_outer.lock();', + 'init.outer_scope(claim)?', + ) + and ordered_ok( + port_outer_scope_drop, + 'let _m5_outer = self.port.m5_outer_lock();', + 'drop(scope);', + ) + ) + # Verify compute_direct reuses self.outer_compute before cell.lock() and restores any + # unspent held claim back into self.outer_compute AFTER the cell.lock() closure exits. + direct_restore_ok = ( + compute_direct.count('let mut held = self.outer_compute.lock();') == 2 + and ordered_ok( + compute_direct, + 'held.take()', + 'let result = (|| {', + 'let mut queue = cell.lock()?;', + '})();', + 'if outcome.is_none() && from_held {', + '*held = Some(claim);', + ) + and compute_direct.index('let mut held = self.outer_compute.lock();') + < compute_direct.index('let result = (|| {') + and compute_direct.rindex('let mut held = self.outer_compute.lock();') + > compute_direct.index('if outcome.is_none() && from_held {') + ) + cluster_pin_ok = ( + 'pin_scheduler_cluster: !m5 || id.num_dies > 1,' in mod_src + and 'self.shared.pin_scheduler_cluster()' in creator_cluster + ) + + kunit_idx = outer_src.index('#[kernel::macros::kunit_tests(') + prod = outer_src[:kunit_idx] + prod = re.sub(r'^//!.*$', '', prod, flags=re.M) + prod = re.sub(r'^use crate::g17::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use core::sync::atomic::.*$', '', prod, flags=re.M) + prod = re.sub(r'^use kernel::.*$', '', prod, flags=re.M) + prod = prod.replace('Arc::new(', 'HostArc::new(') + prod = prod.replace(', GFP_KERNEL)?', ')?') + prod = prod.replace('pub(crate)', 'pub') + prod = prod.replace('pub(super)', 'pub') + + return f''' +use std::sync::{{Arc, Mutex, atomic::{{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const WORK_RING_SLOTS: u32 = 128; +type Result = std::result::Result; + +struct HostArc; +impl HostArc {{ + fn new(v: T) -> Result> {{ Ok(Arc::new(v)) }} +}} + +pub struct Availability {{ + waiters: AtomicUsize, + notifications: AtomicUsize, +}} +impl Availability {{ + pub fn new() -> Result> {{ + Ok(Arc::new(Self {{ + waiters: AtomicUsize::new(0), + notifications: AtomicUsize::new(0), + }})) + }} + pub fn has_waiters(&self) -> bool {{ self.waiters.load(Ordering::Acquire) != 0 }} + pub fn notify(&self) {{ self.notifications.fetch_add(1, Ordering::AcqRel); }} + pub fn notifications(&self) -> usize {{ self.notifications.load(Ordering::Acquire) }} +}} + +{prod} + +struct RingState {{ + consumer: u32, + producer: u32, +}} + +impl RingState {{ + fn cursors(&self) -> [u32; 3] {{ + [self.consumer, self.consumer, self.producer] + }} + fn advance_producer(&mut self, count: u32) {{ + for _ in 0..count {{ + let next = (self.producer + 1) % WORK_RING_SLOTS; + assert_ne!(next, self.consumer, "outer ring overcommitted past consumer"); + self.producer = next; + }} + }} + fn consume_if_needed(&mut self, keep_free: u32) {{ + while free(self.cursors()).unwrap() < keep_free {{ + assert_ne!(self.consumer, self.producer); + self.consumer = (self.consumer + 1) % WORK_RING_SLOTS; + }} + }} +}} + +struct HostPortScope<'a> {{ + scope: Option>, + m5_outer: Arc>, +}} + +impl Drop for HostPortScope<'_> {{ + fn drop(&mut self) {{ + if let Some(scope) = self.scope.take() {{ + let _guard = self.m5_outer.lock().unwrap(); + drop(scope); + }} + }} +}} + +fn test_serialized_tight_ring_contention() {{ + let credits = Credits::new().unwrap(); + // Start with only 4 free slots so any race between claim_outer, reserve_m5_outer, + // and OuterScope entry/drop immediately overcommits or trips EIO. + let m5_outer = Arc::new(Mutex::new(RingState {{ + consumer: 5, + producer: 0, + }})); + let stop = Arc::new(AtomicBool::new(false)); + let mut threads = Vec::new(); + + for tid in 0..4u32 {{ + let c = credits.clone(); + let lock = m5_outer.clone(); + let s = stop.clone(); + threads.push(std::thread::spawn(move || {{ + let mut iters = 0u32; + while !s.load(Ordering::Acquire) && iters < 3000 {{ + let reserved = {{ + let mut ring = lock.lock().unwrap(); + ring.consume_if_needed(4); + if c.is_scoped() {{ + Err(EBUSY) + }} else {{ + c.reserve(1, 1, ring.cursors()) + }} + }}; + if let Ok(mut claim) = reserved {{ + if (iters + tid) % 4 == 0 {{ + // Simulate compute_direct fallback: drop unspent claim outside m5_outer. + drop(claim); + }} else {{ + let mut ring = lock.lock().unwrap(); + ring.advance_producer(1); + c.consume_direct(&mut claim).unwrap(); + }} + }} + iters += 1; + }} + }})); + }} + + // Device-mutex publisher: claim_outer() + PortOuterScope entry/drop all serialized on m5_outer. + for iter in 0..400u32 {{ + let claim = {{ + let mut ring = m5_outer.lock().unwrap(); + ring.consume_if_needed(4); + credits.reserve(1, 2, ring.cursors()) + }}; + if let Ok(mut render_claim) = claim {{ + let mut scoped = false; + {{ + let scope = {{ + let _guard = m5_outer.lock().unwrap(); + credits.scope(&mut render_claim).map(|scope| HostPortScope {{ + scope: Some(scope), + m5_outer: m5_outer.clone(), + }}) + }}; + if let Ok(scope) = scope {{ + if iter % 3 != 0 {{ + let mut ring = m5_outer.lock().unwrap(); + assert!(credits.capacity(1, ring.cursors()).unwrap() >= 2); + ring.advance_producer(2); + credits.counter(1).unwrap().fetch_add(2, Ordering::AcqRel); + }} + drop(scope); + scoped = true; + }} + }} + if scoped {{ + if iter % 3 != 0 {{ + assert_eq!(render_claim.remaining(), 0); + }} else {{ + assert_eq!(render_claim.remaining(), 2); + }} + }} + drop(render_claim); + }} + }} + + stop.store(true, Ordering::Release); + for t in threads {{ + t.join().unwrap(); + }} + let ring = m5_outer.lock().unwrap(); + let expected = free(ring.cursors()).unwrap(); + assert_eq!(credits.capacity(1, ring.cursors()).unwrap(), expected); +}} + +fn test_fallback_preserves_claim_without_spurious_notify() {{ + let credits = Credits::new().unwrap(); + let cursors = [0, 0, 0]; + let claim = credits.reserve(1, 1, cursors).unwrap(); + let notes_before = credits.available().notifications(); + + // Simulate compute_direct taking held claim and restoring it on None fallback. + let mut held: Option = Some(claim); + let mut m5_outer = held.take(); + assert!(held.is_none()); + let outcome: Option = None; + if outcome.is_none() {{ + if let Some(c) = m5_outer.take().filter(|c| c.remaining() != 0) {{ + if !held.as_ref().is_some_and(|e| e.remaining() != 0) {{ + held = Some(c); + }} + }} + }} + drop(m5_outer); + assert!(held.is_some()); + assert_eq!(held.as_ref().unwrap().remaining(), 1); + assert_eq!(credits.available().notifications(), notes_before); + + // Subsequent slow-path publication consumes the restored claim cleanly. + let mut c = held.take().unwrap(); + credits.consume_direct(&mut c).unwrap(); + assert_eq!(c.remaining(), 0); + drop(c); + assert_eq!(credits.available().notifications(), notes_before); +}} + +fn main() {{ + assert!({str(claim_outer_ok).lower()}, "claim_outer must hold Port::m5_outer around reserve_outer"); + assert!({str(publish_claimed_ok).lower()}, "publish_claimed must use Port::outer_scope"); + assert!({str(render_scope_ok).lower()}, "render/prepare.rs must use Port::outer_scope"); + assert!({str(port_scope_ok).lower()}, "Port::outer_scope and PortOuterScope::drop must hold Port::m5_outer"); + assert!({str(direct_restore_ok).lower()}, "compute_direct must restore unspent m5_outer claim on None fallback outside cell.lock()"); + assert!({str(cluster_pin_ok).lower()}, "single-die M5 must leave scheduler queues unrestricted"); + test_serialized_tight_ring_contention(); + test_fallback_preserves_claim_without_spurious_notify(); + println!("PASS g17-m5-multiqueue-contention-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument( + '--mutation', + choices=[ + 'unlocked-claim-outer', + 'raw-compute-scope', + 'raw-render-scope', + 'unlocked-scope-drop', + 'drop-direct-claim-on-fallback', + 'pin-single-die', + ], + ) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-m5-mq-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-render-direct-recovery-tests.py b/tools/asahi/g17-render-direct-recovery-tests.py new file mode 100755 index 0000000000000..ef1bd4360769e --- /dev/null +++ b/tools/asahi/g17-render-direct-recovery-tests.py @@ -0,0 +1,293 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host lifecycle test for render_direct() recovery crossing publication and doorbell contract. + +Compiles production `render_doorbell_message()` (from `runtime/render.rs`) and +`finish_publication()` (from `runtime/backend.rs`), and drives the real +post-publication recovery check extracted from `render_direct()` +(`runtime/render/direct.rs`) through a full lifecycle harness: +1. Recovery starts while a render pair is lent and published (same generation, + `recovery_state != 0`): `render_direct()` returns `Ok(())`, `return_render()` + returns the published pair before `lease` drops, `queue_events()` runs, + `finish_publication()` does NOT fail the unrelated client's VM, and the + subsequent recovery pass settles the pair exactly once. +2. Generation changes mid-publication (`port.generation() != generation`): + `render_direct()` returns `Err(EIO)` and `finish_publication()` fails the VM. +3. Shared `render_doorbell_message()` contract: M5 (!J813_FORMS) uses pipe 2, + J813 (J813_FORMS) uses pipe 0, non-M5 uses pipe 0, and both render publishers + delegate to `render_doorbell_message()`. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + render_src = (G17 / 'runtime/render.rs').read_text() + direct_src = (G17 / 'runtime/render/direct.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + + doorbell_fn = item(render_src, 'fn render_doorbell_message(') + direct_fn = item(direct_src, 'pub(in crate::g17::runtime) fn render_direct(') + finish_fn = item(backend_src, 'pub(super) fn finish_publication(').replace('pub(super) ', '') + + if mutation == 'wrong-j813-pipe': + doorbell_fn = doorbell_fn.replace( + 'if m5 && !crate::g17::J813_FORMS.load(core::sync::atomic::Ordering::Relaxed)', + 'if m5', + 1, + ) + + # Extract the exact post-publication check block from render_direct(). + check_start = direct_fn.index('result?;') + check_end = direct_fn.index('Ok(())\n })();', check_start) + len('Ok(())') + post_publish = direct_fn[check_start:check_end] + + if mutation == 'recovery-state-eio': + post_publish = post_publish.replace( + 'if port.recovery_state()? != 0 {\n recovery_started = true;\n }', + 'if port.recovery_state()? != 0 {\n return Err(EIO);\n }', + 1, + ) + elif mutation == 'drop-generation-check': + post_publish = post_publish.replace( + 'if port.generation() != generation {\n return Err(EIO);\n }', + '', + 1, + ) + + # Verify both locked and direct render publishers share render_doorbell_message() + # and that render_direct() returns the pair and drops lease before queueing events. + shared_contract = ( + 'notify(render_doorbell_message(m5, priority))' in render_src + and 'self.port.notify(super::render_doorbell_message(m5, priority))' in direct_src + and direct_src.count('J813_FORMS') == 0 + ) + order_tokens = [ + 'firmware.return_render(slot, &mut loan, activation, packet)', + 'self.shared.note_changed();', + 'drop(lease);', + 'if recovery_started {\n self.shared.queue_events();\n }', + ] + order_ok = True + pos = -1 + for tok in order_tokens: + if direct_fn.count(tok) != 1 or direct_fn.index(tok) <= pos: + order_ok = False + break + pos = direct_fn.index(tok) + + doorbell_host = doorbell_fn.replace('crate::g17::', 'g17_stub::') + + return f''' +use std::cell::Cell; +use std::sync::{{Arc, atomic::{{AtomicBool, AtomicUsize, Ordering}}}}; + +const EIO: i32 = -5; +const ETIMEDOUT: i32 = -110; +const ENODEV: i32 = -19; +type Result = std::result::Result; +type Fence = u8; + +mod g17_stub {{ + use std::sync::atomic::AtomicBool; + pub const MSG_TYPE_SHIFT: u32 = 48; + pub static J813_FORMS: AtomicBool = AtomicBool::new(false); +}} + +{doorbell_host} + +#[derive(PartialEq, Eq)] +enum Engine {{ Render, Compute }} + +struct Status(Cell); +impl Status {{ fn get(&self) -> i32 {{ self.0.get() }} }} + +struct Completion {{ + status: Status, + unpublished_fails: Cell, +}} +impl Completion {{ + fn status(&self) -> &Status {{ &self.status }} + fn fail_unpublished(&self, _: i32) {{ self.unpublished_fails.set(self.unpublished_fails.get() + 1); }} + fn scheduler_fence(&self) -> Fence {{ 1 }} +}} + +struct Packet {{ + published: Cell, + completion: Arc, +}} +impl Packet {{ + fn is_published(&self) -> bool {{ self.published.get() }} + fn engine(&self) -> Engine {{ Engine::Render }} +}} + +struct DeferredBatch {{ finished: usize }} +impl DeferredBatch {{ fn finish(&mut self) {{ self.finished += 1; }} }} + +mod job {{ + pub trait Backend {{ + fn fail_vm(&self, error: i32); + }} +}} + +struct Port {{ + gen: Cell, + rec_state: Cell, +}} +impl Port {{ + fn generation(&self) -> u64 {{ self.gen.get() }} + fn recovery_state(&self) -> Result {{ Ok(self.rec_state.get()) }} +}} + +struct RecoveryHarness {{ + vm_failed: Cell, + events_queued: Cell, + pair_returned_before_lease_drop: Cell, + lease_held: Cell, + pair_in_registry: Cell, + settlements: Cell, + stop_called: Cell, +}} + +impl job::Backend for RecoveryHarness {{ + fn fail_vm(&self, _error: i32) {{ + self.vm_failed.set(true); + }} +}} + +impl RecoveryHarness {{ + fn stop_after_error(&self) {{ self.stop_called.set(true); }} + fn rollback_unpublished_compute(&self) -> Result {{ Ok(()) }} + + {finish_fn} + + fn run_direct_publish_lifecycle(&self, port: &Port, generation: u64, packet: &Arc) -> Result {{ + self.lease_held.set(true); + self.pair_in_registry.set(false); + let mut recovery_started = false; + let result: Result = (|| {{ + let result: Result = Ok(()); + packet.published.set(true); + {post_publish} + }})(); + // return_render() places the published pair back while lease is still held. + self.pair_in_registry.set(true); + self.pair_returned_before_lease_drop.set(self.lease_held.get()); + self.lease_held.set(false); + if recovery_started {{ + self.events_queued.set(self.events_queued.get() + 1); + }} + let mut deferred = DeferredBatch {{ finished: 0 }}; + self.finish_publication(packet, result, &mut deferred) + }} + + fn run_recovery_pass(&self, port: &Port) {{ + // Recovery drains preparations (lease must already be dropped) and settles the returned pair once. + assert!(!self.lease_held.get(), "recovery must wait for lease drop"); + if self.pair_in_registry.get() && port.recovery_state().unwrap() != 0 {{ + self.settlements.set(self.settlements.get() + 1); + port.gen.set(port.gen.get() + 1); + port.rec_state.set(0); + self.pair_in_registry.set(false); + }} + }} +}} + +fn new_packet() -> Arc {{ + Arc::new(Packet {{ + published: Cell::new(false), + completion: Arc::new(Completion {{ + status: Status(Cell::new(0)), + unpublished_fails: Cell::new(0), + }}), + }}) +}} + +fn new_harness() -> RecoveryHarness {{ + RecoveryHarness {{ + vm_failed: Cell::new(false), + events_queued: Cell::new(0), + pair_returned_before_lease_drop: Cell::new(false), + lease_held: Cell::new(false), + pair_in_registry: Cell::new(false), + settlements: Cell::new(0), + stop_called: Cell::new(false), + }} +}} + +fn main() {{ + assert!({str(shared_contract).lower()}, "both render publishers must share render_doorbell_message"); + assert!({str(order_ok).lower()}, "render_direct must return pair before dropping lease and queueing events"); + + // 1. Doorbell pipe contract. + g17_stub::J813_FORMS.store(false, Ordering::Relaxed); + assert_eq!(render_doorbell_message(false, 2) & 3, 0); + assert_eq!(render_doorbell_message(true, 2) & 3, 2); + assert_eq!((render_doorbell_message(true, 3) >> 2) & 3, 3); + g17_stub::J813_FORMS.store(true, Ordering::Relaxed); + assert_eq!(render_doorbell_message(true, 2) & 3, 0); + g17_stub::J813_FORMS.store(false, Ordering::Relaxed); + + // 2. Recovery crosses publication (same generation, recovery_state != 0): + // unrelated client keeps its VM, pair is returned before lease drop, and settles once. + let h = new_harness(); + let port = Port {{ gen: Cell::new(7), rec_state: Cell::new(1) }}; + let pkt = new_packet(); + let fence = h.run_direct_publish_lifecycle(&port, 7, &pkt).unwrap(); + assert_eq!(fence, 1); + assert!(!h.vm_failed.get(), "unrelated client VM must survive recovery crossing publication"); + assert!(h.pair_returned_before_lease_drop.get()); + assert_eq!(h.events_queued.get(), 1); + h.run_recovery_pass(&port); + h.run_recovery_pass(&port); + assert_eq!(h.settlements.get(), 1, "published pair must settle exactly once"); + + // 3. Generation changed mid-publication: fails with EIO and fails VM. + let h2 = new_harness(); + let port2 = Port {{ gen: Cell::new(8), rec_state: Cell::new(0) }}; + let pkt2 = new_packet(); + assert_eq!(h2.run_direct_publish_lifecycle(&port2, 7, &pkt2).err(), Some(EIO)); + assert!(h2.vm_failed.get(), "generation mismatch must fail VM"); + + println!("PASS g17-render-direct-recovery-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['recovery-state-eio', + 'drop-generation-check', + 'wrong-j813-pipe']) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-rd-rec-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 0d3fb7209e45c..fa37c9c3cacb1 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -273,6 +273,13 @@ def mutations(flag, names, base, expect=KILL): 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', 'unsafe-wait', 'owed-blocks-kill', 'open-owed-skipped'), []), + 'g17-m5-direct-compute-tests.py': [([], PASS)] + + mutations('--mutation', ('no-pre-recovery-drain', 'direct-debits-published', + 'scope-allows-reserve'), []), + 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', + 'raw-render-scope', 'unlocked-scope-drop', + 'drop-direct-claim-on-fallback', 'pin-single-die'), []), 'g17-m5-effort-tests.py': [([], PASS)] + mutations('--mutation', ('m5-ignores-bound',), []), 'g17-firmware-selection-tests.py': [([], PASS)], @@ -287,6 +294,9 @@ def mutations(flag, names, base, expect=KILL): 'g17-quarantine-drain-tests.py': [([], PASS)] + mutations('--mutation', ('no-drain-release', 'without-witness', 'ignore-leases', 'no-last-lease', 'witness-covers-later-failure', 'unquarantined-drain'), []), + 'g17-render-direct-recovery-tests.py': [([], PASS)] + + mutations('--mutation', ('recovery-state-eio', 'drop-generation-check', + 'wrong-j813-pipe'), []), 'g17-resource-tests.py': [([], PASS)], 'g17-shared-pool-tests.py': [([], PASS)], 'g17-t6041-initdata-tests.py': [([], PASS)],