From 550b955538f4ab5f0f524c4652cdee8b0bd22cb1 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 13:40:06 -0500 Subject: [PATCH 1/6] drm/asahi: g17: deduplicate sync-input chains and resolve M5 cross-QID sources directly Cross-queue compute handoffs previously hit three layers of host lock contention and fallback overhead: 1. asahi_g17_collect_fences() expanded every unsignaled node in a timeline dma_fence_chain without same-context coalescing (forcing reallocations and per-leaf global device-mutex scans inside Backend::input_sources()). 2. Backend::input_sources(), compute_readiness(), and sources_published() always took the global device mutex and linearly scanned compute queues to check whether a same-VM producer was published. 3. Backend::compute_direct() unconditionally rejected packets with converted input sources, forcing every cross-QID compute submission through compute_inline() under the global device mutex (and holding m5_outer across mailbox doorbell I/O in ComputeHost::notify()). Coalesce healthy unsignaled leaves sharing a non-zero fence context in collect_leaf() (keeping only the latest seqno via dma_fence_is_later() while preserving every failed leaf with status < 0), keeping the initial Rust collection capacity at 4, and hoist the fallback device mutex out of the leaf loop in Backend::input_sources(). Publish immutable cross-QID kick metadata (PublishedSource: epoch, publication order, KickDependency, and producer source_readers counter) onto fence::Submission once compute::Queue::publish() commits and rings its doorbell, invalidating it on retirement, error, replay, and cancel. Track the live epoch in published_epoch (AtomicU64, 0 = unpublished) so has_published_epoch() and empty clear_published() skip Submission::state, and store immutable vm_status outside Mutex so same_vm() is lock-free. Remove ReaderHint's blind spot so lock-free Hold::new() loans are always observed by shareable(), can_rearm(), and reset_for_owner(). Use the PublishedSource snapshot for lock-free checks in input_sources(), compute_readiness(), and sources_published(), allow M5 compute_direct() to resolve same-VM compute sources directly (skipping duplicate explicit barriers, self-reader Holds, and firmware_consumer marks when a source was already published on the consumer's own physical QID in the same epoch while still validating source_status() and recovery/epoch), mark firmware_consumer atomically on cross-QID producers, and drop m5_outer before port.notify() in ComputeHost::notify(). Add host C+Rust tests and mutation controls in g17-m5-cross-qid-direct-tests. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/completion.rs | 8 + drivers/gpu/drm/asahi/g17/fence.rs | 90 ++- drivers/gpu/drm/asahi/g17/job.rs | 1 + drivers/gpu/drm/asahi/g17/queue/compute.rs | 17 + drivers/gpu/drm/asahi/g17/runtime.rs | 186 +++++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 62 +- drivers/gpu/drm/asahi/g17/sync_input.c | 23 +- drivers/gpu/drm/asahi/g17/sync_input.rs | 9 +- tools/asahi/g17-m5-cross-qid-direct-tests.py | 648 +++++++++++++++++++ tools/asahi/run-host-tests.py | 11 + 10 files changed, 1013 insertions(+), 42 deletions(-) create mode 100755 tools/asahi/g17-m5-cross-qid-direct-tests.py diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index 41e8b3c09fc9a..2919fa2841547 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -512,6 +512,12 @@ impl Completion { pub(super) fn is_input_source(&self, source: &Arc) -> bool { self.output.output().member.is_source(source) } + pub(crate) fn note_source_published(&self, published: super::fence::PublishedSource) { + self.output.output().member.note_published(published); + } + pub(crate) fn clear_source_published(&self) { + self.output.output().member.clear_published(); + } pub(super) fn set_source_ready(&self, ready: Fence) { self.output.output().member.set_source_ready(ready); } @@ -609,6 +615,7 @@ impl Completion { }) .is_ok(); if accepted { + self.clear_source_published(); self.replay_timeout.store(true, Ordering::Release); // Callers replay only work proven not to have started; the new // publication runs from the beginning and reports its own result. @@ -627,6 +634,7 @@ impl Completion { pub(crate) fn has_firmware_consumer(&self) -> bool { self.firmware_consumer.load(Ordering::Acquire) + || self.output.output().member.has_firmware_consumer() } pub(crate) fn take_replay_timeout(&self) -> bool { diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index df98a3410a50d..bcd9f6f305cf0 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -172,9 +172,20 @@ pub(super) unsafe fn exported_source_raw(raw: *mut bindings::dma_fence) -> Optio .cloned() } +/// Immutable cross-QID kick metadata published once a compute source is committed in firmware. +/// Consumers on the same VM read this without acquiring the global device mutex. +#[derive(Clone)] +pub(crate) struct PublishedSource { + pub(crate) epoch: u64, + pub(crate) published: u64, + pub(crate) dependency: super::fw::kick::KickDependency, + pub(crate) readers: Arc, +} + struct State { work: Option>, ready: Option, + published: Option, } // One Member per parsed command, plus the enqueue guard. Exported references @@ -186,6 +197,8 @@ kernel::static_assert!(crate::file::MAX_COMMANDS_PER_SUBMISSION < u8::MAX as u32 pub(crate) struct Submission { #[pin] state: Mutex, + /// Immutable VM status of this submission, stored outside `state` so `same_vm()` is lock-free. + vm_status: Option>, remaining: AtomicU8, error: AtomicI32, /// Live Member objects, plus the enqueue guard, independently of signalling. @@ -195,22 +208,35 @@ pub(crate) struct Submission { /// is queued, before its fence is signalled off-lock: a consumer published /// in between needs no wait on it. retired: AtomicBool, + /// Non-zero encoded recovery epoch (`epoch.wrapping_add(1)`) while `state.published` holds a + /// live `PublishedSource` snapshot, or `0` when unpublished. + published_epoch: AtomicU64, + /// Set atomically when a firmware kick depends on this source so replay/retirement + /// observes consumers without scanning producer queues under the device mutex. + firmware_consumer: AtomicBool, } impl Submission { + fn encode_epoch(epoch: u64) -> u64 { + epoch.wrapping_add(1) + } fn new(context: Arc, firmware_source: bool) -> Result> { let work = Arc::new(WorkStateLease::deferred(context)?, GFP_KERNEL)?; Self::with_work(Some(work), firmware_source) } fn with_work(work: Option>, firmware_source: bool) -> Result> { + let vm_status = work.as_ref().map(|work| work.status().clone()); Arc::pin_init( pin_init!(Self { - state <- new_mutex!(State { work, ready: None }, "G17 submission work state"), + state <- new_mutex!(State { work, ready: None, published: None }, "G17 submission work state"), + vm_status, remaining: AtomicU8::new(1), error: AtomicI32::new(0), owners: AtomicU8::new(1), firmware_source, retired: AtomicBool::new(false), + published_epoch: AtomicU64::new(0), + firmware_consumer: AtomicBool::new(false), }), GFP_KERNEL, ) @@ -225,15 +251,55 @@ impl Submission { Ok(complete) } pub(super) fn same_vm(&self, status: &Arc) -> bool { - self.state - .lock() - .work + self.vm_status .as_ref() - .is_some_and(|work| Arc::ptr_eq(work.status(), status)) + .is_some_and(|vm| Arc::ptr_eq(vm, status)) } pub(super) fn ready(&self) -> Option { self.state.lock().ready.clone() } + pub(super) fn set_published(&self, source: PublishedSource) { + if !self.firmware_source { + return; + } + let tag = Self::encode_epoch(source.epoch); + let mut state = self.state.lock(); + if state.work.is_some() + && self.error.load(Ordering::Acquire) == 0 + && !self.retired.load(Ordering::Acquire) + { + state.published = Some(source); + self.published_epoch.store(tag, Ordering::Release); + } + } + pub(super) fn clear_published(&self) { + if self.published_epoch.swap(0, Ordering::AcqRel) == 0 { + return; + } + let old = self.state.lock().published.take(); + drop(old); + } + pub(super) fn published_source(&self, epoch: u64) -> Option { + if !self.has_published_epoch(epoch) { + return None; + } + let state = self.state.lock(); + state + .published + .as_ref() + .filter(|source| source.epoch == epoch) + .cloned() + } + pub(super) fn has_published_epoch(&self, epoch: u64) -> bool { + let tag = Self::encode_epoch(epoch); + self.firmware_source && tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag + } + pub(super) fn note_firmware_consumer(&self) { + self.firmware_consumer.store(true, Ordering::Release); + } + pub(super) fn has_firmware_consumer(&self) -> bool { + self.firmware_consumer.load(Ordering::Acquire) + } fn set_ready(&self, ready: Fence) { if !self.firmware_source { return; @@ -244,14 +310,16 @@ impl Submission { } } fn note_error(&self, error: Error) -> bool { + self.clear_published(); self.error .compare_exchange(0, error.to_errno(), Ordering::AcqRel, Ordering::Acquire) .is_ok() } fn release_state(&self) { + self.published_epoch.store(0, Ordering::Release); let old = { let mut state = self.state.lock(); - (state.work.take(), state.ready.take()) + (state.work.take(), state.ready.take(), state.published.take()) }; drop(old); } @@ -346,8 +414,18 @@ impl Member { let source = self.aggregate.source(); if source.firmware_source { source.retired.store(true, Ordering::Release); + source.clear_published(); } } + pub(super) fn note_published(&self, published: PublishedSource) { + self.aggregate.source().set_published(published); + } + pub(super) fn clear_published(&self) { + self.aggregate.source().clear_published(); + } + pub(super) fn has_firmware_consumer(&self) -> bool { + self.aggregate.source().has_firmware_consumer() + } pub(crate) fn complete(&self, result: Result) { if !self.complete.swap(true, Ordering::AcqRel) { self.aggregate diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index b6536c07b443f..dbf766f4dabb8 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -270,6 +270,7 @@ impl Packet { } pub(crate) fn request_cancel(&self) -> bool { self.cancelled.store(true, Ordering::Release); + self.completion.clear_source_published(); self.publication .compare_exchange(0, 3, Ordering::AcqRel, Ordering::Acquire) .is_ok() diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index e7e1b43eb6b2a..adc94dca1de4d 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -3137,6 +3137,23 @@ impl Queue { first || notify_activation)?)?; } host.notify((0x83 << 48) | 0x02 | u64::from(policy.priority()) << 2)?; + if !packet.cancel_requested() { + if let Some(dependency) = + crate::g17::fw::kick::KickDependency::new(qid, kick_timestamp) + { + packet.completion.note_source_published( + crate::g17::fence::PublishedSource { + epoch, + published, + dependency, + readers: self.source_readers.clone(), + }, + ); + if packet.cancel_requested() { + packet.completion.clear_source_published(); + } + } + } crate::g17::trace::publish(crate::g17::trace::COMPUTE, qid, ordinal, &packet); host.note_submission() })(); diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 2297c1a79429f..ea9a245e6ea2d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -80,6 +80,8 @@ struct ComputeEntry { pub(super) struct ComputeCell { #[pin] queue: kernel::sync::Mutex>>, + /// Lock-free mirror of the installed queue's QID (`u8::MAX` when empty). + qid: core::sync::atomic::AtomicU8, } impl ComputeCell { @@ -87,11 +89,17 @@ impl ComputeCell { Arc::pin_init( pin_init!(Self { queue <- kernel::new_mutex!(None, "g17::ComputeCell::queue"), + qid: core::sync::atomic::AtomicU8::new(u8::MAX), }), GFP_KERNEL, ) } + pub(super) fn qid(&self) -> Option { + let qid = self.qid.load(Ordering::Acquire); + (qid != u8::MAX).then_some(qid) + } + /// The installed queue, locked; None once the registry gave it up. pub(super) fn lock(&self) -> Option> { QueueGuard::new(self.queue.lock()) @@ -148,10 +156,18 @@ impl ComputeSlot { } /// Gives the queue up to the caller, which drops it outside the cell lock. fn take(&mut self) -> Option> { - self.0.queue.lock().take() + let mut guard = self.0.queue.lock(); + let taken = guard.take(); + self.0.qid.store(u8::MAX, Ordering::Release); + taken } fn put(&mut self, queue: Option>) { - let old = core::mem::replace(&mut *self.0.queue.lock(), queue); + let qid = queue.as_ref().map_or(u8::MAX, |queue| queue.qid()); + let old = { + let mut guard = self.0.queue.lock(); + self.0.qid.store(qid, Ordering::Release); + core::mem::replace(&mut *guard, queue) + }; drop(old); } } @@ -1534,6 +1550,7 @@ struct ComputeHost<'a> { regs: &'a crate::regs::G17Resources, port: &'a super::port::Port, outer: Option>, + m5_outer: Option>>, /// M5: the shared compute ring's room check of this publication, by priority. outer_cursors: Option<(u8, [u32; 3])>, effort: &'a mut super::power::Effort, @@ -1588,7 +1605,14 @@ impl compute::Host for ComputeHost<'_> { // Every M5 pipe-2 doorbell (0x83) is noted in the firmware's submission history first, // as the render doorbell notes its pair. if self.init.is_m5() && message >> super::MSG_TYPE_SHIFT == 0x83 && message & 3 == 2 { - if let Err(error) = self.init.note_m5_submission_history(1) { + if let Some(guard) = self.m5_outer.as_mut() { + 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 = None; + } else if let Err(error) = self.init.note_m5_submission_history(1) { pr_warn!("asahi: M5 submission history skipped: {:?}\n", error); } } @@ -1719,6 +1743,7 @@ impl super::Firmware { // the source's kick, and the firmware orders it. So is a G17P source of the consumer's // own execution context: one context needs no write-back between the two kicks. let m5 = self.init.is_m5(); + let consumer_qid = self.queues.compute(owner).map(|queue| queue.qid()); let mut waited: u128 = 0; for source in &sources.sources { if source.submission.source_status()? { continue; } @@ -1732,6 +1757,13 @@ impl super::Firmware { let Some((sequence, dependency, stamp_va, event_slot, hold, same_execution)) = found else { return Err(EAGAIN); }; + if m5 && consumer_qid == Some(dependency.qid()) { + // Same physical QID in this epoch: the queue's implicit parent already strictly + // orders earlier kicks on this QID; drop the self-reader hold and skip adding a + // duplicate explicit barrier. + drop(hold); + continue; + } waited |= 1u128 << dependency.qid(); if m5 || same_execution { merged.insert(sequence, dependency)?; @@ -1798,7 +1830,7 @@ impl super::Firmware { // 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 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(); @@ -1816,6 +1848,7 @@ impl super::Firmware { regs: &self.bridge.regs, port: &self.port, outer, + m5_outer, outer_cursors, effort: &mut self.effort, qids: &mut queues.qids, @@ -2157,17 +2190,76 @@ impl Backend { } } + /// Resolves same-VM cross-QID M5 compute sources lock-free from each producer's + /// `PublishedSource` snapshot under a live preparation lease. Sources already published on + /// `target_qid` in `generation` are ordered by this queue's implicit parent, so they skip the + /// duplicate explicit barrier, `Hold`, and `firmware_consumer` mark while still checking + /// `source_status()` (error propagation) and epoch validity. Any unpublished, errored, + /// cancelled, or epoch-mismatched source returns `None` so the device-mutex path handles it. + fn resolve_direct_sources( + &self, + port: &super::port::Port, + generation: u64, + target_qid: u8, + sources: &super::sync_input::Sources, + ) -> Option<(super::dependency::Frontier, KVec, u64)> { + sources.check().ok()?; + let mut frontier = super::dependency::Frontier::new(); + let mut holds = KVec::new(); + let mut cross_qid_mask = 0u64; + for (idx, source) in sources.sources.iter().enumerate() { + if source.submission.source_status().ok()? { + continue; + } + let published = source.submission.published_source(generation)?; + if published.dependency.qid() == target_qid { + if port.recovery_state().ok()? != 0 || port.generation() != generation { + return None; + } + if source.submission.source_status().ok()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + return None; + } + continue; + } + let hold = super::sync_input::Hold::new(&published.readers).ok()?; + // Re-validate after taking the binding loan so the producer cannot have retired, + // faulted, cancelled, or crossed an epoch before `readers` became non-zero. + if port.recovery_state().ok()? != 0 || port.generation() != generation { + return None; + } + if source.submission.source_status().ok()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + return None; + } + frontier + .insert(published.published, published.dependency) + .ok()?; + holds.push(hold, GFP_KERNEL).ok()?; + cross_qid_mask |= 1u64 << idx; + } + Some((frontier, holds, cross_qid_mask)) + } + /// Steady-state publication into this owner's bound channel without the device mutex: only /// the channel's own lock and the port's small locks are taken, and nothing device-wide is - /// scanned. None leaves the packet untouched for the device-mutex path, which owns binding, - /// first installation, input sources, render prefixes, replay and recovery. + /// scanned. On M5, same-VM cross-QID compute sources whose producers have published their kick + /// metadata also resolve directly without the device mutex. None leaves the packet untouched + /// for the device-mutex path, which owns binding, first installation, non-M5 native-wait + /// sources, render prefixes, replay and recovery. fn compute_direct( &self, packet: &Arc, required: super::freelist::ComputeCapacity, deferred: &mut DeferredBatch, ) -> Option { - if packet.completion.sources().is_some() + let m5 = self.context.is_m5(); + let has_sources = packet.completion.sources().is_some(); + if (has_sources && !m5) || self.context.render_seen() || packet.cancel_requested() || packet.completion.status().get() != 0 @@ -2176,11 +2268,19 @@ impl Backend { return None; } let cell = self.direct.lock().clone()?; + let target_qid = cell.qid()?; let lease = self.shared.preparations.try_enter().ok()?; let port = self.shared.port(&lease)?; if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { return None; } + let generation = port.generation(); + let (direct_frontier, direct_holds, cross_qid_mask) = + if let Some(sources) = packet.completion.sources() { + self.resolve_direct_sources(port, generation, target_qid, sources)? + } else { + (super::dependency::Frontier::new(), KVec::new(), 0) + }; // Full effort is applied by the device-mutex path when it is not already. if !port.note_submission() { return None; @@ -2192,7 +2292,6 @@ impl Backend { Err(error) if error == EBUSY => return None, Err(error) => return Some(Err(error)), } - 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 @@ -2221,6 +2320,7 @@ impl Backend { || queue.spared_pending() || !queue.pool_fits(required) || queue.pending_switch_from().is_some() + || queue.qid() != target_qid || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) || !lease.is_current() { @@ -2237,10 +2337,33 @@ impl Backend { m5_outer: m5_outer.as_mut(), m5_outer_guard: None, m5, - generation: port.generation(), + generation, }; - Some(queue.publish(packet.clone(), &[], &mut host, &mut |event| deferred.push(event))) + Some(queue.publish( + packet.clone(), + direct_frontier.as_slice(), + &mut host, + &mut |event| deferred.push(event), + )) })(); + if packet.is_published() { + if let Some(sources) = packet.completion.sources() { + if cross_qid_mask != 0 { + for (idx, source) in sources.sources.iter().enumerate() { + if cross_qid_mask & (1u64 << idx) != 0 { + source.submission.note_firmware_consumer(); + } + } + sources.set_holds(direct_holds); + } else { + drop(direct_holds); + } + super::sync_input::note_published(); + super::sync_input::note_native(0); + } + } else { + drop(direct_holds); + } let outcome = match result { None => None, Some(Err(error)) if (error == EAGAIN || error == EBUSY) && !packet.is_published() => { @@ -2399,8 +2522,17 @@ impl Backend { Err(_) => return Readiness::Ready, Ok(_) => {} } + let sources_checked = if packet.completion.sources().is_some() { + match self.sources_published(packet) { + Ok(false) => return Readiness::Progress, + Err(_) => return Readiness::Ready, + Ok(true) => true, + } + } else { + false + }; // The steady state: this owner's channel is bound and installed. - if packet.completion.sources().is_none() { + if !sources_checked || self.context.is_m5() { if let Some(cell) = self.direct.lock().clone() { let bound = cell.lock().and_then(|mut queue| { let bound = queue.installed() @@ -2426,10 +2558,12 @@ impl Backend { } } } - match self.sources_published(packet) { - Ok(false) => return Readiness::Progress, - Err(_) => return Readiness::Ready, - Ok(true) => {} + if !sources_checked { + match self.sources_published(packet) { + Ok(false) => return Readiness::Progress, + Err(_) => return Readiness::Ready, + Ok(true) => {} + } } let lease = match self.shared.preparations.try_enter() { Ok(lease) => lease, @@ -2602,6 +2736,28 @@ impl Backend { fn sources_published(&self, packet: &super::job::Packet) -> Result { let Some(sources) = packet.completion.sources() else { return Ok(true); }; sources.check()?; + if let Ok(lease) = self.shared.preparations.try_enter() { + if let Some(port) = self.shared.port(&lease) { + if !self.shared.crashed.load(Ordering::Acquire) + && port.recovery_state().ok() == Some(0) + { + let generation = port.generation(); + let mut all_fast = true; + for source in &sources.sources { + if source.submission.source_status()? { + continue; + } + if !source.submission.has_published_epoch(generation) { + all_fast = false; + break; + } + } + if all_fast { + return Ok(true); + } + } + } + } let state = self.shared.state.lock(); let firmware = state.as_deref().ok_or(ENODEV)?; if firmware.recovery.pending() diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 35ddab8134ff5..7cf47757a9550 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -144,6 +144,15 @@ impl job::Backend for Backend { let mut heads = KVec::new(); let mut sources: KVec = KVec::new(); let mut publication_waits = KVec::new(); + let mut unchecked: KVec = KVec::new(); + let lease = self.shared.preparations.try_enter().ok(); + let port_epoch = lease.as_ref().and_then(|lease| { + let port = self.shared.port(lease)?; + if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { + return None; + } + Some(port.generation()) + }); for input in inputs.iter().filter_map(|input| input.fence.as_ref()) { let status = job::fence_status(input); if status > 0 { continue; } @@ -160,29 +169,52 @@ impl job::Backend for Backend { continue; } if sources.len() == crate::g17::fw::kick::KICK_BARRIERS_MAX { return None; } - let published = { - let state = self.shared.state.lock(); - let firmware = state.as_deref()?; - if self.shared.crashed.load(Ordering::Acquire) || firmware.recovery.pending() - || crate::g17::recovery::Memory::recovery_state(&firmware.init).ok()? != 0 - { return None; } - firmware.queues.compute.iter().flatten() - .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.has_input_source(&submission, self.context.status(), - firmware.recovery.generation())) - }; + let published_fast = + port_epoch.is_some_and(|epoch| submission.has_published_epoch(epoch)); + let idx = sources.len(); + sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; + if !published_fast { + unchecked.push(idx, GFP_KERNEL).ok()?; + } + } + heads.push(input.clone(), GFP_KERNEL).ok()?; + } + drop(lease); + if sources.is_empty() { return None; } + if !unchecked.is_empty() { + // Hoist the device mutex outside the leaf loop when any source was not already + // confirmed via the lock-free `PublishedSource` snapshot. + let state = self.shared.state.lock(); + let firmware = state.as_deref()?; + if self.shared.crashed.load(Ordering::Acquire) + || firmware.recovery.pending() + || crate::g17::recovery::Memory::recovery_state(&firmware.init).ok()? != 0 + { + return None; + } + let generation = firmware.recovery.generation(); + for idx in unchecked { + let submission = &sources[idx].submission; + let published = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| { + queue.has_input_source(submission, self.context.status(), generation) + }); if !published { - if submission.source_status().ok()? { continue; } + if submission.source_status().ok()? { + continue; + } // The existing scheduler fence becomes ready after actual // publication, not GPU completion. No binding loan or // consumer hardware capacity is acquired while waiting. publication_waits.push(submission.ready()?, GFP_KERNEL).ok()?; } - sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; } - heads.push(input.clone(), GFP_KERNEL).ok()?; } - if sources.is_empty() { return None; } sync_input::Sources::new(heads, sources, publication_waits).ok() } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 145a5955c8796..858e97066134d 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -10,10 +10,31 @@ static int collect_leaf(struct dma_fence *leaf, struct asahi_g17_fence_leaf *out, size_t capacity, size_t *count) { + int status = dma_fence_get_status(leaf); + + /* + * Coalesce healthy unsignaled leaves sharing a fence context (such as + * multiple points of one timeline chain), keeping only the latest seqno. + * Failed leaves (status < 0) are never coalesced so errors are preserved. + */ + if (status == 0 && leaf->context != 0) { + size_t i; + + for (i = 0; i < *count; ++i) { + if (out[i].status != 0 || + out[i].fence->context != leaf->context) + continue; + if (dma_fence_is_later(leaf, out[i].fence)) { + dma_fence_put(out[i].fence); + out[i].fence = dma_fence_get(leaf); + } + return 0; + } + } if (*count == capacity) return -ENOSPC; out[*count].fence = dma_fence_get(leaf); - out[*count].status = dma_fence_get_status(leaf); + out[*count].status = status; ++*count; return 0; } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 33ac3f94d4f21..612bd7de10952 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -76,7 +76,7 @@ pub(super) struct Source { /// processor stop until the last consumer releases its binding loan. pub(super) struct Hold(Arc); impl Hold { - fn new(readers: &Arc) -> Result { + pub(super) fn new(readers: &Arc) -> Result { readers.fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| count.checked_add(1)).map_err(|_| EOVERFLOW)?; Ok(Self(readers.clone())) @@ -86,9 +86,8 @@ impl Drop for Hold { fn drop(&mut self) { self.0.fetch_sub(1, Ordering::AcqRel); } } -/// A new owner starts with no loans. Acquiring a loan requires exclusive access -/// and arms the hint; eligibility queries stay read-only. A validated owner -/// transition can clear the hint after all independent loans have been released. +/// Checks a physical queue's independent source-reader counter directly so lock-free +/// direct-path loans (`Hold::new`) are always observed by ownership, rearm, and share checks. #[repr(transparent)] pub(super) struct ReaderHint { possible: bool, @@ -103,7 +102,7 @@ impl ReaderHint { Ok(hold) } pub(super) fn has_readers(&self, count: &AtomicU32) -> bool { - self.possible && count.load(Ordering::Acquire) != 0 + count.load(Ordering::Acquire) != 0 } pub(super) fn reset_for_owner(&mut self, count: &AtomicU32) -> Result { if self.has_readers(count) { return Err(EBUSY); } diff --git a/tools/asahi/g17-m5-cross-qid-direct-tests.py b/tools/asahi/g17-m5-cross-qid-direct-tests.py new file mode 100755 index 0000000000000..e175d8cdfe702 --- /dev/null +++ b/tools/asahi/g17-m5-cross-qid-direct-tests.py @@ -0,0 +1,648 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for sync-input chain deduplication and lock-free M5 cross-QID compute publication. + +Tests both the real C `collect_leaf()` extracted from +`drivers/gpu/drm/asahi/g17/sync_input.c` and the real Rust `Hold`, +`ReaderHint`, and `resolve_direct_sources()` logic extracted from +`sync_input.rs` and `runtime.rs`: +1. Timeline chain deduplication (C): 8 unsignaled same-context leaves + collapse to the single latest seqno with zero refcount leaks; distinct + contexts stay distinct; failed earlier leaves (`status < 0`) are never + coalesced or dropped. +2. Lock-free `compute_direct()` cross-QID resolution (Rust): + - Resolves `PublishedSource` into a `Frontier` `KickDependency`, takes + `Hold::new(&readers)` which is immediately observed by + `ReaderHint::has_readers()` and blocks `reset_for_owner()` without + locking the producer queue, and marks `note_firmware_consumer()`. + - Safely falls back (`None`, zero leaked `Hold`s) on unpublished source, + epoch/generation mismatch, active recovery, cancelled/quarantined + source, and failed source fence; skips already-retired sources. +3. Structural verification of `runtime/backend.rs`, `runtime.rs`, + `queue/compute.rs`, `fence.rs`, `completion.rs`, and `job.rs`. +""" +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: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +def build_c_harness(mutation=None): + c_src = (G17 / 'sync_input.c').read_text() + collect_leaf = item(c_src, 'static int collect_leaf(') + if mutation == 'no-chain-dedup': + collect_leaf = collect_leaf.replace( + 'if (status == 0 && leaf->context != 0) {', + 'if (0) {', + 1, + ) + elif mutation == 'coalesce-failed-leaf': + collect_leaf = collect_leaf.replace( + 'if (out[i].status != 0 ||\n\t\t\t out[i].fence->context != leaf->context)', + 'if (out[i].fence->context != leaf->context)', + 1, + ) + + return f''' +#include +#include +#include +#include +#include +#include + +struct dma_fence {{ + uint64_t context; + uint64_t seqno; + int status; + int refs; +}}; + +struct asahi_g17_fence_leaf {{ + struct dma_fence *fence; + int status; +}}; + +static struct dma_fence *dma_fence_get(struct dma_fence *f) +{{ + f->refs++; + return f; +}} + +static void dma_fence_put(struct dma_fence *f) +{{ + assert(f->refs > 0); + f->refs--; +}} + +static int dma_fence_get_status(struct dma_fence *f) +{{ + return f->status; +}} + +static bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) +{{ + assert(f1->context == f2->context); + return (int64_t)(f1->seqno - f2->seqno) > 0; +}} + +{collect_leaf} + +static void release_all(struct asahi_g17_fence_leaf *out, size_t count) +{{ + for (size_t i = 0; i < count; ++i) + dma_fence_put(out[i].fence); +}} + +int main(void) +{{ + /* 1. 8 unsignaled same-context timeline leaves (out of order) -> 1 newest leaf. */ + struct dma_fence chain[8]; + uint64_t order[8] = {{3, 7, 1, 8, 5, 2, 6, 4}}; + for (int i = 0; i < 8; ++i) {{ + chain[i].context = 10; + chain[i].seqno = order[i]; + chain[i].status = 0; + chain[i].refs = 1; + }} + struct asahi_g17_fence_leaf out[16]; + size_t count = 0; + for (int i = 0; i < 8; ++i) {{ + assert(collect_leaf(&chain[i], out, 16, &count) == 0); + }} + assert(count == 1); + assert(out[0].fence->context == 10); + assert(out[0].fence->seqno == 8); + assert(out[0].status == 0); + release_all(out, count); + for (int i = 0; i < 8; ++i) + assert(chain[i].refs == 1); + + /* 2. Failed earlier leaf + healthy later unsignaled leaf on same context -> BOTH kept. */ + struct dma_fence failed = {{ .context = 10, .seqno = 2, .status = -EIO, .refs = 1 }}; + struct dma_fence healthy = {{ .context = 10, .seqno = 9, .status = 0, .refs = 1 }}; + count = 0; + assert(collect_leaf(&failed, out, 16, &count) == 0); + assert(collect_leaf(&healthy, out, 16, &count) == 0); + assert(count == 2); + assert(out[0].status == -EIO && out[0].fence->seqno == 2); + assert(out[1].status == 0 && out[1].fence->seqno == 9); + release_all(out, count); + assert(failed.refs == 1 && healthy.refs == 1); + + /* 3. Two distinct contexts coalesce independently to 1 newest leaf each. */ + struct dma_fence q0[3] = {{ + {{ .context = 11, .seqno = 1, .status = 0, .refs = 1 }}, + {{ .context = 11, .seqno = 4, .status = 0, .refs = 1 }}, + {{ .context = 11, .seqno = 2, .status = 0, .refs = 1 }}, + }}; + struct dma_fence q1[2] = {{ + {{ .context = 22, .seqno = 10, .status = 0, .refs = 1 }}, + {{ .context = 22, .seqno = 12, .status = 0, .refs = 1 }}, + }}; + count = 0; + for (int i = 0; i < 3; ++i) + assert(collect_leaf(&q0[i], out, 16, &count) == 0); + for (int i = 0; i < 2; ++i) + assert(collect_leaf(&q1[i], out, 16, &count) == 0); + assert(count == 2); + assert(out[0].fence->context == 11 && out[0].fence->seqno == 4); + assert(out[1].fence->context == 22 && out[1].fence->seqno == 12); + release_all(out, count); + + /* 4. Context 0 leaves are never coalesced. */ + struct dma_fence z0 = {{ .context = 0, .seqno = 1, .status = 0, .refs = 1 }}; + struct dma_fence z1 = {{ .context = 0, .seqno = 2, .status = 0, .refs = 1 }}; + count = 0; + assert(collect_leaf(&z0, out, 16, &count) == 0); + assert(collect_leaf(&z1, out, 16, &count) == 0); + assert(count == 2); + release_all(out, count); + return 0; +}} +''' + + +def build_rust_harness(mutation=None): + sync_rs = (G17 / 'sync_input.rs').read_text() + backend_rs = (G17 / 'runtime/backend.rs').read_text() + runtime_rs = (G17 / 'runtime.rs').read_text() + compute_rs = (G17 / 'queue/compute.rs').read_text() + completion_rs = (G17 / 'completion.rs').read_text() + fence_rs = (G17 / 'fence.rs').read_text() + job_rs = (G17 / 'job.rs').read_text() + + hold_struct = 'pub struct Hold(Arc);' + hold_impl = item(sync_rs, 'impl Hold').replace('pub(super) ', 'pub ') + hold_drop = item(sync_rs, 'impl Drop for Hold') + hint_struct = item(sync_rs, 'pub(super) struct ReaderHint').replace('pub(super) ', 'pub ') + hint_impl = item(sync_rs, 'impl ReaderHint').replace('pub(super) ', 'pub ') + resolve_fn = item(runtime_rs, 'fn resolve_direct_sources(') + input_sources_fn = item(backend_rs, 'fn input_sources(') + compute_direct_fn = item(runtime_rs, 'fn compute_direct(') + sources_pub_fn = item(runtime_rs, 'fn sources_published(') + compute_host_impl = item(runtime_rs, 'impl compute::Host for ComputeHost<') + begin_replay_fn = item(completion_rs, 'pub(crate) fn begin_replay(') + submission_impl = item(fence_rs, 'impl Submission') + note_error_fn = item(submission_impl, 'fn note_error(') + same_vm_fn = item(submission_impl, 'pub(super) fn same_vm(') + has_pub_epoch_fn = item(submission_impl, 'pub(super) fn has_published_epoch(') + clear_pub_fn = item(submission_impl, 'pub(super) fn clear_published(') + cancel_fn = item(job_rs, 'pub(crate) fn request_cancel(') + + if mutation == 'hint-blind-spot': + hint_impl = hint_impl.replace( + 'count.load(Ordering::Acquire) != 0', + 'self.possible && count.load(Ordering::Acquire) != 0', + 1, + ) + elif mutation == 'skip-epoch-check': + resolve_fn = resolve_fn.replace( + 'source.submission.published_source(generation)?', + 'source.submission.published_source_unchecked()?', + 1, + ) + resolve_fn = resolve_fn.replace( + 'if !source.submission.has_published_epoch(generation) {\n return None;\n }', + '', + 2, + ) + elif mutation == 'skip-recovery-recheck': + resolve_fn = resolve_fn.replace( + 'if port.recovery_state().ok()? != 0 || port.generation() != generation {\n return None;\n }', + '', + 2, + ) + elif mutation == 'lock-per-leaf': + input_sources_fn = input_sources_fn.replace( + 'let published_fast =', + 'let _ = self.shared.state.lock(); let published_fast =', + 1, + ) + elif mutation == 'hold-m5-outer-compute-host': + compute_host_impl = compute_host_impl.replace( + 'self.m5_outer = None;', + '', + 1, + ) + elif mutation == 'same-qid-emits-barrier': + resolve_fn = resolve_fn.replace( + 'if published.dependency.qid() == target_qid {', + 'if false && published.dependency.qid() == target_qid {', + 1, + ) + elif mutation == 'lock-has-published-epoch': + has_pub_epoch_fn = has_pub_epoch_fn.replace( + 'self.published_epoch.load(Ordering::Acquire) == tag', + 'self.state.lock().published.as_ref().is_some_and(|s| s.epoch == epoch)', + 1, + ) + elif mutation == 'lock-same-vm': + same_vm_fn = same_vm_fn.replace( + 'self.vm_status', + 'self.state.lock().work', + 1, + ) + + # Structural checks on production sources. + collect_cap_ok = 'let mut capacity = 4;' in sync_rs + leaf_loop_start = input_sources_fn.index('for leaf in &leaves {') + unchecked_block_start = input_sources_fn.index('if !unchecked.is_empty() {') + leaf_loop = input_sources_fn[leaf_loop_start:unchecked_block_start] + input_sources_ok = ( + 'self.shared.state.lock()' not in leaf_loop + and ordered_ok( + input_sources_fn, + 'submission.has_published_epoch(epoch)', + 'if !unchecked.is_empty() {', + 'let state = self.shared.state.lock();', + 'for idx in unchecked {', + ) + ) + direct_sources_ok = ( + '(has_sources && !m5)' in compute_direct_fn + and ordered_ok( + compute_direct_fn, + 'let target_qid = cell.qid()?;', + 'self.resolve_direct_sources(port, generation, target_qid, sources)?', + 'queue.qid() != target_qid', + 'queue.publish(', + 'direct_frontier.as_slice(),', + 'source.submission.note_firmware_consumer();', + 'sources.set_holds(direct_holds);', + 'drop(direct_holds);', + ) + ) + lockfree_submission_ok = ( + 'published_epoch: AtomicU64,' in fence_rs + and 'vm_status: Option>,' in fence_rs + and 'self.state.lock()' not in has_pub_epoch_fn + and 'self.published_epoch.load(Ordering::Acquire)' in has_pub_epoch_fn + and 'self.state.lock()' not in same_vm_fn + and 'self.vm_status' in same_vm_fn + and 'if self.published_epoch.swap(0, Ordering::AcqRel) == 0 {' in clear_pub_fn + ) + sources_published_ok = ordered_ok( + sources_pub_fn, + 'source.submission.has_published_epoch(generation)', + 'let state = self.shared.state.lock();', + ) + compute_host_ok = ordered_ok( + compute_host_impl, + 'note_m5_submission_history_locked(guard, 1)', + 'self.m5_outer = None;', + 'self.port.notify(message)', + ) + publish_invalidation_ok = ( + ordered_ok( + compute_rs, + 'host.notify((0x83 << 48) | 0x02 | u64::from(policy.priority()) << 2)?;', + 'packet.completion.note_source_published(', + 'if packet.cancel_requested() {', + 'packet.completion.clear_source_published();', + ) + and 'self.clear_published();' in note_error_fn + and 'self.clear_source_published();' in begin_replay_fn + and 'self.completion.clear_source_published();' in cancel_fn + ) + + # Adapt resolve_direct_sources() for host compilation. + host_resolve = resolve_fn + host_resolve = host_resolve.replace('super::port::Port', 'Port') + host_resolve = host_resolve.replace('super::sync_input::Sources', 'Sources') + host_resolve = host_resolve.replace('super::dependency::Frontier', 'Frontier') + host_resolve = host_resolve.replace('super::sync_input::Hold', 'Hold') + host_resolve = host_resolve.replace('KVec', 'Vec') + host_resolve = host_resolve.replace('KVec::new()', 'Vec::new()') + host_resolve = host_resolve.replace('holds.push(hold, GFP_KERNEL).ok()?;', 'holds.push(hold);') + + return f''' +use std::sync::{{Arc, Mutex, atomic::{{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}}}}; + +const EBUSY: i32 = -16; +const EIO: i32 = -5; +const EOVERFLOW: i32 = -75; +const PRODUCER_FAILED: i32 = -5; +type Result = std::result::Result; + +{hold_struct} +{hold_impl} +{hold_drop} + +{hint_struct} +{hint_impl} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct KickDependency {{ + qid: u8, + kick: u64, +}} +impl KickDependency {{ + fn qid(self) -> u8 {{ self.qid }} +}} + +#[derive(Clone)] +struct PublishedSource {{ + epoch: u64, + published: u64, + dependency: KickDependency, + readers: Arc, +}} + +struct Frontier {{ + items: Vec<(u64, KickDependency)>, +}} +impl Frontier {{ + fn new() -> Self {{ Self {{ items: Vec::new() }} }} + fn insert(&mut self, seq: u64, dep: KickDependency) -> Result {{ + if let Some(old) = self.items.iter_mut().find(|(_, d)| d.qid == dep.qid) {{ + if seq > old.0 {{ *old = (seq, dep); }} + }} else {{ + self.items.push((seq, dep)); + }} + Ok(()) + }} +}} + +struct Submission {{ + retired: AtomicBool, + error: AtomicI32, + published_epoch: AtomicU64, + firmware_consumer: AtomicBool, + state_locks: AtomicU32, + published: Mutex>, +}} + +impl Submission {{ + fn encode_epoch(epoch: u64) -> u64 {{ epoch.wrapping_add(1) }} + fn new() -> Arc {{ + Arc::new(Self {{ + retired: AtomicBool::new(false), + error: AtomicI32::new(0), + published_epoch: AtomicU64::new(0), + firmware_consumer: AtomicBool::new(false), + state_locks: AtomicU32::new(0), + published: Mutex::new(None), + }}) + }} + fn set_published(&self, src: PublishedSource) {{ + let tag = Self::encode_epoch(src.epoch); + self.state_locks.fetch_add(1, Ordering::Relaxed); + *self.published.lock().unwrap() = Some(src); + self.published_epoch.store(tag, Ordering::Release); + }} + fn clear_published(&self) {{ + if self.published_epoch.swap(0, Ordering::AcqRel) == 0 {{ + return; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + *self.published.lock().unwrap() = None; + }} + fn source_status(&self) -> Result {{ + if self.error.load(Ordering::Acquire) != 0 {{ + return Err(PRODUCER_FAILED); + }} + Ok(self.retired.load(Ordering::Acquire)) + }} + fn published_source(&self, epoch: u64) -> Option {{ + if !self.has_published_epoch(epoch) {{ + return None; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + self.published.lock().unwrap().as_ref().filter(|s| s.epoch == epoch).cloned() + }} + #[allow(dead_code)] + fn published_source_unchecked(&self) -> Option {{ + if self.published_epoch.load(Ordering::Acquire) == 0 {{ + return None; + }} + self.state_locks.fetch_add(1, Ordering::Relaxed); + self.published.lock().unwrap().clone() + }} + fn has_published_epoch(&self, epoch: u64) -> bool {{ + let tag = Self::encode_epoch(epoch); + tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag + }} + fn note_firmware_consumer(&self) {{ + self.firmware_consumer.store(true, Ordering::Release); + }} +}} + +struct Source {{ submission: Arc }} +struct Sources {{ sources: Vec }} +impl Sources {{ + fn check(&self) -> Result {{ + for s in &self.sources {{ s.submission.source_status()?; }} + Ok(()) + }} +}} + +struct Port {{ + gen: AtomicU64, + rec: AtomicU32, + flip_rec_on_query: AtomicBool, +}} +impl Port {{ + fn generation(&self) -> u64 {{ self.gen.load(Ordering::Acquire) }} + fn recovery_state(&self) -> Result {{ + if self.flip_rec_on_query.swap(false, Ordering::AcqRel) {{ + self.rec.store(1, Ordering::Release); + }} + Ok(self.rec.load(Ordering::Acquire)) + }} +}} + +struct Backend; +impl Backend {{ + {host_resolve} +}} + +fn main() {{ + assert!({str(collect_cap_ok).lower()}, "sync_input::collect must start with capacity 4"); + assert!({str(input_sources_ok).lower()}, "input_sources must check PublishedSource lock-free and hoist state.lock outside leaf loop"); + assert!({str(direct_sources_ok).lower()}, "compute_direct must resolve M5 cross-QID sources lock-free and set holds + firmware_consumer"); + assert!({str(lockfree_submission_ok).lower()}, "Submission::has_published_epoch, same_vm, and empty clear_published must be lock-free"); + assert!({str(sources_published_ok).lower()}, "sources_published must check PublishedSource lock-free before state.lock"); + assert!({str(compute_host_ok).lower()}, "ComputeHost::notify must drop m5_outer before port.notify"); + assert!({str(publish_invalidation_ok).lower()}, "compute::Queue must publish after notify and invalidate on quarantine/replay/cancel"); + + let backend = Backend; + let port = Port {{ + gen: AtomicU64::new(7), + rec: AtomicU32::new(0), + flip_rec_on_query: AtomicBool::new(false), + }}; + let readers = Arc::new(AtomicU32::new(0)); + let mut hint = ReaderHint::new(); + + // 1. Happy path: published cross-QID source (qid 5 -> target_qid 9) resolves lock-free, + // Hold blocks ReaderHint::reset_for_owner even though ReaderHint::hold(&mut self) was never called. + let sub = Submission::new(); + // clear_published() on unpublished submission must take 0 state locks. + sub.clear_published(); + assert_eq!(sub.state_locks.load(Ordering::Relaxed), 0); + sub.set_published(PublishedSource {{ + epoch: 7, + published: 42, + dependency: KickDependency {{ qid: 5, kick: 100 }}, + readers: readers.clone(), + }}); + let locks_before = sub.state_locks.load(Ordering::Relaxed); + assert!(sub.has_published_epoch(7)); + assert!(!sub.has_published_epoch(8)); + assert_eq!(sub.state_locks.load(Ordering::Relaxed), locks_before, "has_published_epoch must be lock-free"); + let sources = Sources {{ sources: vec![Source {{ submission: sub.clone() }}] }}; + let (frontier, holds, mask) = backend.resolve_direct_sources(&port, 7, 9, &sources).unwrap(); + assert_eq!(frontier.items, vec![(42, KickDependency {{ qid: 5, kick: 100 }})]); + assert_eq!(holds.len(), 1); + assert_eq!(mask, 1); + assert_eq!(readers.load(Ordering::Acquire), 1); + assert!(hint.has_readers(&readers), "lock-free Hold::new must be visible to ReaderHint::has_readers"); + assert_eq!(hint.reset_for_owner(&readers), Err(EBUSY), "lock-free Hold must block owner reset"); + sub.note_firmware_consumer(); + assert!(sub.firmware_consumer.load(Ordering::Acquire)); + drop(holds); + assert_eq!(readers.load(Ordering::Acquire), 0); + assert!(!hint.has_readers(&readers)); + assert_eq!(hint.reset_for_owner(&readers), Ok(())); + + // 1b. Same-QID source (qid 5 -> target_qid 5): skipped cleanly (empty frontier, 0 holds, + // 0 readers, mask == 0) because the implicit parent already orders same-QID kicks. + let same_sub = Submission::new(); + same_sub.set_published(PublishedSource {{ + epoch: 7, + published: 43, + dependency: KickDependency {{ qid: 5, kick: 101 }}, + readers: readers.clone(), + }}); + let same_sources = Sources {{ sources: vec![Source {{ submission: same_sub.clone() }}] }}; + let (f_same, h_same, m_same) = backend.resolve_direct_sources(&port, 7, 5, &same_sources).unwrap(); + assert!(f_same.items.is_empty(), "same-QID source must not emit a duplicate explicit barrier"); + assert!(h_same.is_empty(), "same-QID source must not take a self-reader Hold"); + assert_eq!(m_same, 0, "same-QID source must not set cross_qid_mask"); + assert_eq!(readers.load(Ordering::Acquire), 0); + assert!(!same_sub.firmware_consumer.load(Ordering::Acquire)); + + // 1c. Same-QID failed producer MUST still return None so error propagates! + same_sub.error.store(EIO, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 7, 5, &same_sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 2. Unpublished source -> clean None fallback. + let unpub = Submission::new(); + let s_unpub = Sources {{ sources: vec![Source {{ submission: unpub }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_unpub).is_none()); + + // 3. Epoch/generation mismatch (port advanced to epoch 8 while source stays at epoch 7) + // -> clean None fallback, zero leaked Hold. + port.gen.store(8, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 8, 9, &sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + port.gen.store(7, Ordering::Release); + + // 4. Recovery starts concurrently right after Hold -> clean None fallback, zero leaked Hold. + port.flip_rec_on_query.store(true, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 7, 9, &sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + port.rec.store(0, Ordering::Release); + + // 5. Cancelled/quarantined source (clear_published) -> clean None fallback. + let cancelled = Submission::new(); + cancelled.set_published(PublishedSource {{ + epoch: 7, + published: 44, + dependency: KickDependency {{ qid: 5, kick: 102 }}, + readers: readers.clone(), + }}); + cancelled.clear_published(); + let s_can = Sources {{ sources: vec![Source {{ submission: cancelled }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_can).is_none()); + + // 6. Failed producer -> clean None fallback (so slow path propagates PRODUCER_FAILED). + let failed = Submission::new(); + failed.set_published(PublishedSource {{ + epoch: 7, + published: 45, + dependency: KickDependency {{ qid: 5, kick: 103 }}, + readers: readers.clone(), + }}); + failed.error.store(EIO, Ordering::Release); + let s_fail = Sources {{ sources: vec![Source {{ submission: failed }}] }}; + assert!(backend.resolve_direct_sources(&port, 7, 9, &s_fail).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 7. Already-retired source -> skipped cleanly with empty frontier and 0 holds. + let retired = Submission::new(); + retired.retired.store(true, Ordering::Release); + let s_ret = Sources {{ sources: vec![Source {{ submission: retired }}] }}; + let (f_ret, h_ret, m_ret) = backend.resolve_direct_sources(&port, 7, 9, &s_ret).unwrap(); + assert!(f_ret.items.is_empty()); + assert!(h_ret.is_empty()); + assert_eq!(m_ret, 0); + + println!("PASS g17-m5-cross-qid-direct-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['no-chain-dedup', + 'coalesce-failed-leaf', + 'hint-blind-spot', + 'skip-epoch-check', + 'skip-recovery-recheck', + 'lock-per-leaf', + 'hold-m5-outer-compute-host', + 'same-qid-emits-barrier', + 'lock-has-published-epoch', + 'lock-same-vm']) + args = parser.parse_args() + cc = os.environ.get('HOSTCC', 'cc') + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-xqid-') as td: + c_file = Path(td) / 'c_test.c' + c_exe = Path(td) / 'c_test' + c_file.write_text(build_c_harness(args.mutation)) + subprocess.run([cc, '-O2', '-Wall', '-Wextra', '-Werror', '-o', str(c_exe), str(c_file)], check=True) + res_c = subprocess.run([str(c_exe)]) + if res_c.returncode != 0: + sys.exit(res_c.returncode) + + rs_file = Path(td) / 'rs_test.rs' + rs_exe = Path(td) / 'rs_test' + rs_file.write_text(build_rust_harness(args.mutation)) + subprocess.run([rustc, '-O', '-o', str(rs_exe), str(rs_file)], check=True) + res_rs = subprocess.run([str(rs_exe)]) + sys.exit(res_rs.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 79281c819bab9..7c51f27236a39 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -261,6 +261,17 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', 'drop-direct-claim-on-fallback', 'pin-single-die'), []), + 'g17-m5-cross-qid-direct-tests.py': [([], PASS)] + + mutations('--mutation', ('no-chain-dedup', + 'coalesce-failed-leaf', + 'hint-blind-spot', + 'skip-epoch-check', + 'skip-recovery-recheck', + 'lock-per-leaf', + 'hold-m5-outer-compute-host', + 'same-qid-emits-barrier', + 'lock-has-published-epoch', + 'lock-same-vm'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From 7bb65ce97e1d0fe0c52303d63ae98c8372e772e9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 14:59:05 -0500 Subject: [PATCH 2/6] drm/asahi: g17: fan M5 Pro compute out to sibling channels for sustained heavy kicks On M5 Pro one physical firmware compute QID per logical compute queue serializes its kicks: each QID owns a single preemption, operand, usage, status and stamp state, so a kick holds for its parent on that QID. Kicks that each leave the GPU partly idle then run one at a time. macOS runs one M5 Pro command queue on up to three firmware compute queues of the same context, created on demand and sharing one completion ordinal, as its own kicks show when run under aura. Describe that as a property of the board: Board::compute_channels() is the number of firmware compute queues of one context over which a single command queue's independent kicks may run, 3 for the J714 and 1 for the J716C, J775D and J813, whose macOS drivers have not been seen to spread a command queue. multi_channel() and pairs::select_board() read that count alone rather than the board's encoding forms, and a const assertion keeps every board between 1 and COMPUTE_CHANNELS_MAX, the size of the per-owner channel arrays and of the compute waits a render kick carries. Let an owner on such a board hold up to that many physical compute channels sharing one execution context, QoS slot, scheduler page and work-state table, and fan out onto them only the work that gains from overlap: - A command runs on, or brings up, a sibling channel only when it is independent (no in-queue barrier), has no cross-queue input sources, the owner's primary channel runs sustained heavy work and at least two kicks of the owner are already in flight. The work is sustained heavy when the primary's last two retired kicks each ran at least 100 us between the start and end timestamps of their exact firmware execution records (pairs::heavy_run(), pairs::sustained()). One QID streams short kicks back to back faster (about 11 us per kick) than three QIDs do (about 16.4 us: each sibling kick pays about 5 us of firmware arbitration), so short kicks stay on the primary ring; from 100 us that cost is within 5% of the kick. Recordless retirements and releases of held descriptors never count, and the run restarts for every owner. - A kick queued behind one in flight on the same ring starts the moment its predecessor ends, while the host needs 60 to 100 us to turn that completion into the next submission. Two overlapped kicks that each fill the shader cores share them and end together; both rings then wait for the host, and every pair of kicks pays that turnaround (a processor-sharing model predicts 300 to 319 us per kick against 270 us serial; 286 to 302 us were measured for an owner keeping two such kicks in flight). A kick that leaves the GPU partly idle gains about 10% from the same overlap, but the kernel cannot tell the two apart from a kick's metadata (same workgroup size, no threadgroup memory, similar register footprint; the grid lives in the CDM stream). So a kick leaves the primary ring only with SIBLING_MIN_IN_FLIGHT (two) kicks already in flight (pairs::overlaps(), on the direct path, in channel selection and in sibling admission): the primary then keeps one queued behind the overlap, a sibling only adds overlap and never exposes the turnaround, and an owner keeping at most two kicks in flight runs exactly as on one ring. Mesa applies the same rule to the sibling queues it opens itself. - A command with input sources always takes the primary channel, on the direct path (whose lock-free cross-QID source resolution, binding loans and hold hand-off are unchanged) and on the device-mutex path, and never binds a sibling, so a semaphore hop between queues stays on one ring per queue. - Backend::fans_out() checks the command before it asks for the primary's state, and compute_direct() reads that state from the primary ComputeCell's lock-free mirror (sustained), so short kicks and sourced commands neither lock a cell nor detour to the device-mutex path to add a sibling. - Each sibling channel owns a dedicated ComputePool mapped into the context VM; concurrent kicks take distinct 1-based ordinals and (predecessor_id << 32) | current_id object ids from one per-context atomic sequence (Context::next_compute_identity()), used as both submit_sequence and completion_ordinal. - ComputeCell mirrors (configuring, active_len, last_published, sustained) whenever a QueueGuard drops; compute_direct() routes to an idle primary without locking a sibling cell and scans the hints lock-free otherwise. - Siblings bind lazily when every bound channel is busy, from the source Registry::sibling_source() names, in the order a primary binding takes its channel: an idle reusable queue whose populated pool serves the owner's VM and fits, bound at once; a vacant reusable queue no other owner is re-arming, re-armed with fresh backing off the device mutex and bound as the sibling through the primary's own rearm_vacant(), rearm_compute() and bind_rearmed(); a fresh QID; and last an idle reusable queue whose pool still serves another VM, given back (give_back_foreign(), which rebind_compute() now shares) while no other pool release is in flight, so the next pool pass vacates it for a later attempt. Only reusable queues qualify: a queue with an owner or work, an open owner's idle channel, a queue another owner is re-arming and one whose scheduler or pool release is in flight are never taken, and an owner waiting for its first channel goes first. Once earlier clients had taken compute QIDs up to the fresh-QID ceiling, every idle queue was vacant or held a gone VM's pool, so admitting only same-VM pools and fresh QIDs never brought a sibling up again until the GPU slept. A miss backs off for SIBLING_HEADROOM_BACKOFF_NS. - Each QID keeps the completion-class implicit parent while its own earlier kick is active; dependent compute and render consumers wait on every channel of the owner. Siblings release and roll back before the primary, idle siblings drain before primary pool growth, and a ContextKill cookie and its acknowledgment cover every channel. GET_PARAMS reports the new DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL wherever a logical compute queue holds more than one channel (pairs::compute_channels_per_owner() > 1), so userspace that would open sibling queues of its own for the same overlap leaves it to the kernel instead of fanning out twice. Only the M5 Pro reports it: the other M5 boards describe one channel, and G17P never selects an M5 board. The feature takes bit 42, the next free bit: bit 40 is DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE and bit 41 is DRM_ASAHI_FEATURE_COMPUTE_ONLY. Mesa's Vulkan driver reads the bit and then leaves the sibling queues to the kernel (aurora-silicon/mesa#793). Host tests: tools/asahi/g17-m5-sibling-gate-tests.py compiles the gate, the in-flight threshold, the direct-path channel selection, the ComputeCell mirror and the registry's channel selection and sibling admission, with 17 mutation controls; g17-m5-sibling-rearm-tests.py runs the production reuse predicates, sibling sources, give-back, pool pass and re-arm for clients that come and go with no fresh QID left (14 controls, the old admission rule among them); g17-compute-multi-channel-feature-tests.py reads every production board's channel count and checks where the feature is reported, that the decision ignores the encoding forms and that its bit is unique (9 controls); g17-compute-owed-stamp-tests.py runs the real retirement pass against the heavy-kick run (2 more controls); g17-m5-sibling-compute-tests.py covers identities, dedicated pools, routing, release, rollback, growth and exit ordering (8 controls). Link: https://github.com/aurora-silicon/mesa/pull/793 Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/file.rs | 4 + drivers/gpu/drm/asahi/g17/context.rs | 40 +- drivers/gpu/drm/asahi/g17/fw/m5/compute.rs | 23 +- drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs | 28 + drivers/gpu/drm/asahi/g17/mod.rs | 14 +- drivers/gpu/drm/asahi/g17/pairs.rs | 76 +- drivers/gpu/drm/asahi/g17/queue/compute.rs | 270 +++- drivers/gpu/drm/asahi/g17/queue/render.rs | 38 +- drivers/gpu/drm/asahi/g17/runtime.rs | 1234 +++++++++++++++-- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 64 +- .../drm/asahi/g17/runtime/compute_control.rs | 12 +- .../gpu/drm/asahi/g17/runtime/compute_exit.rs | 30 +- .../drm/asahi/g17/runtime/compute_replay.rs | 32 +- .../drm/asahi/g17/runtime/render/submit.rs | 25 +- include/uapi/drm/asahi_drm.h | 9 + tools/asahi/g17-capacity-fault-tests.py | 18 +- tools/asahi/g17-compute-deadline-tests.py | 20 +- .../g17-compute-growth-deadline-tests.py | 4 + ...g17-compute-multi-channel-feature-tests.py | 243 ++++ tools/asahi/g17-compute-owed-stamp-tests.py | 92 +- tools/asahi/g17-growth-tests.py | 6 +- tools/asahi/g17-m5-cross-qid-direct-tests.py | 2 +- .../g17-m5-multiqueue-contention-tests.py | 2 +- tools/asahi/g17-m5-sibling-compute-tests.py | 660 +++++++++ tools/asahi/g17-m5-sibling-gate-tests.py | 527 +++++++ tools/asahi/g17-m5-sibling-rearm-tests.py | 646 +++++++++ tools/asahi/g17-pool-release-tests.py | 3 +- tools/asahi/run-host-tests.py | 26 +- 28 files changed, 3893 insertions(+), 255 deletions(-) create mode 100755 tools/asahi/g17-compute-multi-channel-feature-tests.py create mode 100755 tools/asahi/g17-m5-sibling-compute-tests.py create mode 100755 tools/asahi/g17-m5-sibling-gate-tests.py create mode 100755 tools/asahi/g17-m5-sibling-rearm-tests.py diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 0883715502766..aedad5c0bdeb7 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -106,6 +106,10 @@ pub(crate) const DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION: u32 = /// (`drm_asahi_queue_create::compute_timeout_ms`). pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT: u64 = uapi::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT as u64; +/// The kernel spreads one compute queue's independent commands over several firmware compute +/// queues itself. +pub(crate) const DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: u64 = + uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL as u64; /// The tiling half waits only on the render and compute prefixes of the command's stage-prefix /// fields, its fragment half on the whole ones. #[allow(dead_code)] diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 84b519795da73..df8c3da1494f6 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -214,9 +214,12 @@ pub(crate) struct Context { /// A kill of this context was published, through a compute queue or on its render pairs' /// behalf. A context is killed at most once. kill_published: AtomicBool, - /// Advisory only: publication still checks the physical binding under the - /// device mutex. False skips an inline attempt known to need admission. - compute_binding_hint: AtomicBool, + /// Advisory count of bound compute channels: publication still checks the physical binding + /// under the device mutex. Zero skips an inline attempt known to need admission. + compute_bindings: AtomicU32, + /// Shared monotonic compute completion ordinal / submit sequence across an M5 multi-channel + /// context's physical compute queues. + compute_ordinal: AtomicU32, /// Mixed-engine contexts keep the original inline publication path. render_seen: AtomicBool, qos: Arc, @@ -346,7 +349,8 @@ impl Context { scheduler_generation, published: AtomicBool::new(false), kill_published: AtomicBool::new(false), - compute_binding_hint: AtomicBool::new(false), + compute_bindings: AtomicU32::new(0), + compute_ordinal: AtomicU32::new(0), render_seen: AtomicBool::new(false), qos, owner_pid, @@ -373,7 +377,11 @@ impl Context { } pub(crate) fn compute_binding_hint(&self) -> bool { self.render_seen.load(Ordering::Acquire) - || self.compute_binding_hint.load(Ordering::Relaxed) + || self.compute_bindings.load(Ordering::Relaxed) != 0 + } + /// Advisory count of physical compute channels currently bound to this context. + pub(crate) fn compute_binding_count(&self) -> u32 { + self.compute_bindings.load(Ordering::Acquire) } /// This logical queue has submitted render work, so its compute may have a render prefix. pub(crate) fn render_seen(&self) -> bool { @@ -385,7 +393,27 @@ impl Context { } } pub(crate) fn note_compute_binding(&self, owned: bool) { - self.compute_binding_hint.store(owned, Ordering::Relaxed); + if owned { + self.compute_bindings.fetch_add(1, Ordering::AcqRel); + } else { + let _ = self + .compute_bindings + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| { + Some(n.saturating_sub(1)) + }); + } + } + /// Atomically allocates the next 1-based shared compute ordinal and packed + /// `(predecessor_id << 32) | current_id` descriptor object_ids pair for a multi-channel + /// M5 context, so concurrent direct submissions across sibling QIDs never collide on + /// `submit_sequence`, `completion_ordinal`, or `object_ids`. + pub(crate) fn next_compute_identity(&self) -> (u32, u64) { + let prev = self.compute_ordinal.fetch_add(1, Ordering::AcqRel); + let next = prev.wrapping_add(1); + let predecessor_id = if prev == 0 { 1 } else { prev }; + let current_id = if next == 0 { 1 } else { next }; + let object_ids = (u64::from(predecessor_id) << 32) | u64::from(current_id); + (next, object_ids) } pub(crate) fn compute_timestamps(&self) -> &Arc { &self.compute_timestamps diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs b/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs index a2d7205dfe9af..fd326e708f2dd 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/compute.rs @@ -48,10 +48,9 @@ pub(crate) fn explicit_dependency(board: &Board) -> u8 { /// Dependency class of a compute kick's implicit parent (the previous kick of its queue) on /// `board`. With the counted forms ([`counted_forms`]) it is class 1, which holds the kick until /// its parent has completed. On boards whose explicit waits take the completion class -/// ([`Board::completion_inputs`]) a parent the host has already retired (`parent_retired`) takes -/// the pipelined class instead, as macOS's late-published M5 Pro kicks do: there is nothing left -/// to hold for. Otherwise it is the pipelined class, with which a kick may start while its parent -/// still runs. +/// ([`Board::completion_inputs`]), a parent the host has already retired (`parent_retired`) takes +/// the pipelined class instead: there is nothing left on that physical QID to hold for. +/// Otherwise it is the pipelined class, with which a kick may start while its parent still runs. pub(crate) fn parent_dependency(board: &Board, parent_retired: bool) -> u8 { if !counted_forms(board) || (parent_retired && board.completion_inputs()) { COMPUTE_PIPELINED_DEPENDENCY @@ -60,6 +59,16 @@ pub(crate) fn parent_dependency(board: &Board, parent_retired: bool) -> u8 { } } +/// Whether `board` spreads a logical compute queue across multiple physical compute channels +/// ([`Board::compute_channels`]) sharing one context, QoS slot, scheduler page, and work-state +/// table, each with its own dedicated compute pool. Each physical QID still holds a +/// completion-class implicit parent while its own prior kick is active, preventing two kicks +/// from overlapping on one QID's single preemption/operand/usage state; concurrency comes +/// strictly from independent kicks running across distinct sibling QIDs. +pub(crate) fn multi_channel(board: &Board) -> bool { + board.compute_channels() > 1 +} + /// Whether compute kicks on `board` count their completion ordinal and hold for their parent: /// with the G17D forms, on boards whose explicit waits take the completion class /// ([`Board::completion_inputs`]), as macOS encodes M5 Pro compute, and on the J813, whose @@ -465,6 +474,8 @@ pub(crate) struct DescriptorArgs { pub(crate) stamp_va: [u64; 2], pub(crate) stamp_value: u32, pub(crate) qid: u32, + /// Per-context compute channel index (0, 1, 2 for a multi-channel owner; 0 otherwise). + pub(crate) channel_index: u32, pub(crate) kick_timestamp: u64, pub(crate) completion_ordinal: u32, pub(crate) status_va: [u64; 2], @@ -503,7 +514,8 @@ pub(crate) struct Descriptor { stamp_va: [u64; 2], stamp_value: u32, qid: u32, - reserved_f58: u64, + channel_index: u32, + reserved_f5c: u32, kick_timestamp: u64, current_id: u64, completion_ordinal: u32, @@ -574,6 +586,7 @@ impl Descriptor { self.stamp_va = args.stamp_va; self.stamp_value = args.stamp_value; self.qid = args.qid; + self.channel_index = args.channel_index; self.kick_timestamp = args.kick_timestamp; self.current_id = args.registers.object_ids as u32 as u64; self.completion_ordinal = args.completion_ordinal; diff --git a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs index d89a2c5756b22..b6f054d9328f6 100644 --- a/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/fw/m5/initdata.rs @@ -2441,6 +2441,9 @@ pub(crate) struct Board { /// Whether firmware accepts tiling kicks without an entry signal and retained /// render pairs kicked through the host port alone. pub(crate) host_only_render_kicks: bool, + /// Firmware compute queues of one context over which a single command queue's independent + /// kicks may run ([`Board::compute_channels`]). + compute_channels: u8, } /// M5 Pro: two clusters of ten cores. @@ -2471,6 +2474,9 @@ pub(crate) const J714: Board = Board { g17d_forms: false, completion_inputs: true, host_only_render_kicks: false, + // macOS runs one M5 Pro command queue on up to three firmware compute queues of the same + // context, created on demand and sharing one completion ordinal (its own kicks under aura). + compute_channels: 3, }; /// M5 Max: four clusters of ten cores. @@ -2506,6 +2512,7 @@ pub(crate) const J716C: Board = Board { // G17D has distinct kick encodings, and common 26A428 publishes descriptors // on the item ring. Qualify those interfaces separately. host_only_render_kicks: true, + compute_channels: 1, }; /// J775D's performance controllers run from P3. @@ -2548,6 +2555,7 @@ pub(crate) const J775D: Board = Board { g17d_forms: true, completion_inputs: false, host_only_render_kicks: false, + compute_channels: 1, }; /// M5 (T8142, MacBook Air J813): one cluster of ten core slots, eight enabled. Values from the @@ -2588,6 +2596,7 @@ pub(crate) const J813: Board = Board { g17d_forms: false, completion_inputs: false, host_only_render_kicks: false, + compute_channels: 1, }; /// The J813 on its macOS 27.2 (26B123) firmware: the same board on the common 26B123 graph. @@ -2596,6 +2605,17 @@ pub(crate) const J813_26B123: Board = Board { ..J813 }; +// Every board runs at least one compute channel per command queue and no more than the per-owner +// channel arrays hold. +const _: () = { + let mut boards = [&J714, &J716C, &J775D, &J813, &J813_26B123].as_slice(); + while let [board, rest @ ..] = boards { + assert!(board.compute_channels >= 1); + assert!(board.compute_channels as usize <= crate::g17::pairs::COMPUTE_CHANNELS_MAX); + boards = rest; + } +}; + const _: () = { use super::target::min_parameter_buffer_pages; assert!(J714.min_parameter_buffer as u64 == min_parameter_buffer_pages(J714.clusters) << 15); @@ -2966,6 +2986,14 @@ impl Board { self.completion_inputs } + /// Firmware compute queues of one context over which a single command queue's independent + /// kicks may run, each with its own preemption, operand, usage, status and stamp state and all + /// of them sharing the context's completion ordinal. 1 where the board's own macOS driver has + /// not been seen to spread a command queue: one firmware compute queue per command queue. + pub(crate) const fn compute_channels(&self) -> u8 { + self.compute_channels + } + /// Whether this is the J813, whose register programs macOS 27.0 writes in the common 26A428 /// forms rather than the M5 Pro's (read out of its own kicks under aura). pub(crate) const fn j813_forms(&self) -> bool { diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index dd0c3c2453686..9e3b5b3a08b1d 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1167,6 +1167,17 @@ const RETIRED_FEATURES: u64 = (uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE | uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_RENDER_STAGE_PREFIXES) as u64; const _: () = assert!(M5_FEATURES & RETIRED_FEATURES == 0); +/// The compute channel features of a GPU whose logical compute queues each hold up to `channels` +/// physical compute channels ([`pairs::compute_channels_per_owner`]): with more than one, the +/// kernel fans independent compute commands out itself. +fn compute_channel_features(channels: u8) -> u64 { + if channels > 1 { + crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL + } else { + 0 + } +} + /// Event work item ID. const EVENT_WORK: u64 = 0; /// Short control/retirement polls do not wait behind the longer idle deadline. @@ -2542,7 +2553,8 @@ impl gpu::Gpu for Gpu { | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_FRAGMENT_BARRIERS) | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | sync_output::FEATURE_CUMULATIVE_SIGNALS - | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT; + | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT + | compute_channel_features(pairs::compute_channels_per_owner()); let variant = self.shared.variant; // The M5 command set has no AS-build flag: its validation refuses one. if !variant.m5_commands { diff --git a/drivers/gpu/drm/asahi/g17/pairs.rs b/drivers/gpu/drm/asahi/g17/pairs.rs index c7515c1c76417..fe3f9d55b46ec 100644 --- a/drivers/gpu/drm/asahi/g17/pairs.rs +++ b/drivers/gpu/drm/asahi/g17/pairs.rs @@ -18,11 +18,21 @@ use crate::hw::t8140::queues::RENDER_PAIRS_MAX; /// G17D's count. const G17D_PAIRS: u8 = RENDER_PAIRS_MAX as u8; +/// Maximum physical compute channels one logical compute owner may hold: the most firmware +/// compute queues any board spreads one command queue over ([`Board::compute_channels`], three +/// on M5 Pro). It sizes the per-owner channel arrays and the compute waits of a render kick, so +/// every channel of an owner costs one dependency slot in each of its consumers. +/// +/// [`Board::compute_channels`]: crate::g17::fw::m5::initdata::Board::compute_channels +pub(crate) const COMPUTE_CHANNELS_MAX: usize = 3; + static PAIRS: AtomicU8 = AtomicU8::new(1); +static COMPUTE_CHANNELS: AtomicU8 = AtomicU8::new(1); -/// The count for the probed board, set once at probe (one GPU per system). +/// The counts for the probed board, set once at probe (one GPU per system). pub(crate) fn select_board(board: &crate::g17::fw::m5::initdata::Board) { PAIRS.store(if board.g17d_forms() { G17D_PAIRS } else { 1 }, Relaxed); + COMPUTE_CHANNELS.store(board.compute_channels(), Relaxed); } /// Render pairs a logical render queue created now may hold. @@ -30,6 +40,70 @@ pub(crate) fn per_owner() -> u8 { PAIRS.load(Relaxed) } +/// Physical compute channels a logical compute queue created now may hold. +pub(crate) fn compute_channels_per_owner() -> u8 { + COMPUTE_CHANNELS.load(Relaxed) +} + +/// GPU execution time of a compute kick, between the start and end timestamps of its firmware +/// execution record, from which the kick is worth a sibling channel. +/// +/// Measured on M5 Pro: one physical QID streams queued kicks back to back for about 11 us each; +/// the same kicks spread over three QIDs take about 16.4 us each, because every kick then pays +/// about 5 us of firmware arbitration between QIDs. A sibling only pays for itself through +/// overlapped execution, so the kick must run long enough for that cost to vanish into it: +/// 100 us is where the 5 us of arbitration falls to 5% of the kick, while a kick of a few +/// microseconds would spend more on arbitration than it runs. +pub(crate) const SIBLING_EXECUTION_NS: u64 = 100_000; + +/// [`SIBLING_EXECUTION_NS`] in the command timestamp ticks of an execution record. +const SIBLING_EXECUTION_TICKS: u64 = SIBLING_EXECUTION_NS + * crate::hw::t8140::resources::COMMAND_TIMESTAMP_HZ + / 1_000_000_000; + +/// Consecutive heavy kicks ([`SIBLING_EXECUTION_NS`]) after which a primary channel's execution is +/// sustained: a single long kick among short ones (a first dispatch, a cold pipeline) does not +/// fan its queue out. +pub(crate) const SIBLING_SUSTAINED_KICKS: u8 = 2; + +/// Kicks of an owner that must already be in flight on its compute channels before a new kick +/// may run beside them on a sibling channel. +/// +/// A kick queued behind one in flight on the same ring starts the moment its predecessor ends, +/// while the host turns that completion into the next submission (60 to 100 us). Two overlapped +/// kicks that each fill the shader cores share them and end together, both rings then wait for +/// the host, and every pair of kicks pays that turnaround. With two kicks already in flight the +/// primary ring keeps one queued behind the overlap, so a sibling only adds overlap and never +/// exposes the turnaround: an owner keeping at most two kicks in flight runs exactly as on one +/// ring. +pub(crate) const SIBLING_MIN_IN_FLIGHT: usize = 2; + +/// How long publication keeps to an owner's bound compute channels after no sibling could be found +/// (no reusable queue to bind or re-arm and no QID headroom) before it looks again. +pub(crate) const SIBLING_HEADROOM_BACKOFF_NS: u64 = 10_000_000; + +/// Whether a new kick of an owner with `in_flight` kicks in flight on its compute channels may +/// overlap them on a sibling channel ([`SIBLING_MIN_IN_FLIGHT`]). +pub(crate) fn overlaps(in_flight: usize) -> bool { + in_flight >= SIBLING_MIN_IN_FLIGHT +} + +/// Folds the execution record `[start, end]` of a retired compute kick into its channel's run of +/// consecutive heavy kicks. +pub(crate) fn heavy_run(run: u8, start: u64, end: u64) -> u8 { + if end.saturating_sub(start) >= SIBLING_EXECUTION_TICKS { + run.saturating_add(1) + } else { + 0 + } +} + +/// Whether a primary compute channel with this run of heavy kicks runs sustained heavy work, the +/// only work whose independent kicks fan out onto sibling channels. +pub(crate) fn sustained(run: u8) -> bool { + run >= SIBLING_SUSTAINED_KICKS +} + /// Renders a busy pair of a two-pair owner takes before its next render goes to /// an idle sibling: 1 keeps a queue at depth 1-2 on one pair. const SIBLING_BACKLOG: u8 = 1; diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index adc94dca1de4d..e24eb9813b5fc 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -268,7 +268,7 @@ impl Graph { &mut self, context: Arc, kick_alias: mmu::KernelMapping, - pool_alias: mmu::KernelMapping, + pool_alias: Option, ) -> Result { if !context.is_current() { return Err(EFAULT); @@ -290,7 +290,7 @@ impl Graph { .map(|context| context.alias_in(vm, private.clone(), page, prot)).transpose()?; Ok(Binding { _kick_alias: kick_alias, - pool_alias: Some(pool_alias), + pool_alias, descriptors: Some(descriptors), preempt, usage, @@ -368,12 +368,8 @@ impl Graph { fn vacate_ring(&mut self) -> Option { self.ring.take() } - fn rearm_ring(&mut self, ring: DescriptorRing) -> Result { - if self.ring.is_some() { - return Err(EBUSY); - } - self.ring = Some(ring); - Ok(()) + fn rearm_ring(&mut self, ring: DescriptorRing) -> Option { + self.ring.replace(ring) } /// `cursors`: this publication's snapshot (M5), else a fresh read. fn ensure_record_slot(&self, slot: usize, cursors: Option) -> Result { @@ -648,6 +644,14 @@ pub(crate) struct AdmissionState { pub(crate) struct Queue { owner: Option, + /// Per-owner channel index (0 for primary, 1..COMPUTE_CHANNELS_MAX for M5 siblings). + channel_index: u8, + /// Whether this queue currently holds a `Context::note_compute_binding(true)` count. + binding_noted: bool, + /// Consecutive retired kicks of the bound owner whose firmware execution record ran at least + /// [`crate::g17::pairs::SIBLING_EXECUTION_NS`] ([`crate::g17::pairs::heavy_run`]); zero for a + /// new owner. + heavy_run: u8, /// Scheduler/work pages of an exited last owner whose context was dropped; /// the installed queue record still names them until the next owner binds. retained_owner: Option, @@ -739,19 +743,56 @@ impl Queue { program: ComputeProgram, m5: bool, mcache: bool, + ) -> Result { + Self::new_channel( + alloc, + objects, + backing, + owner, + context, + pointers, + operand_state, + board, + program, + m5, + mcache, + 0, + ) + } + + #[expect( + clippy::too_many_arguments, + reason = "A sibling compute queue takes the same physical graph inputs plus its channel identity." + )] + pub(crate) fn new_channel( + alloc: &Allocator<'_>, + objects: &Arc, + backing: Backing, + owner: u64, + context: Arc, + pointers: PointerLayout, + operand_state: &'static OperandState, + board: Option<&'static Board>, + program: ComputeProgram, + m5: bool, + mcache: bool, + channel_index: u8, ) -> Result { let Backing { mut pool, mut kick } = backing; let (active, replays) = (Fifo::new()?, Fifo::new()?); let mut graph = Graph::new(alloc, objects, &context, pointers, operand_state, board, program, m5, mcache)?; let kick_alias = kick.map_client(context.vm())?; - let pool_alias = pool.map_client(context.vm())?; + let pool_alias = Some(pool.map_client(context.vm())?); let binding = graph.bind(context.clone(), kick_alias, pool_alias)?; context.mark_published(); context.note_compute_binding(true); crate::g17::trace::bind(crate::g17::trace::COMPUTE, kick.id().qid(), context.id(), 0); Ok(Self { owner: Some(owner), + channel_index, + binding_noted: true, + heavy_run: 0, retained_owner: None, pool_phase: PoolPhase::Populated, release_sent_ns: None, @@ -870,6 +911,46 @@ impl Queue { pub(crate) fn owner(&self) -> Option { self.owner } + pub(crate) fn channel_index(&self) -> u8 { + self.channel_index + } + pub(crate) fn is_primary(&self) -> bool { + self.channel_index == 0 + } + pub(crate) fn active_len(&self) -> usize { + self.active.len + } + pub(crate) fn has_replays(&self) -> bool { + self.replays.len != 0 + } + pub(crate) fn configuring(&self) -> bool { + self.configuration.is_some() + } + pub(crate) fn has_ring(&self) -> bool { + self.graph.ring.is_some() + } + /// The bound owner's recent kicks on this channel ran sustained heavy work + /// ([`crate::g17::pairs::sustained`]). + pub(crate) fn sustained(&self) -> bool { + crate::g17::pairs::sustained(self.heavy_run) + } + fn clear_binding_note(&mut self) { + if self.binding_noted { + if let Some(binding) = &self.binding { + binding.context.note_compute_binding(false); + } + self.binding_noted = false; + } + } + fn clear_owner(&mut self, stamp_released_at: bool) { + self.clear_binding_note(); + self.owner = None; + self.channel_index = 0; + self.heavy_run = 0; + if stamp_released_at { + self.released_at = now_ns(); + } + } /// The bound owner's context; `None` once an exited owner was detached. pub(crate) fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) @@ -1282,8 +1363,7 @@ impl Queue { drop(self.previous.take()); self.retirement_ready = self.active.len == 0; if self.released && self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } // It was reported when it retired: step past it. @@ -1295,6 +1375,9 @@ impl Queue { self.active.get_mut(at).ok_or(EIO)?.qos_pending = false; } let front = self.active.get(at).ok_or(EIO)?; + // Only an exact execution record measures the kick: a recordless retirement + // carries a synthesized envelope. + let execution = front.observed.map(|record| record.timestamps); if let Some(ticket) = front.ticket { crate::g17::recovery::note_retired(); crate::g17::trace::complete( @@ -1318,6 +1401,9 @@ impl Queue { Err(error) => Deferred::Retired(completion, Err(error)), })?; self.retire_pending = false; + if let Some([start, end]) = execution { + self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, start, end); + } if stampless || at != 0 { // A completion record is no witness that the firmware is done with the // descriptor: it can still store the stamp through it. Keep the command @@ -1340,8 +1426,7 @@ impl Queue { drop(self.previous.take()); self.retirement_ready = self.active.len == 0; if self.released && self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(None) | Err(EAGAIN) => { @@ -1514,8 +1599,7 @@ impl Queue { self.retire_pending = false; self.retirement_ready = true; if self.released { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(()) @@ -1880,6 +1964,27 @@ impl Queue { && !self.source_hint.has_readers(&self.source_readers) } pub(crate) fn bind_owner(&mut self, owner: u64, context: Arc) -> Result { + self.bind_owner_channel(owner, context, 0) + } + /// Binds a reusable physical queue with its own dedicated compute pool as an additional + /// compute channel of `owner`. + pub(crate) fn bind_sibling( + &mut self, + owner: u64, + context: Arc, + channel_index: u8, + ) -> Result { + if !self.graph.m5 || self.pool_phase != PoolPhase::Populated || self.graph.ring.is_none() { + return Err(EBUSY); + } + self.bind_owner_channel(owner, context, channel_index) + } + fn bind_owner_channel( + &mut self, + owner: u64, + context: Arc, + channel_index: u8, + ) -> Result { if !self.reusable() { return Err(EBUSY); } @@ -1927,7 +2032,7 @@ impl Queue { self.kick.clear_ring()?; let kick_alias = self.kick.map_client(context.vm())?; let pool_alias = self.pool.map_client(context.vm())?; - self.graph.bind(context.clone(), kick_alias, pool_alias) + self.graph.bind(context.clone(), kick_alias, Some(pool_alias)) })(); let binding = match moved { Ok(binding) => binding, @@ -1953,7 +2058,9 @@ impl Queue { self.retained_owner = None; } context.mark_published(); + self.clear_binding_note(); context.note_compute_binding(true); + self.binding_noted = true; crate::g17::trace::bind( crate::g17::trace::COMPUTE, self.qid(), @@ -1961,6 +2068,8 @@ impl Queue { if same_vm { 2 } else { 1 }, ); self.owner = Some(owner); + self.channel_index = channel_index; + self.heavy_run = 0; self.rearm_for = None; self.unpublished_binding = true; self.released = false; @@ -1971,10 +2080,9 @@ impl Queue { /// True allows the registry to cancel the never-published QID and drop this graph. An /// installed graph remains retained even after the logical owner exits without work. pub(crate) fn release_owner(&mut self) -> Result { - if let Some(binding) = &self.binding { - binding.context.note_compute_binding(false); - } + self.clear_binding_note(); if !self.installed && self.active.len == 0 && !self.quarantined && self.previous.is_none() { + self.clear_owner(false); return Ok(true); } self.released = true; @@ -2007,8 +2115,7 @@ impl Queue { self.retirement_ready = true; } if self.retirement_ready { - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); } } Ok(false) @@ -2036,6 +2143,25 @@ impl Queue { // exited owner's idle queue left a later command retired without a completion stamp. Some(binding) } + /// A recycled vacant sibling queue whose descriptor ring still awaits off-lock release + /// before re-arming with fresh backing. + pub(crate) fn take_recycled_ring(&mut self) -> Option { + if !self.recycled_pending() || self.pool_phase != PoolPhase::Vacant || self.graph.ring.is_none() + { + return None; + } + let descriptors = self + .binding + .as_mut() + .and_then(|binding| binding.descriptors.take()); + let ring = self.graph.vacate_ring(); + Some(Vacated { + _alias: None, + _pages: None, + _descriptors: descriptors, + _ring: ring, + }) + } /// An idle retained queue whose USC backing may be given back. pub(crate) fn vacate_candidate(&self) -> bool { self.pool_phase == PoolPhase::Populated @@ -2147,10 +2273,9 @@ impl Queue { self.replay_prepared = false; self.submitted = 0; self.kick.clear_parent_after_recovery(); - self.owner = None; + self.clear_owner(true); self.released = true; self.retirement_ready = true; - self.released_at = now_ns(); self.needs_fresh_backing = true; Ok(()) } @@ -2225,21 +2350,40 @@ impl Queue { })) } /// Installs fresh backing into a vacant pool; returns the descriptor row data - /// the caller writes before binding an owner. + /// the caller writes before binding an owner, plus any previous sibling descriptor + /// ring to drop off-lock. pub(crate) fn rearm( &mut self, pages: crate::g17::freelist::Pages, ring: DescriptorRing, - ) -> Result { + ) -> Result<(PoolDescriptor, Option)> { if !self.can_rearm() { return Err(EAGAIN); } - self.graph.rearm_ring(ring)?; - self.pool.rearm(pages)?; + let descriptors = self + .binding + .as_mut() + .and_then(|binding| binding.descriptors.take()); + let old_ring = self.graph.rearm_ring(ring); + if let Err(error) = self.pool.rearm(pages) { + if let Some(old) = old_ring { + let _ = self.graph.rearm_ring(old); + } + if let (Some(binding), Some(descriptors)) = (self.binding.as_mut(), descriptors) { + binding.descriptors = Some(descriptors); + } + return Err(error); + } self.pool_phase = PoolPhase::Populated; self.release_sent_ns = None; self.needs_fresh_backing = false; - self.pool.descriptor() + let vacated = (old_ring.is_some() || descriptors.is_some()).then_some(Vacated { + _alias: None, + _pages: None, + _descriptors: descriptors, + _ring: old_ring, + }); + Ok((self.pool.descriptor()?, vacated)) } pub(crate) fn pool_fits(&self, required: ComputeCapacity) -> bool { !self.growing && self.pool_phase == PoolPhase::Populated && self.pool.fits_capacity(required) @@ -2473,16 +2617,43 @@ impl Queue { status: &Arc, through: Option, recovery_state: u32, + ) -> Result> { + self.dependency_checked(owner, status, through, recovery_state, false) + } + + /// As [`Self::dependency`], additionally requiring every covered active kick to carry a + /// visible completion (`DRM_ASAHI_COMPUTE_VISIBLE_COMPLETION`) when `require_visible` is set. + /// A covered kick without visible completion returns `EAGAIN` so the consumer waits for it + /// to retire on the host. + pub(crate) fn dependency_checked( + &self, + owner: u64, + status: &Arc, + through: Option, + recovery_state: u32, + require_visible: bool, ) -> Result> { if through.is_none() || self.owner != Some(owner) { return Ok(None); } - let Some(active) = self + let mut newest = None; + for active in self .active .iter() .filter(|a| crate::g17::job::Order::contains(through, a.packet.order.sequence)) - .last() - else { + { + if require_visible { + let visible = matches!( + &active.packet.command, + crate::g17::command::Validated::Compute { visible_completion: true, .. } + ); + if !visible { + return Err(EAGAIN); + } + } + newest = Some(active); + } + let Some(active) = newest else { return Ok(None); }; if self.quarantined && self.spared_quarantine { @@ -2789,13 +2960,22 @@ impl Queue { let predecessor = KickPredecessor::new(qid, kick_parent)?; let matrix_ops = self.graph.m5 && *requested_matrix_ops; let m5_board = if self.graph.m5 { Some(self.graph.board.ok_or(EINVAL)?) } else { None }; - // Every earlier kick of this queue has retired, so the parent has completed. + // Each physical QID owns a single preemption/operand/usage/status/stamp set: only take the + // pipelined parent class once every earlier kick on this physical channel has retired. + // On multi-channel boards (M5 Pro), concurrency comes strictly from independent kicks + // running across distinct sibling QIDs because they carry no barrier on each other. let parent_retired = self.active.len == 0 && self.replays.len == 0 && !self.quarantined && !self.awaiting_witness; let parent_class = m5_board .map(|board| crate::g17::fw::m5::compute::parent_dependency(board, parent_retired)); + let multi_channel = m5_board.is_some_and(crate::g17::fw::m5::compute::multi_channel); + let (m5_ordinal, m5_object_ids) = if multi_channel { + packet.context.next_compute_identity() + } else { + (self.ordinal, 0x0000_0001_0000_0001) + }; let m5_args = m5_board.zip(parent_class).map(|(board, parent_class)| { let tuple = crate::g17::fw::m5::compute::kick_tuple(board, parent_class); crate::g17::fw::m5::compute::DescriptorArgs { @@ -2807,7 +2987,7 @@ impl Queue { preempt_va: addresses.preempt, cdm_va: *cdm_va, operand_va: addresses.operand, usage_va: addresses.usage, free_list_slot: u32::from(self.pool.id()), context_id: args.context_id, work_state: work_word, - object_ids: 0x0000_0001_0000_0001, + object_ids: m5_object_ids, resource_policy: plan.map_or(0xf5_0040_0020, |p| u64::from(p.pressure) << 32 | 0x0040_0020), preempt_state_offset: tuple.preempt_state_offset, // The board's core layout sizes the operand state, as on G17P. @@ -2822,13 +3002,15 @@ impl Queue { }, common26_tail: board.graph.is_common26(), descriptor_va: descriptor_low, - // M5 Pro's descriptors carry the ordinal as the submission sequence too, as macOS's do. - submit_sequence: if board.completion_inputs() { u64::from(self.ordinal) } else { 0 }, + // M5 Pro's descriptors carry the shared context ordinal as both submit_sequence and + // completion_ordinal. + submit_sequence: if board.completion_inputs() { u64::from(m5_ordinal) } else { 0 }, work_state_va: work_node, cdm_end_va: *cdm_end_va, stamp_va: [args.stamp_va, args.aux_stamp_va], stamp_value: crate::g17::fw::stamp_value(kick_timestamp.get() as u32), qid: u32::from(qid), + channel_index: if multi_channel { u32::from(self.channel_index) } else { 0 }, kick_timestamp: kick_timestamp.get(), - completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, self.ordinal), + completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, m5_ordinal), status_va: args.status_va, timestamp_va: [timestamp_va, timestamp_va + 8], shared_control_va: self.pool.control_va(), event_metadata: crate::g17::fw::m5::compute::completion_forms(board).1, @@ -2949,7 +3131,8 @@ impl Queue { let target = self.pool.reserve_submission()?; let qos = host.qos_publish(qos::Owner { qid, qos: identity.qos, data_master: 2 }, identity.scheduler, policy).or_else(|error| { - self.pool.cancel_unpublished(target)?; Err(error) + self.pool.cancel_unpublished(target)?; + Err(error) })?; self.active.back_mut().ok_or(EIO)?.qos_pending = true; // `cursors` is this publication's snapshot: no second read of the ring. @@ -3184,7 +3367,7 @@ impl Queue { self.configuration.take().ok_or(EIO)?.release(); if self.ordinal == 0 && self.active.len == 0 && self.replays.len == 0 { self.retirement_ready = true; - if self.released { self.owner = None; } + if self.released { self.clear_owner(false); } } Ok(()) } @@ -3596,7 +3779,9 @@ impl Queue { { return Ok((false, None)); } + self.clear_binding_note(); if !self.installed { + self.clear_owner(false); return Ok((true, None)); } let mut retired = None; @@ -3618,12 +3803,17 @@ impl Queue { self.unpublished_binding = false; self.retirement_ready = true; self.released = true; - self.owner = None; - self.released_at = now_ns(); + self.clear_owner(true); Ok((false, retired)) } } +impl Drop for Queue { + fn drop(&mut self) { + self.clear_binding_note(); + } +} + impl Queue { /// Same immutable singleton identity and current physical epoch. pub(crate) fn has_input_source( diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index de4760aec5f0a..42037e834357c 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -53,8 +53,10 @@ pub(crate) struct RenderDependencies { pub(crate) render_tiling_count: usize, pub(crate) tiling: [KickDependency; 2], pub(crate) tiling_count: usize, - pub(crate) compute: Option, - pub(crate) fragment_compute: Option, + pub(crate) compute: [KickDependency; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + pub(crate) compute_count: usize, + pub(crate) fragment_compute: [KickDependency; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + pub(crate) fragment_compute_count: usize, /// Fragment kicks of other pairs' overlapping same-VM renders. pub(crate) hazards: [KickDependency; crate::g17::hazard::PUBLICATION_BARRIERS], pub(crate) hazard_count: usize, @@ -68,8 +70,10 @@ impl RenderDependencies { render_tiling_count: 0, tiling: [KickDependency::ZERO; 2], tiling_count: 0, - compute: None, - fragment_compute: None, + compute: [KickDependency::ZERO; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + compute_count: 0, + fragment_compute: [KickDependency::ZERO; crate::g17::pairs::COMPUTE_CHANNELS_MAX], + fragment_compute_count: 0, hazards: [KickDependency::ZERO; crate::g17::hazard::PUBLICATION_BARRIERS], hazard_count: 0, }; @@ -671,12 +675,12 @@ impl Pair { /// 1 the tiling encoder, 2 a full channel or compute completion, 3 the /// fragment encoder; the last class is the implicit parent's. struct RenderBarriers { - tiling: [KickDependency; 5], + tiling: [KickDependency; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], tiling_count: usize, - fragment: [KickDependency; 4 + crate::g17::hazard::PUBLICATION_BARRIERS], + fragment: [KickDependency; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], fragment_count: usize, - tiling_types: [u8; 6], - fragment_types: [u8; 5 + crate::g17::hazard::PUBLICATION_BARRIERS], + tiling_types: [u8; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], + fragment_types: [u8; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], } /// The last fragment kick published on any pair, and the last one of a render with an API task @@ -743,12 +747,14 @@ fn render_barriers( compute_class: u8, ) -> RenderBarriers { let fragment_stage = fragment_stage || stage_prefixes; - let mut tiling_barriers = [KickDependency::ZERO; 5]; + let mut tiling_barriers = [KickDependency::ZERO; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; let mut tiling_count = 0; - let mut fragment_barriers = [own_tiling; 4 + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut fragment_barriers = + [own_tiling; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut fragment_count = 1; - let mut tiling_types = [1; 6]; - let mut fragment_types = [3; 5 + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut tiling_types = [1; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; + let mut fragment_types = + [3; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; fragment_types[0] = 1; for dependency in &dependencies.render_tiling[..dependencies.render_tiling_count] { tiling_barriers[tiling_count] = *dependency; @@ -778,13 +784,13 @@ fn render_barriers( } } } - if let Some(compute) = dependencies.compute { - tiling_barriers[tiling_count] = compute; + for compute in &dependencies.compute[..dependencies.compute_count] { + tiling_barriers[tiling_count] = *compute; tiling_types[tiling_count] = compute_class; tiling_count += 1; } - if let Some(compute) = dependencies.fragment_compute { - fragment_barriers[fragment_count] = compute; + for compute in &dependencies.fragment_compute[..dependencies.fragment_compute_count] { + fragment_barriers[fragment_count] = *compute; fragment_types[fragment_count] = compute_class; fragment_count += 1; } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index ea9a245e6ea2d..db17e21efc821 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -82,6 +82,15 @@ pub(super) struct ComputeCell { queue: kernel::sync::Mutex>>, /// Lock-free mirror of the installed queue's QID (`u8::MAX` when empty). qid: core::sync::atomic::AtomicU8, + /// Lock-free mirror of `(configuring, active_len, last_published)` updated while the cell + /// mutex is held, so `compute_direct()` can keep single-in-flight work on channel 0 without + /// locking sibling cells and pick the least-loaded channel without extra mutex trips. + active_len: core::sync::atomic::AtomicU32, + configuring: core::sync::atomic::AtomicBool, + last_published: core::sync::atomic::AtomicU64, + /// Lock-free mirror of [`compute::Queue::sustained`], so `compute_direct()` keeps every kick + /// of an owner whose primary channel runs short kicks on that channel without a lock. + sustained: core::sync::atomic::AtomicBool, } impl ComputeCell { @@ -90,6 +99,10 @@ impl ComputeCell { pin_init!(Self { queue <- kernel::new_mutex!(None, "g17::ComputeCell::queue"), qid: core::sync::atomic::AtomicU8::new(u8::MAX), + active_len: core::sync::atomic::AtomicU32::new(0), + configuring: core::sync::atomic::AtomicBool::new(false), + last_published: core::sync::atomic::AtomicU64::new(0), + sustained: core::sync::atomic::AtomicBool::new(false), }), GFP_KERNEL, ) @@ -100,22 +113,68 @@ impl ComputeCell { (qid != u8::MAX).then_some(qid) } + fn sync_stats(&self, queue: Option<&compute::Queue>) { + match queue { + Some(queue) => { + self.active_len + .store(queue.active_len() as u32, Ordering::Release); + self.configuring + .store(queue.configuring(), Ordering::Release); + self.last_published + .store(queue.last_published(), Ordering::Release); + self.sustained.store(queue.sustained(), Ordering::Release); + } + None => { + self.active_len.store(0, Ordering::Release); + self.configuring.store(false, Ordering::Release); + self.last_published.store(0, Ordering::Release); + self.sustained.store(false, Ordering::Release); + } + } + } + + /// Lock-free routing hint `(configuring, active_len, last_published)`. + pub(super) fn load_hint(&self) -> (bool, u32, u64) { + ( + self.configuring.load(Ordering::Acquire), + self.active_len.load(Ordering::Acquire), + self.last_published.load(Ordering::Acquire), + ) + } + + /// Lock-free hint: this cell's queue runs sustained heavy work ([`compute::Queue::sustained`]). + pub(super) fn sustained(&self) -> bool { + self.sustained.load(Ordering::Acquire) + } + /// The installed queue, locked; None once the registry gave it up. pub(super) fn lock(&self) -> Option> { - QueueGuard::new(self.queue.lock()) + QueueGuard::new(self, self.queue.lock()) } } /// A locked installed queue. pub(super) struct QueueGuard<'a> { + cell: &'a ComputeCell, queue: core::ptr::NonNull, _guard: kernel::sync::MutexGuard<'a, Option>>, } impl<'a> QueueGuard<'a> { - fn new(mut guard: kernel::sync::MutexGuard<'a, Option>>) -> Option { + fn new( + cell: &'a ComputeCell, + mut guard: kernel::sync::MutexGuard<'a, Option>>, + ) -> Option { let queue = core::ptr::NonNull::from((*guard).as_deref_mut()?); - Some(Self { queue, _guard: guard }) + Some(Self { cell, queue, _guard: guard }) + } +} + +impl Drop for QueueGuard<'_> { + fn drop(&mut self) { + // SAFETY: `_guard` drops after `Drop::drop`, so `self.queue` remains locked and valid. + let queue = unsafe { self.queue.as_ref() }; + self.cell.sync_stats(Some(queue)); } } @@ -157,15 +216,17 @@ impl ComputeSlot { /// Gives the queue up to the caller, which drops it outside the cell lock. fn take(&mut self) -> Option> { let mut guard = self.0.queue.lock(); - let taken = guard.take(); + let queue = guard.take(); self.0.qid.store(u8::MAX, Ordering::Release); - taken + self.0.sync_stats(None); + queue } fn put(&mut self, queue: Option>) { let qid = queue.as_ref().map_or(u8::MAX, |queue| queue.qid()); let old = { let mut guard = self.0.queue.lock(); self.0.qid.store(qid, Ordering::Release); + self.0.sync_stats(queue.as_deref()); core::mem::replace(&mut *guard, queue) }; drop(old); @@ -174,7 +235,12 @@ impl ComputeSlot { impl Drop for ComputeSlot { fn drop(&mut self) { - let queue = self.0.queue.lock().take(); + let queue = { + let mut guard = self.0.queue.lock(); + let queue = guard.take(); + self.0.sync_stats(None); + queue + }; drop(queue); } } @@ -260,23 +326,358 @@ impl Registry { } pub(super) fn compute(&self, owner: u64) -> Option> { + self.compute_primary(owner).or_else(|| { + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner)) + }) + } + + pub(super) fn compute_primary(&self, owner: u64) -> Option> { self.compute .iter() .flatten() .filter_map(|entry| entry.queue.as_deref()) - .find(|queue| queue.owner() == Some(owner)) + .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) } pub(super) fn compute_mut(&mut self, owner: u64) -> Option> { self.compute(owner) } - /// The cell of `owner`'s bound queue, which its publisher may lock without the device mutex. - pub(super) fn compute_cell(&self, owner: u64) -> Option> { - self.compute.iter().flatten().find_map(|entry| { - entry.queue.as_deref()?.owner().filter(|bound| *bound == owner)?; - Some(entry.queue.0.clone()) - }) + pub(super) fn compute_for_packet( + &self, + owner: u64, + packet: &Arc, + ) -> Option> { + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.owns_packet(packet)) + } + + pub(super) fn compute_for_packet_mut( + &mut self, + owner: u64, + packet: &Arc, + ) -> Option> { + self.compute_for_packet(owner, packet) + } + + /// Count and used channel-index bitmask of `owner`'s bound compute channels. + fn compute_channels_of(&self, owner: u64) -> (usize, u8) { + let mut count = 0usize; + let mut mask = 0u8; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + count += 1; + let idx = queue.channel_index(); + if idx < 8 { + mask |= 1u8 << idx; + } + } + (count, mask) + } + + fn next_sibling_index(&self, owner: u64, limit: u8) -> Option { + let (count, mask) = self.compute_channels_of(owner); + if count == 0 || count >= usize::from(limit) { + return None; + } + (1..limit).find(|idx| mask & (1u8 << idx) == 0) + } + + /// Where `owner`'s next sibling channel would come from, in the order [`Self::rebind_compute`] + /// gives a primary binding its channel: an idle reusable queue whose populated pool serves the + /// owner's VM and fits, else a vacant reusable queue no other owner is re-arming, else a fresh + /// QID, else an idle reusable queue whose pool still serves another VM (an exited owner's, + /// say), given back first while no other pool release is in flight. Only + /// [`compute::Queue::reusable`] queues whose scheduler release is not in flight qualify, so a + /// channel with an owner, work, a pending pool release or a closing context is never taken, + /// and neither is an open owner's idle channel, which only a primary binding may share. The + /// longest released queue goes first. None keeps the owner on its bound channels. + fn sibling_source( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> Option { + let teardown = &self.teardown; + let vm = context.vm(); + let (mut warm, mut vacant, mut foreign) = (None, None, None); + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.reusable()) + .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound))) + { + let best = if queue.pool_vacant() { + if !queue.rearm_open(owner) { + continue; + } + &mut vacant + } else if queue.pool_serves(vm) { + if queue.needs_fresh_backing() || !queue.pool_fits(required) || !queue.has_ring() { + continue; + } + &mut warm + } else { + &mut foreign + }; + let key = (queue.released_at(), queue.qid()); + if best.is_none_or(|old| key < old) { + *best = Some(key); + } + } + if let Some((_, qid)) = warm { + return Some(SiblingSource::Warm(qid)); + } + if let Some((_, qid)) = vacant { + return Some(SiblingSource::Vacant(qid)); + } + if self.qids.compute_fits(self.admission.queues() as usize) { + return Some(SiblingSource::Fresh); + } + // A pool release in flight ends in a vacant queue; give back one at a time. + if self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.vacancy_pending()) + { + return None; + } + foreign.map(|(_, qid)| SiblingSource::Foreign(qid)) + } + + /// Whether a sibling channel for `owner` is available now ([`Self::sibling_source`]). + fn has_compute_sibling_headroom( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> bool { + self.sibling_source(owner, context, required).is_some() + } + + /// Whether `owner` benefits from acquiring another compute channel now: its primary channel + /// runs sustained heavy work ([`compute::Queue::sustained`]), all currently bound channels are + /// busy with at least [`super::pairs::SIBLING_MIN_IN_FLIGHT`] kicks in flight between them, no + /// replay is pending on any of them, and a sibling source exists + /// ([`Self::has_compute_sibling_headroom`]). A primary channel streaming short kicks never + /// brings up a sibling: its ring runs them faster than several QIDs would. + fn wants_compute_sibling( + &self, + owner: u64, + context: &Arc, + limit: u8, + required: super::freelist::ComputeCapacity, + ) -> bool { + if limit <= 1 || self.next_sibling_index(owner, limit).is_none() { + return false; + } + let mut sustained_primary = false; + let mut all_busy = true; + let mut in_flight = 0usize; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + if queue.has_replays() { + return false; + } + if queue.is_primary() { + sustained_primary = queue.sustained(); + } + if queue.active_len() == 0 && !queue.configuring() { + all_busy = false; + } + in_flight += queue.active_len(); + } + if !sustained_primary || !all_busy || !super::pairs::overlaps(in_flight) { + return false; + } + self.has_compute_sibling_headroom(owner, context, required) + } + + /// Binds a warm sibling source ([`SiblingSource::Warm`]) as an additional compute channel of + /// `owner`. Returns `Ok(Some(true))` if bound, `Ok(Some(false))` if no warm queue is ready (a + /// vacant queue to re-arm, a fresh QID or another VM's idle queue to give back is built or + /// released off the device mutex, [`Backend::try_add_compute_sibling`]), or `Ok(None)` if no + /// sibling slot is needed. + fn bind_reusable_sibling( + &mut self, + owner: u64, + context: &Arc, + limit: u8, + required: super::freelist::ComputeCapacity, + ) -> Result> { + let Some(channel_index) = self.next_sibling_index(owner, limit) else { + return Ok(None); + }; + let Some(SiblingSource::Warm(qid)) = self.sibling_source(owner, context, required) else { + return Ok(Some(false)); + }; + self.compute_queue_mut(qid) + .ok_or(EIO)? + .bind_sibling(owner, context.clone(), channel_index)?; + Ok(Some(true)) + } + + /// The installed compute queue with QID `qid`. + fn compute_queue_mut(&mut self, qid: u8) -> Option> { + self.compute + .iter_mut() + .flatten() + .filter_map(|entry| entry.queue.as_deref_mut()) + .find(|queue| queue.qid() == qid) + } + + /// Gives back the idle reusable queue `qid`, whose pool serves another VM, for fresh backing: + /// the next pool pass releases its pool ([`Self::vacate_idle_pools`]) and leaves it vacant, + /// ready to re-arm for the VM that asked. + fn give_back_foreign(&mut self, qid: u8) -> Result { + self.compute_queue_mut(qid).ok_or(EIO)?.require_fresh_backing(); + Ok(()) + } + + /// Picks the bound compute channel of `owner` for `packet`. A command with cross-queue input + /// sources always takes the primary channel, so a chain of semaphore hops between queues + /// stays on one ring per queue. Dependent commands stay on the sole active channel when only + /// one is active so the implicit parent covers them without cross-channel barriers. Other + /// commands take the primary channel unless it runs sustained heavy work + /// ([`compute::Queue::sustained`]) and enough kicks are in flight to overlap + /// ([`super::pairs::overlaps`]); then they spread across the least-loaded channel (oldest + /// `last_published` breaks ties). + fn select_compute_channel(&self, owner: u64, packet: &super::job::Packet) -> Option { + let primary = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) + .map(|queue| (queue.qid(), queue.sustained())); + if let Some((qid, _)) = primary.filter(|_| packet.completion.sources().is_some()) { + return Some(qid); + } + if packet.order.wait_through[1].is_some() { + let mut active_qid = None; + let mut active_channels = 0usize; + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + if queue.active_len() != 0 || queue.configuring() { + active_qid = Some(queue.qid()); + active_channels += 1; + } + } + if active_channels == 1 { + return active_qid; + } + } + if let Some((qid, false)) = primary { + return Some(qid); + } + let in_flight: usize = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .map(|queue| queue.active_len()) + .sum(); + if let Some((qid, _)) = primary.filter(|_| !super::pairs::overlaps(in_flight)) { + return Some(qid); + } + self.compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .min_by_key(|queue| { + ( + queue.configuring(), + queue.active_len(), + queue.last_published(), + queue.channel_index(), + ) + }) + .map(|queue| queue.qid()) + } + + /// Appends covered active compute kicks from every compute channel of `owner` other than + /// `exclude_qid` into `frontier`. On boards whose firmware waits require visible completion + /// (`require_visible`), any covered kick on another channel without it returns `EAGAIN`. + pub(super) fn append_compute_prefix( + &self, + owner: u64, + exclude_qid: Option, + packet: &Arc, + recovery_state: u32, + require_visible: bool, + frontier: &mut super::dependency::Frontier, + ) -> Result { + let through = packet.order.wait_through[1]; + if through.is_none() { + return Ok(()); + } + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner) && Some(queue.qid()) != exclude_qid) + { + if let Some(dep) = queue.dependency_checked( + owner, + packet.completion.status(), + through, + recovery_state, + require_visible, + )? { + frontier.insert(0, dep).map_err(|_| EAGAIN)?; + } + } + Ok(()) + } + + /// The cells of `owner`'s bound compute channels, indexed by `channel_index`, which its + /// publisher may lock one at a time without the device mutex. + pub(super) fn compute_cells( + &self, + owner: u64, + ) -> [Option>; super::pairs::COMPUTE_CHANNELS_MAX] { + let mut cells = [const { None }; super::pairs::COMPUTE_CHANNELS_MAX]; + for entry in self.compute.iter().flatten() { + let Some(queue) = entry.queue.as_deref() else { + continue; + }; + if queue.owner() == Some(owner) { + let index = usize::from(queue.channel_index()); + if index < cells.len() { + cells[index] = Some(entry.queue.0.clone()); + } + } + } + cells } /// An installed idle queue keeps its original QID and backing. Mapping a @@ -290,8 +691,19 @@ impl Registry { pub(super) fn rebind_compute(&mut self, owner: u64, context: &Arc, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; if let Some(queue) = self.compute(owner) { - return Ok(if queue.matches(owner, queue.qid(), context)? { - if queue.pool_fits(required) { Rebind::Done } else { Rebind::Grow } + let matches = queue.matches(owner, queue.qid(), context)?; + let fits = queue.pool_fits(required); + drop(queue); + let all_fit = fits + && self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + .all(|queue| queue.pool_fits(required)); + return Ok(if matches { + if all_fit { Rebind::Done } else { Rebind::Grow } } else { Rebind::Fresh }); @@ -325,13 +737,7 @@ impl Registry { .min_by_key(|(key, _)| *key) .map(|(_, qid)| qid); if let Some(qid) = foreign { - self.compute - .iter_mut() - .flatten() - .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.qid() == qid) - .ok_or(EIO)? - .require_fresh_backing(); + self.give_back_foreign(qid)?; return Err(ENOSPC); } let idle = self @@ -370,6 +776,16 @@ impl Registry { /// Whether `owner` can bind a channel now, without changing any binding. Owner 0 asks /// only whether some channel is free for a new owner. fn compute_readiness(&self, owner: u64, query: Option<(&Arc, super::freelist::ComputeCapacity)>) -> Readiness { + if owner != 0 + && self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .any(|queue| queue.owner() == Some(owner) && queue.spared_pending()) + { + return Readiness::Progress; + } if let (Some((context, required)), Some(queue)) = (query, self.compute(owner).filter(|_| owner != 0)) { return if queue.spared_pending() { Readiness::Progress @@ -446,7 +862,7 @@ impl Registry { qid: u8, pages: crate::g17::freelist::Pages, ring: compute::DescriptorRing, - ) -> Result { + ) -> Result<(super::freelist::PoolDescriptor, Option)> { let mut queue = self .compute .iter_mut() @@ -457,6 +873,13 @@ impl Registry { queue.rearm(pages, ring) } + /// Reserves the vacant queue `qid` for `owner`'s re-arm, as [`Self::bind_reusable`] does for a + /// primary binding. + fn reserve_rearm(&mut self, qid: u8, owner: u64) -> Result { + self.compute_queue_mut(qid).ok_or(EIO)?.reserve_rearm(owner); + Ok(()) + } + /// Ends `owner`'s re-arm reservation of `qid` when it did not bind the queue. pub(super) fn release_rearm(&mut self, qid: u8, owner: u64) { if let Some(mut queue) = self.compute.iter_mut().flatten() @@ -467,7 +890,15 @@ impl Registry { } } - pub(super) fn bind_rearmed(&mut self, qid: u8, owner: u64, context: &Arc) -> Result { + /// Binds the re-armed queue `qid` as `owner`'s compute channel `channel_index`: its primary + /// (0) or a sibling. + pub(super) fn bind_rearmed( + &mut self, + qid: u8, + owner: u64, + context: &Arc, + channel_index: u8, + ) -> Result { let teardown = &self.teardown; let mut queue = self .compute @@ -480,7 +911,11 @@ impl Registry { if queue.context().is_some_and(|bound| teardown.releasing(bound)) { return Err(EAGAIN); } - queue.bind_owner(owner, context.clone()) + if channel_index == 0 { + queue.bind_owner(owner, context.clone()) + } else { + queue.bind_sibling(owner, context.clone(), channel_index) + } } /// Delay before retrying pools a turn could not release. @@ -595,16 +1030,26 @@ impl Registry { } pub(super) fn reserve_compute(&mut self, owner: u64) -> Result { - if owner == 0 - || self.compute.iter().flatten().any(|entry| { - entry - .queue - .as_deref() - .map_or(entry.reservation.owner == owner, |queue| { - queue.owner() == Some(owner) - }) - }) - { + self.reserve_compute_channel(owner, 1) + } + + pub(super) fn reserve_compute_channel( + &mut self, + owner: u64, + limit: u8, + ) -> Result { + if owner == 0 || limit == 0 { + return Err(EINVAL); + } + let mut owned = 0usize; + for entry in self.compute.iter().flatten() { + match entry.queue.as_deref() { + None if entry.reservation.owner == owner => return Err(EINVAL), + Some(queue) if queue.owner() == Some(owner) => owned += 1, + _ => {} + } + } + if owned >= usize::from(limit) { return Err(EINVAL); } let slot = self @@ -667,21 +1112,63 @@ impl Registry { Ok(()) } - pub(super) fn release_compute(&mut self, owner: u64) -> Result { - let Some(slot) = self.compute.iter().position(|entry| { - entry + /// Releases idle sibling channels of `owner` before primary pool growth. Returns `Err(EAGAIN)` + /// while any sibling still has active, replaying or configuring work, and returns any + /// unpublished sibling queues for off-lock alias drop and QID cancellation. + fn drain_compute_siblings( + &mut self, + owner: u64, + ) -> Result)>> { + let mut retired = KVec::new(); + for slot in 0..self.compute.len() { + let is_sibling = self.compute[slot] .as_ref() .and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| queue.owner() == Some(owner)) - }) else { - return Ok(()); - }; - let entry = self.compute[slot].as_mut().ok_or(EIO)?; - let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; - if unpublished { - self.qids.cancel_unpublished(entry.reservation.id)?; - self.compute[slot] = None; - self.note_build_room(); + .is_some_and(|queue| queue.owner() == Some(owner) && !queue.is_primary()); + if !is_sibling { + continue; + } + let busy = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.active_len() != 0 || queue.has_replays() || queue.configuring() + }); + if busy { + return Err(EAGAIN); + } + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; + if unpublished { + if let Some(queue) = entry.queue.take() { + retired.push((entry.reservation, queue), GFP_KERNEL)?; + } + } + } + Ok(retired) + } + + pub(super) fn release_compute(&mut self, owner: u64) -> Result { + // Release sibling channels before the primary channel for deterministic teardown order. + for primary_pass in [false, true] { + for slot in 0..self.compute.len() { + let matches = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; + if unpublished { + self.qids.cancel_unpublished(entry.reservation.id)?; + self.compute[slot] = None; + self.note_build_room(); + } + } } Ok(()) } @@ -711,6 +1198,20 @@ pub(super) enum Rebind { Fresh, } +/// Where an owner's next sibling compute channel comes from ([`Registry::sibling_source`]). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(super) enum SiblingSource { + /// An idle reusable queue whose populated pool serves the owner's VM and fits: bind it. + Warm(u8), + /// A vacant reusable queue no other owner is re-arming: re-arm it with fresh backing. + Vacant(u8), + /// No reusable queue to bind or re-arm, but a fresh QID fits. + Fresh, + /// An idle reusable queue whose pool still serves another VM: give it back, so it is vacated + /// and can be re-armed. + Foreign(u8), +} + #[kunit_tests(asahi_g17_uninstalled_cleanup)] mod uninstalled_cleanup_tests { @@ -747,11 +1248,15 @@ pub(super) struct Backend { backlog: core::sync::atomic::AtomicU32, compute_backlog: core::sync::atomic::AtomicU32, closed: core::sync::atomic::AtomicBool, - /// The cell of the compute queue this owner last published to under the device mutex, - /// with the shared compute objects mapped into its VM. Direct publication revalidates the - /// binding under the cell lock; a stale cell only sends the packet back to that path. + /// The cells of the compute channels this owner last published to under the device mutex, + /// indexed by `channel_index`, with the shared compute objects mapped into its VM. Direct + /// publication revalidates each binding under its own cell lock; a stale cache only sends + /// the packet back to the device-mutex path. #[pin] - direct: kernel::sync::Mutex>>, + direct: kernel::sync::Mutex<[Option>; super::pairs::COMPUTE_CHANNELS_MAX]>, + /// Earliest monotonic timestamp (ns) at which `compute_direct()` may yield again to try + /// adding another sibling channel after a headroom miss. + sibling_backoff_until: core::sync::atomic::AtomicU64, /// The channel a prepared packet is about to publish into. Its claim keeps the idle /// channel from being shared away between prepare_job and run_job. #[pin] @@ -771,6 +1276,8 @@ pub(super) struct Backend { /// Render pairs this owner may hold, fixed at creation with its scheduler's /// credits and its render pool's sizing. pairs: u8, + /// Physical compute channels this owner may hold (up to three on M5 Pro, one elsewhere). + compute_channels: u8, } impl Backend { @@ -908,13 +1415,18 @@ impl Backend { backlog: core::sync::atomic::AtomicU32::new(0), compute_backlog: core::sync::atomic::AtomicU32::new(0), closed: core::sync::atomic::AtomicBool::new(false), - direct <- kernel::new_mutex!(None, "g17::Backend::direct"), + direct <- kernel::new_mutex!( + [const { None }; super::pairs::COMPUTE_CHANNELS_MAX], + "g17::Backend::direct" + ), + sibling_backoff_until: core::sync::atomic::AtomicU64::new(0), claimed <- kernel::new_mutex!(None, "g17::Backend::claimed"), outer_compute <- kernel::new_mutex!(None, "g17::Backend::outer_compute"), outer_render <- kernel::new_mutex!(None, "g17::Backend::outer_render"), admission, direct_slot: core::sync::atomic::AtomicU32::new(0), pairs: super::pairs::per_owner(), + compute_channels: super::pairs::compute_channels_per_owner(), }), GFP_KERNEL, )?, @@ -1077,7 +1589,16 @@ impl Backend { { let state = self.shared.state.lock(); let firmware = state.as_ref().ok_or(ENODEV)?; - if firmware.queues.compute(self.owner).is_some_and(|queue| queue.pool_fits(required)) { + if firmware.queues.compute(self.owner).is_some() + && firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(self.owner)) + .all(|queue| queue.pool_fits(required)) + { return Ok(()); } } @@ -1094,6 +1615,7 @@ impl Backend { // Growth waits for this queue's retirement and for firmware to consume the pool // release; both are progress the event worker reports. let observed = self.shared.progress.observe(); + let mut retired_siblings = KVec::new(); let result = (|| { let mut state = self.shared.state.lock(); admission.check()?; @@ -1101,7 +1623,10 @@ impl Backend { if !lease.is_current() { return Err(EAGAIN); } if self.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } firmware.scan_compute(None, &mut deferred)?; - let mut queue = firmware.queues.compute_mut(self.owner).ok_or(EAGAIN)?; + // Release sibling channels before growing the primary channel so undersized + // sibling pools are detached and later re-acquired at the grown capacity. + retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?; + let mut queue = firmware.queues.compute_primary(self.owner).ok_or(EAGAIN)?; if queue.pool_fits(required) { return Ok(None); } if growth.is_none() { let notify = queue.begin_growth(&firmware.init, required)?; @@ -1115,6 +1640,9 @@ impl Backend { } queue.finish_growth(&firmware.init, &mut pages, &mut alias).map(Some) })(); + for item in retired_siblings { + self.finish_uninstalled_compute(Some(item))?; + } deferred.finish(); match result { Ok(old) => { drop(old); return Ok(()); } @@ -1155,12 +1683,14 @@ impl Backend { } /// Re-arms the vacant queue `qid` reserved for this owner with fresh zeroed backing, built - /// without the device mutex, and binds it. Some(true): bound; Some(false): retry (the - /// preparation epoch changed or the queue is no longer re-armable); None: no memory for - /// the backing now. + /// without the device mutex, and binds it as compute channel `channel_index` (0: the primary; + /// a sibling only while that index is still the owner's next free one). Some(true): bound; + /// Some(false): retry (the preparation epoch changed, the queue is no longer re-armable or + /// the sibling index was taken); None: no memory for the backing now. fn rearm_vacant( &self, qid: u8, + channel_index: u8, required: super::freelist::ComputeCapacity, alloc: &super::object::Allocator<'_>, objects: &Arc, @@ -1187,16 +1717,21 @@ impl Backend { // rearm(). let ready = firmware.queues.compute.iter().flatten() .filter_map(|entry| entry.queue.as_deref()) - .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)); + .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)) + && (channel_index == 0 + || firmware.queues.next_sibling_index(self.owner, self.compute_channels) + == Some(channel_index)); if !ready { drop(state); return Ok(Some(false)); } - let descriptor = match firmware.queues.rearm_compute(qid, pages, ring) { + let (descriptor, vacated) = match firmware.queues.rearm_compute(qid, pages, ring) { Err(error) if error == EAGAIN => return Ok(Some(false)), result => result?, }; // The firmware consumed this slot's release before the backing // was dropped; the row is rewritten before the queue is kicked. firmware.init.install_compute_pool(descriptor)?; - firmware.queues.bind_rearmed(qid, self.owner, &self.context)?; + firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?; + drop(state); + drop(vacated); Ok(Some(true)) } @@ -1279,7 +1814,8 @@ impl Backend { Err(qid) => { // bind_reusable reserved `qid` for this owner: any outcome but binding it // ends the reservation, so another owner may re-arm it. - let result = self.rearm_vacant(qid, required, &alloc, &objects, &lease, admission); + let result = + self.rearm_vacant(qid, 0, required, &alloc, &objects, &lease, admission); if !matches!(result, Ok(Some(true))) { if let Some(firmware) = self.shared.state.lock().as_deref_mut() { firmware.queues.release_rearm(qid, self.owner); @@ -1369,6 +1905,176 @@ impl Backend { if result != Err(EAGAIN) { return result; } } } + + /// Best-effort acquisition of an additional compute channel with its own dedicated compute + /// pool for a multi-channel M5 owner, from the source [`Registry::sibling_source`] names: a + /// warm reusable queue is bound at once, a vacant one is re-armed with fresh backing and + /// bound as [`Self::rearm_vacant`] re-arms a primary's, a fresh QID gets a new queue, and an + /// idle queue still holding another VM's pool is given back for the next attempt. An owner + /// waiting for its first channel goes first. Never blocks or fails the submission if no + /// sibling is available. + fn try_add_compute_sibling( + &self, + required: super::freelist::ComputeCapacity, + admission: &Admission<'_>, + ) -> Result { + if self.compute_channels <= 1 || !self.context.is_m5() { + return Ok(false); + } + admission.check()?; + let lease = self.shared.preparations.enter_until(admission)?; + let dev = self.shared.drm()?; + let (uat, objects, source, channel_index) = { + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() || self.shared.crashed.load(Ordering::Acquire) { + return Ok(false); + } + if self.admission_open().is_err() + || self.shared.channels.has_waiters() + || !firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) + { + return Ok(false); + } + let Some(channel_index) = firmware + .queues + .next_sibling_index(self.owner, self.compute_channels) + else { + return Ok(false); + }; + let source = match firmware.queues.sibling_source(self.owner, &self.context, required) { + None => return Ok(false), + Some(SiblingSource::Warm(_)) => { + return Ok(firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? == Some(true)); + } + Some(SiblingSource::Foreign(qid)) => { + firmware.queues.give_back_foreign(qid)?; + drop(state); + // A full event pass releases its pool; a later kick re-arms it. + self.shared.queue_events(); + return Ok(false); + } + Some(SiblingSource::Vacant(qid)) => { + firmware.queues.reserve_rearm(qid, self.owner)?; + Err(qid) + } + Some(SiblingSource::Fresh) => match firmware + .queues + .reserve_compute_channel(self.owner, self.compute_channels) + { + Ok(reservation) => Ok(reservation), + Err(_) => return Ok(false), + }, + }; + ( + firmware.uat.clone(), + firmware.pool.clone(), + source, + channel_index, + ) + }; + let alloc = super::object::Allocator { + dev: &dev, + uat: &uat, + }; + let reservation = match source { + Ok(reservation) => reservation, + Err(qid) => { + // The reservation ends with any outcome but binding the queue. + let result = self.rearm_vacant( + qid, + channel_index, + required, + &alloc, + &objects, + &lease, + admission, + ); + let bound = matches!(result, Ok(Some(true))); + if !bound { + if let Some(firmware) = self.shared.state.lock().as_deref_mut() { + firmware.queues.release_rearm(qid, self.owner); + } + } + drop(lease); + // As for a fresh sibling, a failed re-arm leaves the owner on its bound channels. + admission.check()?; + return Ok(bound); + } + }; + let built = (|| { + let pool = compute::PoolBacking::new( + &alloc, + reservation.id, + required, + self.context.vm().memory_client(), + )?; + { + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { + return Err(EAGAIN); + } + self.admission_open()?; + firmware.queues.reserved(reservation)?; + firmware.init.install_compute_pool(pool.pool_descriptor()?)?; + } + let backing = compute::Backing::new(&alloc, pool)?; + let queue = compute::Queue::new_channel( + &alloc, + &objects, + backing, + self.owner, + self.context.clone(), + self.shared.variant.pointers, + self.shared.operand_state, + self.shared.m5_board, + self.shared.variant.compute, + true, + self.shared.variant.mcache, + channel_index, + )?; + Ok(KBox::new(queue, GFP_KERNEL)?) + })(); + let (mut built, build_error) = match built { + Ok(queue) => (Some(queue), None), + Err(error) => (None, Some(error)), + }; + let result = { + let mut state = self.shared.state.lock(); + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if let Err(error) = admission.check() { + Err(error) + } else if !lease.is_current() || self.admission_open().is_err() { + Err(EAGAIN) + } else if let Some(error) = build_error { + Err(error) + } else { + firmware.queues.install_compute(reservation, &mut built) + } + }; + drop(built); + if result.is_err() { + let mut state = self.shared.state.lock(); + if let Some(firmware) = (*state).as_deref_mut() { + let _ = firmware.queues.cancel_compute(reservation); + } + } + drop(lease); + Ok(result.is_ok()) + } } /// One device transaction can fail each retained kick once and then retire it. @@ -1718,15 +2424,51 @@ impl super::Firmware { fn publish_compute(&mut self, owner: u64, packet: Arc, dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result { + self.publish_compute_on(owner, None, packet, dependencies, deferred) + } + + pub(super) fn publish_compute_on( + &mut self, + owner: u64, + target_qid: Option, + packet: Arc, + dependencies: &[super::fw::kick::KickDependency], + deferred: &mut DeferredBatch, + ) -> Result { + let qid = match target_qid { + Some(qid) => qid, + None => self.queues.select_compute_channel(owner, &packet).ok_or(EIO)?, + }; + let mut combined = super::dependency::Frontier::new(); + for dependency in dependencies { + combined.insert(0, *dependency)?; + } + if target_qid.is_none() && packet.order.wait_through[1].is_some() { + let recovery_state = super::recovery::Memory::recovery_state(&self.init)?; + let require_visible = self + .primary + .state + .shared + .m5_board + .is_some_and(|board| board.completion_inputs()); + self.queues.append_compute_prefix( + owner, + Some(qid), + &packet, + recovery_state, + require_visible, + &mut combined, + )?; + } if packet.completion.sources().is_some() { - self.publish_compute_inputs(owner, packet, dependencies, deferred) + self.publish_compute_inputs(owner, qid, packet, combined.as_slice(), deferred) } else { - self.publish_compute_raw(owner, packet, dependencies, &[], deferred) + self.publish_compute_raw(owner, qid, packet, combined.as_slice(), &[], deferred) } } #[inline(never)] - fn publish_compute_inputs(&mut self, owner: u64, packet: Arc, + fn publish_compute_inputs(&mut self, owner: u64, target_qid: u8, packet: Arc, dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result { if self.recovery.pending() || super::recovery::Memory::recovery_state(&self.init)? != 0 { @@ -1743,7 +2485,6 @@ impl super::Firmware { // the source's kick, and the firmware orders it. So is a G17P source of the consumer's // own execution context: one context needs no write-back between the two kicks. let m5 = self.init.is_m5(); - let consumer_qid = self.queues.compute(owner).map(|queue| queue.qid()); let mut waited: u128 = 0; for source in &sources.sources { if source.submission.source_status()? { continue; } @@ -1757,7 +2498,7 @@ impl super::Firmware { let Some((sequence, dependency, stamp_va, event_slot, hold, same_execution)) = found else { return Err(EAGAIN); }; - if m5 && consumer_qid == Some(dependency.qid()) { + if m5 && dependency.qid() == target_qid { // Same physical QID in this epoch: the queue's implicit parent already strictly // orders earlier kicks on this QID; drop the self-reader hold and skip adding a // duplicate explicit barrier. @@ -1782,7 +2523,7 @@ impl super::Firmware { } holds.push(hold, GFP_KERNEL)?; } - let result = self.publish_compute_raw(owner, packet.clone(), merged.as_slice(), + let result = self.publish_compute_raw(owner, target_qid, packet.clone(), merged.as_slice(), native.as_slice(), deferred); if packet.is_published() { for queue in self.queues.compute.iter().flatten() @@ -1801,6 +2542,7 @@ impl super::Firmware { fn publish_compute_raw( &mut self, owner: u64, + target_qid: u8, packet: Arc, dependencies: &[super::fw::kick::KickDependency], native: &[super::sync_input::NativeWait], @@ -1815,7 +2557,7 @@ impl super::Firmware { .iter_mut() .flatten() .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.owner() == Some(owner)) + .find(|queue| queue.qid() == target_qid && queue.owner() == Some(owner)) .ok_or(EIO)?; // The first command after an owner change waits while the scheduler // the queue was bound to is being released: a live previous owner may @@ -1891,12 +2633,31 @@ impl Registry { /// objects mapped into its VM, and its queue bound to `context` with a /// pool that fits and no spared witness to release. fn compute_bound(&self, owner: u64, context: &Arc, required: super::freelist::ComputeCapacity) -> Result { - let Some(queue) = self.compute(owner) else { + let Some(primary) = self.compute_primary(owner) else { return Ok(false); }; - Ok(!queue.spared_pending() - && queue.pool_fits(required) - && queue.matches(owner, queue.qid(), context)?) + if primary.spared_pending() + || !primary.pool_fits(required) + || !primary.matches(owner, primary.qid(), context)? + { + return Ok(false); + } + drop(primary); + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner) && !queue.is_primary()) + { + if queue.spared_pending() + || !queue.pool_fits(required) + || !queue.matches(owner, queue.qid(), context)? + { + return Ok(false); + } + } + Ok(true) } fn release_compute_witness( @@ -1906,24 +2667,26 @@ impl Registry { owner: u64, deferred: &mut DeferredBatch, ) -> Result { - let Some(mut queue) = self + let mut pending = false; + let recovery_state = super::recovery::Memory::recovery_state(init)?; + for mut queue in self .compute .iter_mut() .flatten() .filter_map(|entry| entry.queue.as_deref_mut()) - .find(|queue| queue.owner() == Some(owner)) - else { - return Ok(false); - }; - if !queue.spared_pending() { - return Ok(false); + .filter(|queue| queue.owner() == Some(owner)) + { + if !queue.spared_pending() { + continue; + } + queue.release_witnessed( + recovery_state, + |owner| port.qos_complete(&[owner]), + &mut |event| deferred.push(event), + )?; + pending |= queue.spared_pending(); } - queue.release_witnessed( - super::recovery::Memory::recovery_state(init)?, - |owner| port.qos_complete(&[owner]), - &mut |event| deferred.push(event), - )?; - Ok(queue.spared_pending()) + Ok(pending) } fn fail_compute_vm( @@ -2245,12 +3008,26 @@ impl Backend { Some((frontier, holds, cross_qid_mask)) } - /// Steady-state publication into this owner's bound channel without the device mutex: only - /// the channel's own lock and the port's small locks are taken, and nothing device-wide is - /// scanned. On M5, same-VM cross-QID compute sources whose producers have published their kick - /// metadata also resolve directly without the device mutex. None leaves the packet untouched - /// for the device-mutex path, which owns binding, first installation, non-M5 native-wait - /// sources, render prefixes, replay and recovery. + /// Whether `packet` may run on, or bring up, a sibling compute channel of this owner: only an + /// independent command (no in-queue barrier, no cross-queue input sources) of an owner whose + /// primary channel runs sustained heavy work (`primary_sustained`, asked last, from + /// [`compute::Queue::sustained`]). Every other command streams down the primary ring: short + /// kicks run faster there than spread over several QIDs, and a semaphore hop between queues + /// stays on one ring per queue. + fn fans_out(&self, packet: &super::job::Packet, primary_sustained: impl FnOnce() -> bool) -> bool { + self.compute_channels > 1 + && packet.order.wait_through[1].is_none() + && packet.completion.sources().is_none() + && primary_sustained() + } + + /// Steady-state publication into this owner's bound channel(s) without the device mutex: only + /// one channel's own lock at a time and the port's small locks are taken, and nothing + /// device-wide is scanned. On M5, same-VM cross-QID compute sources whose producers have + /// published their kick metadata also resolve directly, always onto the primary channel. + /// None leaves the packet untouched for the device-mutex path, which owns binding, first + /// installation, cross-channel barriers, non-M5 native-wait sources, render prefixes, replay + /// and recovery. fn compute_direct( &self, packet: &Arc, @@ -2259,16 +3036,24 @@ impl Backend { ) -> Option { let m5 = self.context.is_m5(); let has_sources = packet.completion.sources().is_some(); + let bound_count = self.context.compute_binding_count() as usize; if (has_sources && !m5) || self.context.render_seen() + || bound_count == 0 + || bound_count > super::pairs::COMPUTE_CHANNELS_MAX + || (bound_count > 1 && packet.order.wait_through[1].is_some()) || packet.cancel_requested() || packet.completion.status().get() != 0 || self.admission_open().is_err() { return None; } - let cell = self.direct.lock().clone()?; - let target_qid = cell.qid()?; + let cells = self.direct.lock().clone(); + let cached_count = cells.iter().filter(|cell| cell.is_some()).count(); + if cached_count != bound_count || cells[0].is_none() { + return None; + } + let target_qid = cells[0].as_ref()?.qid()?; let lease = self.shared.preparations.try_enter().ok()?; let port = self.shared.port(&lease)?; if self.shared.crashed.load(Ordering::Acquire) || port.recovery_state().ok()? != 0 { @@ -2281,6 +3066,59 @@ impl Backend { } else { (super::dependency::Frontier::new(), KVec::new(), 0) }; + // Only an independent kick without input sources of an owner whose primary channel runs + // sustained heavy work may leave the primary ring ([`Self::fans_out`]); the primary + // cell's lock-free hint answers that without a lock. + let primary = cells[0].as_ref()?; + let fans_out = self.fans_out(packet, || primary.sustained()); + let can_add_sibling = fans_out + && cached_count < usize::from(self.compute_channels) + && now_ns() >= self.sibling_backoff_until.load(Ordering::Relaxed); + // Lock-free channel selection using each cell's atomic `(configuring, active_len, + // last_published)` mirror: + // - A kick that does not fan out, or finds primary channel 0 idle (`active == 0 && + // !configuring`), routes straight to channel 0 without locking any sibling cell mutexes + // at all, keeping short kicks, input sources and single-in-flight work streaming down + // the primary ring with zero extra mutex overhead. + // - Otherwise, scan bound cells' atomic hints lock-free. While fewer than + // `SIBLING_MIN_IN_FLIGHT` kicks are in flight the kick queues behind them on channel 0 + // ([`super::pairs::overlaps`]); from there it takes the least-loaded channel (oldest + // `last_published` breaks ties), falling back to add a sibling only when every bound + // channel already has >= 1 kick in flight (`all_busy`). + let target_idx = if cached_count == 1 || !fans_out { + 0 + } else { + let (primary_configuring, primary_active, _) = primary.load_hint(); + if primary_active == 0 && !primary_configuring { + 0 + } else { + let mut best: Option<(usize, (bool, u32, u64, usize))> = None; + let mut all_busy = true; + let mut in_flight = 0usize; + for (idx, cell) in cells.iter().enumerate() { + let Some(cell) = cell else { + continue; + }; + let (configuring, active, last_published) = cell.load_hint(); + if active == 0 && !configuring { + all_busy = false; + } + in_flight += active as usize; + let key = (configuring, active, last_published, idx); + if best.is_none_or(|(_, best_key)| key < best_key) { + best = Some((idx, key)); + } + } + if !super::pairs::overlaps(in_flight) { + 0 + } else if can_add_sibling && all_busy { + return None; + } else { + best?.0 + } + } + }; + let target_cell = cells[target_idx].as_ref()?; // Full effort is applied by the device-mutex path when it is not already. if !port.note_submission() { return None; @@ -2315,13 +3153,18 @@ impl Backend { (None, false) }; let result = (|| { - let mut queue = cell.lock()?; + let mut queue = target_cell.lock()?; if !queue.installed() || queue.spared_pending() || !queue.pool_fits(required) || queue.pending_switch_from().is_some() - || queue.qid() != target_qid + || (has_sources && queue.qid() != target_qid) + || (m5 && queue.outer_slots() != 1) + || (cached_count == 1 + && can_add_sibling + && super::pairs::overlaps(queue.active_len())) || !matches!(queue.matches(self.owner, queue.qid(), &self.context), Ok(true)) + || self.context.compute_binding_count() as usize != cached_count || !lease.is_current() { return None; @@ -2465,10 +3308,19 @@ impl Backend { return Ok(true); } let (held, count) = match engine { - crate::g17::job::Engine::Compute => ( - &self.outer_compute, - firmware.queues.compute(self.owner).map_or(2, |queue| queue.outer_slots()), - ), + crate::g17::job::Engine::Compute => { + let slots = firmware + .queues + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(self.owner)) + .map(|queue| queue.outer_slots()) + .max() + .unwrap_or(2); + (&self.outer_compute, slots) + } // Tiling and fragment: one slot each. crate::g17::job::Engine::Render => (&self.outer_render, 2), }; @@ -2531,30 +3383,68 @@ impl Backend { } else { false }; - // The steady state: this owner's channel is bound and installed. - if !sources_checked || self.context.is_m5() { - if let Some(cell) = self.direct.lock().clone() { - 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()) + // The steady state: this owner's bound channel(s) are all cached and installed. + let bound_count = self.context.compute_binding_count() as usize; + if (!sources_checked || self.context.is_m5()) + && bound_count != 0 + && bound_count <= super::pairs::COMPUTE_CHANNELS_MAX + { + let cells = self.direct.lock().clone(); + let cached_count = cells.iter().filter(|cell| cell.is_some()).count(); + if cached_count == bound_count { + if let Some(primary) = cells[0].clone() { + // Validate siblings first so primary is claimed only once every channel passes. + let mut all_ok = true; + let mut outer_slots = 1u32; + for cell in cells[1..].iter().flatten() { + match cell.lock() { + Some(queue) + if queue.installed() + && !queue.spared_pending() + && queue.pool_fits(required) + && matches!( + queue.matches(self.owner, queue.qid(), &self.context), + Ok(true) + ) => + { + outer_slots = outer_slots.max(queue.outer_slots()); + } + _ => { + all_ok = false; + break; + } + } + } + let bound = if all_ok { + primary.lock().and_then(|mut queue| { + let ok = queue.installed() + && !queue.spared_pending() + && queue.pool_fits(required) + && matches!( + queue.matches(self.owner, queue.qid(), &self.context), + Ok(true) + ) + && self.context.compute_binding_count() as usize == cached_count; + if ok { + queue.claim(); + Some(outer_slots.max(queue.outer_slots())) + } else { + None + } + }) } else { None - } - }); - if let Some(outer_slots) = bound { - self.hold_claim(Some(cell)); - if !self.context.is_m5() { - return Readiness::Ready; - } - return match self.claim_compute_outer_direct(outer_slots) { - Ok(false) => Readiness::Outer, - _ => Readiness::Ready, }; + if let Some(outer_slots) = bound { + self.hold_claim(Some(primary)); + if !self.context.is_m5() { + return Readiness::Ready; + } + return match self.claim_compute_outer_direct(outer_slots) { + Ok(false) => Readiness::Outer, + _ => Readiness::Ready, + }; + } } } } @@ -2602,18 +3492,18 @@ impl Backend { } } - /// Called with the device mutex held after a successful publication: remembers the bound - /// channel for direct publication. + /// Called with the device mutex held after a successful publication: remembers all bound + /// channels for direct publication. fn remember_direct(&self, registry: &Registry) { - let cell = registry.compute_cell(self.owner); + let cells = registry.compute_cells(self.owner); let mut direct = self.direct.lock(); - let current = match (&*direct, &cell) { + let current = direct.iter().zip(cells.iter()).all(|pair| match pair { (Some(old), Some(new)) => Arc::ptr_eq(old, new), (None, None) => true, _ => false, - }; + }); if !current { - let old = core::mem::replace(&mut *direct, cell); + let old = core::mem::replace(&mut *direct, cells); drop(direct); drop(old); } @@ -2714,6 +3604,37 @@ impl Backend { { return Err(render::FALLBACK); } + if self.fans_out(packet, || { + firmware.queues.compute_primary(self.owner).is_some_and(|queue| queue.sustained()) + }) { + if firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) { + // Bind a warm reusable sibling inline if one is ready; otherwise fall back once + // so `compute_packet` can build a fresh surplus sibling off-lock. + match firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? { + Some(true) => self.sibling_backoff_until.store(0, Ordering::Relaxed), + Some(false) => return Err(render::FALLBACK), + None => {} + } + } else if !firmware + .queues + .has_compute_sibling_headroom(self.owner, &self.context, required) + { + self.sibling_backoff_until.store( + now_ns().saturating_add(super::pairs::SIBLING_HEADROOM_BACKOFF_NS), + Ordering::Relaxed, + ); + } + } if !self.claim_outer(firmware, crate::g17::job::Engine::Compute)? { return Err(render::FALLBACK); } @@ -2792,6 +3713,7 @@ impl Backend { // progress (work states, ring room, replays) and the reopening of // publication after recovery both signal `progress`. let mut bound = true; + let mut sibling_tried = false; let mut demand = None; let deadline = now_ns().saturating_add(super::preparation::QUEUE_WAIT_NS); let check = || { @@ -2883,6 +3805,58 @@ impl Backend { drop(lease); continue; } + if !sibling_tried + && self.fans_out(packet, || { + firmware + .queues + .compute_primary(self.owner) + .is_some_and(|queue| queue.sustained()) + }) + { + if firmware.queues.wants_compute_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + ) { + sibling_tried = true; + match firmware.queues.bind_reusable_sibling( + self.owner, + &self.context, + self.compute_channels, + required, + )? { + Some(true) => { + self.sibling_backoff_until.store(0, Ordering::Relaxed); + } + Some(false) => { + drop(state); + drop(lease); + if self.try_add_compute_sibling(required, &admission)? { + self.sibling_backoff_until.store(0, Ordering::Relaxed); + } else { + self.sibling_backoff_until.store( + now_ns().saturating_add( + super::pairs::SIBLING_HEADROOM_BACKOFF_NS, + ), + Ordering::Relaxed, + ); + } + continue; + } + None => {} + } + } else if !firmware + .queues + .has_compute_sibling_headroom(self.owner, &self.context, required) + { + sibling_tried = true; + self.sibling_backoff_until.store( + now_ns().saturating_add(super::pairs::SIBLING_HEADROOM_BACKOFF_NS), + Ordering::Relaxed, + ); + } + } let held = self.claim_outer(firmware, crate::g17::job::Engine::Compute)?; if let (false, Some(domain), Some(claimed)) = (held, &outer, claimed) { // The shared work ring has no unclaimed room: consumption or returned claims @@ -3112,6 +4086,12 @@ impl super::Firmware { let busy = !queue.channel_free(); queue.recycle_killed()?; queue.recycle_quarantined_idle()?; + if deferred.vacated_room() { + if let Some(vacated) = queue.take_recycled_ring() { + deferred.defer_vacated(vacated); + freed = true; + } + } if let Some(binding) = queue.detach_exited_owner() { deferred.defer_binding(binding); } diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 7cf47757a9550..13479fd13c773 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -34,30 +34,48 @@ impl Backend { // No outer preparation lease survives compute_packet's return. Hold a // fresh epoch through alias destruction so recovery can join this work. loop { - let lease = self.shared.preparations.enter(false)?; - let mut retired = None; - let mut state = self.shared.state.lock(); - let firmware = state.as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { drop(state); drop(lease); continue; } - let mut binding = None; - if let Some(index) = firmware.queues.compute.iter().position(|entry| { - entry.as_ref().and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| queue.owner() == Some(self.owner)) - }) { - let entry = firmware.queues.compute[index].as_mut().ok_or(EIO)?; - let (cancel, replaced) = entry.queue.as_deref_mut().ok_or(EIO)? - .rollback_unpublished(self.owner, &self.context)?; - binding = replaced; - if cancel { - retired = entry.queue.take().map(|queue| (entry.reservation, queue)); + let lease = self.shared.preparations.enter(false)?; + let mut retired = KVec::new(); + let mut bindings = KVec::new(); + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { drop(state); drop(lease); continue; } + // Roll back sibling channels before the primary channel for deterministic teardown. + for primary_pass in [false, true] { + for index in 0..firmware.queues.compute.len() { + let matches = firmware.queues.compute[index] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(self.owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + let entry = firmware.queues.compute[index].as_mut().ok_or(EIO)?; + let (cancel, replaced) = entry + .queue + .as_deref_mut() + .ok_or(EIO)? + .rollback_unpublished(self.owner, &self.context)?; + if let Some(replaced) = replaced { + let _ = bindings.push(replaced, GFP_KERNEL); + } + if cancel { + if let Some(queue) = entry.queue.take() { + let _ = retired.push((entry.reservation, queue), GFP_KERNEL); + } + } + } } - } - drop(state); - drop(binding); - self.finish_uninstalled_compute(retired)?; - self.shared.channels.notify(); - self.shared.queue_events(); - return Ok(()); + drop(state); + drop(bindings); + for item in retired { + self.finish_uninstalled_compute(Some(item))?; + } + self.shared.channels.notify(); + self.shared.queue_events(); + return Ok(()); } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs index 2bad8071087fd..4e0dfece644a6 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs @@ -30,7 +30,7 @@ impl Backend { return Ok(Decision::Defer); } // Each queue is locked on its own: release this one before visiting the others. - let Some(own) = firmware.queues.compute(self.owner) + let Some(own) = firmware.queues.compute_for_packet(self.owner, packet) .filter(|queue| queue.can_classify_timeout(packet)) .and_then(|queue| queue.timeout_head()) else { return Ok(Decision::Own); @@ -48,7 +48,7 @@ impl Backend { } let decision = verdict.decision; if decision == Decision::Spare { - firmware.queues.compute(self.owner).ok_or(EIO)? + firmware.queues.compute_for_packet(self.owner, packet).ok_or(EIO)? .classify(&|_| Class::Spared); } if let Some(blocker) = verdict.reported_blocker(renewals, excuse) { @@ -73,13 +73,13 @@ impl Backend { deferred: &mut DeferredBatch) -> Result { use crate::g17::timeout::Decision; use core::sync::atomic::{AtomicU32, Ordering}; - let expired = firmware.queues.compute_mut(self.owner) + let expired = firmware.queues.compute_for_packet_mut(self.owner, packet) .is_some_and(|mut queue| queue.expire_stamp_wait(packet)); if !expired { return Ok(Decision::Own); } firmware.scan_compute(None, deferred)?; - if !firmware.queues.compute(self.owner).is_some_and(|queue| queue.retired_held(packet)) { + if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) { return Ok(Decision::Own); } static REPORTED: AtomicU32 = AtomicU32::new(0); @@ -122,7 +122,7 @@ impl Backend { return Ok(None); }; firmware.scan_compute(None, &mut deferred)?; - let Some(mut queue) = firmware.queues.compute_mut(self.owner) else { + let Some(mut queue) = firmware.queues.compute_for_packet_mut(self.owner, packet) else { return Ok(None); }; // A command that retired in this pass has its result. @@ -150,7 +150,7 @@ impl Backend { return Ok(()); }; firmware.scan_compute(None, &mut deferred)?; - if let Some(mut queue) = firmware.queues.compute_mut(self.owner) { + if let Some(mut queue) = firmware.queues.compute_for_packet_mut(self.owner, packet) { queue.cancel(packet, &mut |event| deferred.push(event))?; } Ok(()) diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs index d19a52c674632..ee3536a8bbcd0 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs @@ -166,13 +166,15 @@ impl super::Registry { /// ACK storage belongs to the already-retained transaction, so a full event /// batch cannot overflow a separate cache. No allocation or wait is needed. pub(super) fn acknowledge_compute_exit(&mut self, cookie: u64) { + let mut matched = false; for entry in self.compute.iter_mut().flatten() { if let Some(mut queue) = entry.queue.as_deref_mut() { - if queue.acknowledge_exit(cookie) { - return; - } + matched |= queue.acknowledge_exit(cookie); } } + if matched { + return; + } if self.teardown.acknowledge_render_kill(cookie) { RENDER_KILLS[RENDER_KILL_ACKNOWLEDGED].fetch_add(1, Ordering::Relaxed); crate::g17::trace::teardown(4, cookie, 0x100, 0); @@ -269,6 +271,11 @@ impl Firmware { } fn publish_compute_exit(&mut self, context: &Arc, age: u64, now: u64, pressed: &mut bool) -> Result { + // A context is killed at most once: a multi-channel context records the single kill + // cookie across all of its exiting channels below. + if context.kill_published() { + return Ok(()); + } let Some(index) = self.queues.compute.iter().position(|entry| { entry .as_ref() @@ -374,8 +381,25 @@ impl Firmware { PRESSED_KILL_NS.store(now.max(1), Ordering::Relaxed); } queue.record_exit(cookie, now); + drop(queue); + // A single ContextKill tears down every queue of this context: attach the same + // cookie to any other exiting compute channel of `context` so they settle together. + for (other_index, entry) in self.queues.compute.iter_mut().enumerate() { + if other_index == index { + continue; + } + if let Some(mut other) = entry.as_mut().and_then(|entry| entry.queue.as_deref_mut()) { + if other.exit_candidate(context, age) { + other.record_exit(cookie, now); + } + } + } crate::g17::trace::teardown(3, cookie, u64::from(context.id()), hold | u64::from(beside)); fence(Ordering::SeqCst); + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; if let Err(error) = queue.announce_exit(now, || self.primary.notify(MSG_CONTROL_NOTIFY)) { dev_warn!( self.primary.state.shared.dev.as_ref(), diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs index e72fc921834d9..55cd94b8b003f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs @@ -124,15 +124,33 @@ impl Firmware { // backpressure uses the existing failed-replay retirement. Err(EBUSY) } else { (|| { - self.queues.compute[index] - .as_mut() - .and_then(|entry| entry.queue.as_deref_mut()) - .ok_or(EIO)? - .prepare_replay(&packet)?; + let qid = { + let mut queue = self.queues.compute[index] + .as_mut() + .and_then(|entry| entry.queue.as_deref_mut()) + .ok_or(EIO)?; + queue.prepare_replay(&packet)?; + queue.qid() + }; let owner = owner.ok_or(EIO)?; packet.check_replay_dependencies()?; - let dependencies = self.queues.render_prefix(owner, &packet)?; - self.publish_compute(owner, packet.clone(), dependencies.as_slice(), deferred) + let mut dependencies = self.queues.render_prefix(owner, &packet)?; + let recovery_state = recovery::Memory::recovery_state(&self.init)?; + let require_visible = self + .primary + .state + .shared + .m5_board + .is_some_and(|board| board.completion_inputs()); + self.queues.append_compute_prefix( + owner, + Some(qid), + &packet, + recovery_state, + require_visible, + &mut dependencies, + )?; + self.publish_compute_on(owner, Some(qid), packet.clone(), dependencies.as_slice(), deferred) })() }; let recovery_wait = matches!(result, Err(EAGAIN) | Err(EBUSY)) && (self.recovery.pending() diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index ee3b5e518da58..6f1ade9a2b284 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -656,13 +656,26 @@ impl Registry { dependencies.tiling_count += 1; } } - if let Some(queue) = self.compute(owner) { - dependencies.compute = queue.dependency( + for queue in self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| queue.owner() == Some(owner)) + { + let tiling = queue.dependency( owner, packet.completion.status(), packet.order.tiling_wait_through[1], state, )?; + if let Some(dep) = tiling { + *dependencies + .compute + .get_mut(dependencies.compute_count) + .ok_or(EOVERFLOW)? = dep; + dependencies.compute_count += 1; + } if packet.order.tiling_wait_through[1] != packet.order.wait_through[1] { let whole = queue.dependency( owner, @@ -670,8 +683,12 @@ impl Registry { packet.order.wait_through[1], state, )?; - if whole != dependencies.compute { - dependencies.fragment_compute = whole; + if let Some(dep) = whole.filter(|dep| Some(*dep) != tiling) { + *dependencies + .fragment_compute + .get_mut(dependencies.fragment_compute_count) + .ok_or(EOVERFLOW)? = dep; + dependencies.fragment_compute_count += 1; } } } diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 3e1ad1c649aa7..b7ba5152f5051 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -561,6 +561,15 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_COMPUTE_ONLY ((1ULL) << 41) +/* + * DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: the kernel itself runs the + * independent compute commands of one queue on several firmware compute + * queues of its context, so that they overlap. Userspace needs no further + * queues of its own for that. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. + */ +#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 42) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 diff --git a/tools/asahi/g17-capacity-fault-tests.py b/tools/asahi/g17-capacity-fault-tests.py index 72f2552d781a4..46b6ec3c51438 100644 --- a/tools/asahi/g17-capacity-fault-tests.py +++ b/tools/asahi/g17-capacity-fault-tests.py @@ -109,7 +109,8 @@ def fixture(): mod qos { pub type Owner = u64; } enum Deferred { Retired(Arc, Result<[u64; 4]>), Release(Arc) } struct Queue { - owner: Option, installed: bool, active: Fifo, quarantined: bool, + owner: Option, channel_index: u8, binding_noted: bool, + installed: bool, active: Fifo, quarantined: bool, previous: Option, unpublished_binding: bool, released: bool, graph: Graph, binding: Option, retirement_ready: bool, released_at: u64, growing: bool, pool_phase: PoolPhase, needs_fresh_backing: bool, exit: Option, replays: Fifo>, @@ -126,11 +127,24 @@ def fixture(): fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> u64 { 1 } fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) } + fn clear_binding_note(&mut self) { + if self.binding_noted { + if let Some(binding) = &self.binding { binding.context.note_compute_binding(false); } + self.binding_noted = false; + } + } + fn clear_owner(&mut self, stamp_released_at: bool) { + self.clear_binding_note(); + self.owner = None; + self.channel_index = 0; + if stamp_released_at { self.released_at = now_ns(); } + } ''' + methods + r''' } fn idle(live: &Arc) -> Queue { Queue { - owner: Some(2), installed: true, active: Fifo::new(), quarantined: false, + owner: Some(2), channel_index: 0, binding_noted: false, + installed: true, active: Fifo::new(), quarantined: false, previous: None, unpublished_binding: false, released: false, graph: Graph { cursors: Cursors { count: 1280, producer: 4, consumer: 4 }, stamp: 7 << 8, fail: false, resets: 0, owner: 2, m5: false }, binding: Some(Binding { context: Context::new(2, live) }), retirement_ready: false, diff --git a/tools/asahi/g17-compute-deadline-tests.py b/tools/asahi/g17-compute-deadline-tests.py index a97a3b4021e74..fb3585ea7ec90 100644 --- a/tools/asahi/g17-compute-deadline-tests.py +++ b/tools/asahi/g17-compute-deadline-tests.py @@ -35,7 +35,8 @@ def fixture(): ('super::recovery::Memory', 'Memory'), ('super::fw::compute_pool::required_blocks', 'required_blocks'), ('super::freelist::ComputeCapacity', 'ComputeCapacity'), - ('super::preparation::QUEUE_WAIT_NS', 'QUEUE_WAIT_NS')]: + ('super::preparation::QUEUE_WAIT_NS', 'QUEUE_WAIT_NS'), + ('super::pairs::SIBLING_HEADROOM_BACKOFF_NS', 'SIBLING_HEADROOM_BACKOFF_NS')]: packet = packet.replace(old, new) ensure = ensure.replace(old, new) admission = (item(preparation, "pub(super) struct Admission<'a>") + '\n' + @@ -85,7 +86,8 @@ def fixture(): // A work-state node is taken per engine: compute admission must ask for a compute one. struct Work;impl Work{fn acquire(&self,engine:g17::job::Engine)->Result{assert_eq!(engine,g17::job::Engine::Compute,"compute admission takes a compute work state");if MODE.load(Ordering::SeqCst)==4{Err(EBUSY)}else{Ok(1)}}} struct Completion;impl Completion{fn status(&self)->Status{Status}fn work_state(&self)->Result{Ok(Work)}} -struct Packet{command:Validated,completion:Completion} +struct Order{wait_through:[Option;2]} +struct Packet{command:Validated,completion:Completion,order:Order} impl Packet{fn check_dependencies(&self)->Result{Ok(())}fn cancel_requested(&self)->bool{now_ns()>=CANCEL.load(Ordering::SeqCst)}fn is_published(&self)->bool{false}} struct DeferredBatch;impl DeferredBatch{fn publication()->Result{Ok(Self)}fn finish(&mut self){}} struct Recovery;impl Recovery{fn pending(&self)->bool{MODE.load(Ordering::SeqCst)==1}} @@ -98,7 +100,13 @@ def fixture(): fn compute(&self,_:u64)->Option<()>{if MODE.load(Ordering::SeqCst)==0{None}else{Some(())}} fn render_prefix(&self,_:u64,_:&Arc)->Result>{Ok(vec![])} fn release_compute_witness(&self,_:&Init,_:&(),_:u64,_:&mut DeferredBatch)->Result{Ok(MODE.load(Ordering::SeqCst)==2)} + fn wants_compute_sibling(&self,_:u64,_:&Context,_:u8,_:usize)->bool{false} + fn has_compute_sibling_headroom(&self,_:u64,_:&Context,_:usize)->bool{true} + fn bind_reusable_sibling(&mut self,_:u64,_:&Context,_:u8,_:usize)->Result>{Ok(None)} + fn compute_primary(&self,_:u64)->Option{None} } +struct Primary;impl Primary{fn sustained(&self)->bool{false}} +const SIBLING_HEADROOM_BACKOFF_NS:u64=10_000_000; struct Firmware{recovery:Recovery,init:Init,queues:Queues,port:()} // Mode 6: the publication itself refuses with EBUSY (no recovery): an immediate error, not a spent budget. impl Firmware{fn replay_compute(&mut self,_:&mut DeferredBatch)->Result{Ok(())}fn publish_compute(&mut self,_:u64,_:Arc,_:&[()],_:&mut DeferredBatch)->Result{if MODE.load(Ordering::SeqCst)==6{advance(5_000_000);Err(EBUSY)}else{Err(EAGAIN)}}} @@ -106,7 +114,7 @@ def fixture(): struct Available;impl Available{fn observe(&self)->u64{now_ns()}} struct Shared{preparations:Arc,state:State,crashed:AtomicBool,compute_blocks:usize,active_cores:u32,progress:Available}impl Shared{fn queue_events(&self){}} struct ComputeDemand;impl ComputeDemand{fn new(_:&Shared)->Self{Self}} -struct Backend{shared:Shared,owner:u64,context:Context} +struct Backend{shared:Shared,owner:u64,context:Context,compute_channels:u8,sibling_backoff_until:AtomicU64} fn required_blocks(_:usize,_:u32,_:u16)->Result{Ok(1)} type ComputeCapacity=usize; impl Backend{ @@ -118,6 +126,8 @@ def fixture(): fn compute_direct(&self,_:&Arc,_:usize,_:&mut DeferredBatch)->Option{None} fn sources_published(&self,_:&Arc)->Result{Ok(true)} fn remember_direct(&self,_:&Queues){} + fn try_add_compute_sibling(&self,_:usize,_:&Admission<'_>)->Result{Ok(false)} + fn fans_out(&self,_:&Packet,primary_sustained:impl FnOnce()->bool)->bool{self.compute_channels>1&&primary_sustained()} fn wait_release(&self,_:&Available,_:u64,admission:&Admission<'_>)->Result{ let _=admission.slice_ms()?; advance(1_000_000); @@ -140,8 +150,8 @@ def fixture(): ''' + ensure + '\n' + packet + r''' } fn main(){ - let b=Backend{owner:1,context:Context,shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; - let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion}); + let b=Backend{owner:1,context:Context,compute_channels:1,sibling_backoff_until:AtomicU64::new(0),shared:Shared{compute_blocks:21,active_cores:1,progress:Available,preparations:Arc::new(Gate{wait:Wait,changed:Changed}),state:State(Mutex::new(Some(Box::new(Firmware{recovery:Recovery,init:Init,queues:Queues,port:()})))),crashed:AtomicBool::new(false)}}; + let p=Arc::new(Packet{command:Validated::Compute{scratch:Scratch},completion:Completion,order:Order{wait_through:[None,None]}}); for mode in 0..4 { MODE.store(mode,Ordering::SeqCst);NOW.store(0,Ordering::SeqCst);CALLS.store(0,Ordering::SeqCst);REPORTED.store(usize::MAX,Ordering::SeqCst); let r=b.compute_packet(&p,&mut DeferredBatch); diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index 1a29447f2f07e..d79d784b7578f 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -41,6 +41,7 @@ def fixture(): use std::sync::{Mutex,MutexGuard,atomic::{AtomicBool,AtomicU64,Ordering,fence}}; type Result = std::result::Result; type KBox = Box; +type KVec = Vec; const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const EBUSY:i32=-16;const ECANCELED:i32=-125; const RECOVERY_WAIT_MS:u32=26_000; static NOW:AtomicU64=AtomicU64::new(0);static ALIAS:AtomicBool=AtomicBool::new(false);static PAGES:AtomicBool=AtomicBool::new(false); @@ -76,6 +77,7 @@ def fixture(): mod compute{pub(crate) use crate::Queue;} struct Queue{fresh:bool} impl Queue{ + fn owner(&self)->Option{Some(1)} fn pool_fits(&self,_:usize)->bool{false} fn begin_growth(&mut self,_:&(),_:usize)->Result{Ok(false)} fn growth_token(&self)->Option{Some(7)} @@ -89,6 +91,8 @@ def fixture(): impl Registry{ fn compute(&self,_:u64)->Option<&Queue>{self.compute[0].as_ref().unwrap().queue.as_deref()} fn compute_mut(&mut self,_:u64)->Option<&mut Queue>{self.compute[0].as_mut().unwrap().queue.as_deref_mut()} + fn compute_primary(&mut self,owner:u64)->Option<&mut Queue>{self.compute_mut(owner)} + fn drain_compute_siblings(&mut self,_:u64)->Result)>>{Ok(Vec::new())} fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} } struct Primary;impl Primary{fn notify(&self,_:u32)->Result{Ok(())}} diff --git a/tools/asahi/g17-compute-multi-channel-feature-tests.py b/tools/asahi/g17-compute-multi-channel-feature-tests.py new file mode 100755 index 0000000000000..0707c01070c03 --- /dev/null +++ b/tools/asahi/g17-compute-multi-channel-feature-tests.py @@ -0,0 +1,243 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: G17 GET_PARAMS reports DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL exactly where the +kernel fans compute out itself. + +Compiles the production board selection of drivers/gpu/drm/asahi/g17/pairs.rs +(`select_board()`, `compute_channels_per_owner()`), `multi_channel()` of +g17/fw/m5/compute.rs, `Board::compute_channels()` and every board's +`compute_channels` value of g17/fw/m5/initdata.rs, `compute_channel_features()` +of g17/mod.rs and the feature constant of file.rs, the latter against every +DRM_ASAHI_FEATURE_* bit that include/uapi/drm/asahi_drm.h defines. It checks +that the bit is set exactly when a logical compute queue may hold more than one +physical compute channel: on the M5 Pro (J714), and neither on the M5 Max, +the M5 Ultra and the M5 (J716C, J775D, J813), whose boards run one firmware +compute queue per command queue, nor on GPUs that never select an M5 board +(G17P), so userspace keeps its own sibling queues there; that the decision reads +the board's channel count alone, never its encoding forms; that GET_PARAMS +reports it from the probed board's channel count on every G17; and that the bit +is distinct from every other feature bit. + +Each mutation drops one part of the rule and must fail an assertion of the +compiled harness. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASAHI = ROOT / 'drivers/gpu/drm/asahi' +G17 = ASAHI / 'g17' +UAPI = ROOT / 'include/uapi/drm/asahi_drm.h' + + +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: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +REPORTED = ' | compute_channel_features(pairs::compute_channels_per_owner());\n' + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + 'always-multi': [('mod', ' if channels > 1 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL', + ' if channels > 0 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL')], + 'never-multi': [('mod', ' if channels > 1 {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL', + ' if false {\n crate::file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL')], + 'not-reported': [('mod', ' | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT\n' + REPORTED, + ' | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT;\n')], + 'per-board-gate': [('mod', REPORTED, + ' | compute_channel_features(pairs::COMPUTE_CHANNELS_MAX as u8);\n')], + 'forms-gate': [('fw', ' board.compute_channels() > 1\n', + ' board.compute_channels() > 1 || !board.g17d_forms()\n')], + 'max-channels': [('pairs', ' COMPUTE_CHANNELS.store(board.compute_channels(), Relaxed);', + ' COMPUTE_CHANNELS.store(COMPUTE_CHANNELS_MAX as u8, Relaxed);')], + 'multi-channel-max': [('initdata', ' host_only_render_kicks: true,\n compute_channels: 1,\n', + ' host_only_render_kicks: true,\n compute_channels: 3,\n')], + 'colliding-bit': [('uapi', '#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 42)', + '#define DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL ((1ULL) << 39)')], + 'unsynced-binding': [('file', ' uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL as u64;', + ' uapi::DRM_ASAHI_FEATURE_ASYNC_SUBMIT as u64;')], +} + + +def build(mutation=None): + files = { + 'pairs': (G17 / 'pairs.rs').read_text(), + 'mod': (G17 / 'mod.rs').read_text(), + 'fw': (G17 / 'fw/m5/compute.rs').read_text(), + 'file': (ASAHI / 'file.rs').read_text(), + 'uapi': UAPI.read_text(), + 'initdata': (G17 / 'fw/m5/initdata.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + pairs, mod, fw, file, uapi, initdata = (files[k] for k in ('pairs', 'mod', 'fw', 'file', 'uapi', 'initdata')) + + # Every board's own channel count, following `..BASE` for a board that inherits it. + boards = {} + for name, body in re.findall(r'^pub\(crate\) const (\w+): Board = Board \{\n(.*?)^\};', initdata, re.M | re.S): + own = re.search(r'^ compute_channels: (\d+),$', body, re.M) + base = re.search(r'^ \.\.(\w+)$', body, re.M) + assert own or base, name + boards[name] = int(own.group(1)) if own else boards[base.group(1)] + assert set(boards) == {'J714', 'J716C', 'J775D', 'J813', 'J813_26B123'}, boards + board_table = ',\n'.join(f' ("{name}", {n})' for name, n in boards.items()) + channels_fn = item(initdata, 'pub(crate) const fn compute_channels(').replace('pub(crate) ', '') + + bits = re.findall(r'^\s*(DRM_ASAHI_FEATURE_\w+)\s*=\s*\(1U?L{0,2}\)\s*<<\s*(\d+),', uapi, re.M) + bits += re.findall(r'^#define\s+(DRM_ASAHI_FEATURE_\w+)\s+\(\(1ULL\)\s*<<\s*(\d+)\)', uapi, re.M) + names = [name for name, _ in bits] + uapi_mod = '\n'.join(f' pub const {name}: u64 = 1 << {bit};' for name, bit in bits) + table = ',\n'.join(f' ("{name}", 1u64 << {bit})' for name, bit in bits) + + pairs_code = '\n'.join([ + re.search(r'pub\(crate\) const COMPUTE_CHANNELS_MAX: usize = \d+;', pairs).group(0), + re.search(r'const G17D_PAIRS: u8 = [^;]+;', pairs).group(0), + re.search(r'static PAIRS: AtomicU8 = AtomicU8::new\(\d+\);', pairs).group(0), + re.search(r'static COMPUTE_CHANNELS: AtomicU8 = AtomicU8::new\(\d+\);', pairs).group(0), + item(pairs, 'pub(crate) fn select_board('), + item(pairs, 'pub(crate) fn per_owner('), + item(pairs, 'pub(crate) fn compute_channels_per_owner('), + ]).replace('pub(crate) ', 'pub ').replace('crate::g17::fw::m5::initdata::Board', 'crate::Board') \ + .replace('crate::g17::fw::m5::compute::multi_channel', 'crate::multi_channel') \ + .replace('RENDER_PAIRS_MAX as u8', '2u8') + features = item(mod, 'fn compute_channel_features(') + multi = item(fw, 'pub(crate) fn multi_channel(').replace('pub(crate) ', '') + file_const = re.search(r'pub\(crate\) const DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL: u64 =\s*[^;]+;', file).group(0) + params = item(mod, 'fn get_params(&self, params: &mut uapi::drm_asahi_params_global)') + structure = { + 'GET_PARAMS reports the bit from the probed channel count on every G17': ordered_ok( + params, 'params.features |=', '| crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT', REPORTED.strip(), + 'let variant = self.shared.variant;'), + 'the UAPI header defines the bit': 'DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL' in names, + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@UAPI@@', uapi_mod).replace('@@TABLE@@', table).replace('@@PAIRS@@', pairs_code) + .replace('@@FEATURES@@', features).replace('@@MULTI@@', multi).replace('@@FILE@@', file_const) + .replace('@@STRUCTURE@@', checks).replace('@@BOARDS@@', board_table) + .replace('@@CHANNELS@@', channels_fn)) + + +TEMPLATE = r''' +#![allow(dead_code)] +use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + +mod uapi { +@@UAPI@@ +} +const FEATURES: &[(&str, u64)] = &[ +@@TABLE@@ +]; + +mod file { + use crate::uapi; + @@FILE@@ +} + +pub struct Board { g17d: bool, compute_channels: u8 } +impl Board { + fn g17d_forms(&self) -> bool { self.g17d } + @@CHANNELS@@ +} +@@MULTI@@ + +/// The production boards and their `compute_channels`. +const BOARDS: &[(&str, u8)] = &[ +@@BOARDS@@ +]; + +mod pairs { + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + @@PAIRS@@ +} + +@@FEATURES@@ + +/// What GET_PARAMS reports, as get_params() computes it. +fn reported() -> u64 { compute_channel_features(pairs::compute_channels_per_owner()) } + +fn main() { +@@STRUCTURE@@ + + // The bit is the header's and no other feature has it. + let bit = file::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL; + assert_eq!(bit, uapi::DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL, "file.rs reports the header's bit"); + assert_eq!(bit.count_ones(), 1); + for (name, value) in FEATURES { + if *name != "DRM_ASAHI_FEATURE_COMPUTE_MULTI_CHANNEL" { + assert_ne!(*value, bit, "{} shares the multi-channel bit", name); + } + } + + // A GPU that never selects an M5 board (G17P) has one channel per owner: no bit. + assert_eq!(pairs::compute_channels_per_owner(), 1); + assert_eq!(reported() & bit, 0, "single-channel G17P keeps its own sibling queues"); + // The production boards: only the M5 Pro holds several channels per owner, so only it + // reports the bit; the M5 Max, M5 Ultra and M5 run one firmware compute queue per queue. + for &(name, channels) in BOARDS { + let multi = name == "J714"; + assert!(channels >= 1 && usize::from(channels) <= pairs::COMPUTE_CHANNELS_MAX, "{}", name); + for g17d in [false, true] { + let board = Board { g17d, compute_channels: channels }; + assert_eq!(multi_channel(&board), multi, "{}: multi_channel()", name); + pairs::select_board(&board); + assert_eq!(pairs::compute_channels_per_owner(), channels, "{}: channels per owner", name); + assert_eq!(reported() & bit, if multi { bit } else { 0 }, "{}: reported", name); + } + } + assert_eq!(BOARDS.iter().find(|b| b.0 == "J714").unwrap().1 as usize, pairs::COMPUTE_CHANNELS_MAX, + "the M5 Pro holds the most channels"); + // Set exactly when an owner may hold more than one channel, and nothing else. + for channels in 0..=u8::MAX { + assert_eq!(compute_channel_features(channels), if channels > 1 { bit } else { 0 }); + } + + println!("PASS g17-compute-multi-channel-feature: reported exactly where a queue holds several compute channels"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-multi-channel-') as tmp: + path = Path(tmp) / 'feature.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-compute-owed-stamp-tests.py b/tools/asahi/g17-compute-owed-stamp-tests.py index c857199abad99..edca687c3989b 100644 --- a/tools/asahi/g17-compute-owed-stamp-tests.py +++ b/tools/asahi/g17-compute-owed-stamp-tests.py @@ -10,7 +10,9 @@ finished retires it on its record instead of failing its client; the commands behind it then retire past it; every retired command keeps its place and its descriptor until a stamp covers it; work that cannot retire that way is failed -as before. --mutation removes one part of that and must fail. +as before. Every retired kick with an exact execution record, and only those, +feeds its channel's run of heavy kicks once (g17/pairs.rs), which gates sibling +compute fan-out on M5 Pro. --mutation removes one part of that and must fail. """ from pathlib import Path import argparse @@ -79,6 +81,14 @@ def fixture(): 'pub(crate) fn owns_packet(', 'pub(crate) fn retired_held(', 'pub(crate) fn expire_stamp_wait(', 'pub(crate) fn timeout(', 'pub(crate) fn can_classify_timeout(']) + pairs = (G17 / 'pairs.rs').read_text() + hz = re.search(r'pub\(crate\) const COMMAND_TIMESTAMP_HZ: u64 = ([0-9_]+);', + (ROOT / 'hw/t8140.rs').read_text()).group(1) + gate = '\n'.join([f'pub(crate) const COMMAND_TIMESTAMP_HZ: u64 = {hz};'] + [ + re.search(r'(?:pub\(crate\) )?const ' + name + r': [^=]+= [^;]+;', pairs).group(0) + for name in ['SIBLING_EXECUTION_NS', 'SIBLING_EXECUTION_TICKS', 'SIBLING_SUSTAINED_KICKS']] + [ + item(pairs, 'pub(crate) fn heavy_run('), item(pairs, 'pub(crate) fn sustained(')] + ).replace('crate::hw::t8140::resources::', '') backend = '\n'.join([ item(control, 'pub(super) fn defer_compute_timeout(').replace('pub(super) ', '', 1), item(control, 'fn retire_on_record('), @@ -127,6 +137,9 @@ def fixture(): pub(crate) mod job { pub(crate) trait Backend { fn fail_vm(&self, error: crate::Error); } } + pub(crate) mod pairs { +''' + gate + r''' + } } mod module_parameters { pub(crate) struct Parameter(pub(crate) u32); @@ -235,6 +248,7 @@ def fixture(): released: bool, owner: Option, released_at: u64, + heavy_run: u8, terminal: Option<(Arc, Error)>, fault_stamp: Option, timed_out_at: u64, @@ -246,6 +260,10 @@ def fixture(): fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> qos::Owner { qos::Owner } fn classify(&self, _: &dyn Fn(&Arc) -> recovery::Class) {} + fn clear_owner(&mut self, stamp_released_at: bool) { + self.owner = None; + if stamp_released_at { self.released_at = now_ns(); } + } ''' + queue + r''' } @@ -259,6 +277,13 @@ def fixture(): .find(|queue| queue.owner() == Some(owner)) } fn compute_mut(&mut self, owner: u64) -> Option> { self.compute(owner) } + fn compute_for_packet(&self, owner: u64, packet: &Arc) -> Option> { + self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) + .find(|queue| queue.owner() == Some(owner) && queue.owns_packet(packet)) + } + fn compute_for_packet_mut(&mut self, owner: u64, packet: &Arc) -> Option> { + self.compute_for_packet(owner, packet) + } /// Other VMs' heads, as render pairs and other queues give them. fn render_timeout_heads(&self) -> impl Iterator + '_ { self.render.iter().copied() @@ -308,7 +333,7 @@ def fixture(): retirement_proved: false, retired_by_teardown: false, spared_quarantine: false, spared_deferred: false, awaiting_witness: false, retire_pending: false, last_end: 0, previous: None, submitted: 0, retirement_ready: true, released: false, owner: Some(OWNER), - released_at: 0, terminal: None, fault_stamp: None, timed_out_at: 0, + released_at: 0, heavy_run: 0, terminal: None, fault_stamp: None, timed_out_at: 0, } } @@ -374,6 +399,60 @@ def fixture(): packet.completion.class.get() } + /// Execution record ticks of a kick lasting `us` microseconds. + fn ticks(us: u64) -> u64 { us * g17::pairs::COMMAND_TIMESTAMP_HZ / 1_000_000 } + + #[test] + fn only_exact_execution_records_feed_the_heavy_run() { + let heavy = ticks(g17::pairs::SIBLING_EXECUTION_NS / 1_000); + let mut q = queue(true); + let p1 = publish(&mut q, 0x10, true); + let p2 = publish(&mut q, 0x11, true); + let p3 = publish(&mut q, 0x12, true); + record(&mut q, &p1, [1_000, 1_000 + heavy]); + record(&mut q, &p2, [1_000 + heavy, 1_000 + 3 * heavy]); + // p3 retires without a record: its synthesized envelope measures nothing. + q.graph.stamp.set(stamp_of(0x12)); + let b = backend(q, vec![]); + scan(&b); + assert!(result(&p3).is_some_and(|result| result.is_ok())); + with_queue(&b, |q| { + assert_eq!(q.active.len, 0); + assert_eq!(q.heavy_run, 2, "two exact heavy records, nothing from the recordless kick"); + assert!(g17::pairs::sustained(q.heavy_run)); + }); + // One short record ends the run. + let p4 = with_queue(&b, |q| { + let p4 = publish(q, 0x13, true); + record(q, &p4, [9_000, 9_000 + ticks(3)]); + q.graph.stamp.set(stamp_of(0x13)); + p4 + }); + scan(&b); + assert!(result(&p4).is_some()); + with_queue(&b, |q| assert_eq!(q.heavy_run, 0, "a short kick closes the gate")); + } + + #[test] + fn a_kick_held_for_its_stamp_is_measured_once() { + let heavy = ticks(g17::pairs::SIBLING_EXECUTION_NS / 1_000); + let mut q = queue(false); + let p1 = publish(&mut q, 0x10, true); + let p2 = publish(&mut q, 0x11, true); + record(&mut q, &p1, [100, 100 + heavy]); + record(&mut q, &p2, [100 + heavy, 100 + 2 * heavy]); + let b = backend(q, vec![]); + // Late stamps: both retire on their records and stay held for their stamps. + advance(60 * MS); + scan(&b); + assert!(result(&p1).is_some() && result(&p2).is_some()); + with_queue(&b, |q| assert_eq!((q.active.len, q.heavy_run), (2, 2))); + with_queue(&b, |q| q.graph.stamp.set(stamp_of(0x11))); + scan(&b); + with_queue(&b, |q| assert_eq!((q.active.len, q.heavy_run), (0, 2), + "releasing a held descriptor measures nothing again")); + } + #[test] fn a_finished_head_whose_stamp_never_comes_retires_and_the_queue_moves_on() { let mut q = queue(false); @@ -654,7 +733,7 @@ def fixture(): MUTATIONS = { 'own-finished': [('_ if own.finished => Decision::Retire,', '_ if own.finished => Decision::Own,')], 'no-retire-glue': [('verdict.decision = self.retire_on_record(firmware, packet, &mut deferred)?;', '')], - 'retire-unchecked': [('if !firmware.queues.compute(self.owner).is_some_and(|queue| queue.retired_held(packet)) {', + 'retire-unchecked': [('if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) {', 'if false {')], 'no-expiry': [('if observed_at == Some(STAMP_WAIT_EXPIRED) {', 'if false {')], 'no-step-past': [('Ok(Some(_)) | Err(EAGAIN) if owed => at += 1,', 'Ok(Some(_)) | Err(EAGAIN) if owed => break,'), @@ -673,6 +752,13 @@ def fixture(): 'if !queue.owns_packet(packet) {')], 'no-owed-poll': [(' if at != 0 {\n // Owed stamps come without a completion event', ' if false {\n // Owed stamps come without a completion event')], + # A recordless retirement's synthesized envelope counts as an execution. + 'count-recordless': [('let execution = front.observed.map(|record| record.timestamps);', + 'let execution = Some(timestamps);')], + # Releasing a held descriptor measures the kick again. + 'count-owed-twice': [(' // The stamp now covers the held command: release its descriptor.\n', + ' // The stamp now covers the held command: release its descriptor.\n' + ' self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, 0, u64::MAX);\n')], } diff --git a/tools/asahi/g17-growth-tests.py b/tools/asahi/g17-growth-tests.py index f26db9cfca578..f763fd5b5ff80 100644 --- a/tools/asahi/g17-growth-tests.py +++ b/tools/asahi/g17-growth-tests.py @@ -35,18 +35,20 @@ def fixture(): impl Graph {fn set_owner(&mut self,_:&Context)->Result{Ok(())}} struct ReaderHint; impl ReaderHint {fn has_readers(&self,count:&AtomicU32)->bool{count.load(Ordering::Acquire)!=0}} struct Queue { - owner:Option,installed:bool,growing:bool,channel_error:bool,growth:Option,free_list_generation:u64,configuration:Option<()>,retained_owner:Option<()>, + owner:Option,channel_index:u8,binding_noted:bool,installed:bool,growing:bool,channel_error:bool,growth:Option,free_list_generation:u64,configuration:Option<()>,retained_owner:Option<()>, pool_phase:PoolPhase,release_sent_ns:Option,pool:Pool,binding:Option,previous:Option,graph:Graph, active:Fifo,replays:Fifo,quarantined:bool,released:bool,retirement_ready:bool, retired_by_teardown:bool,released_at:u64,exit:Option<()>,needs_fresh_backing:bool, source_hint:ReaderHint,source_readers:AtomicU32, } -fn idle(live:&Arc)->Queue{Queue{owner:Some(1),installed:true,growing:false,channel_error:false,growth:None, +fn idle(live:&Arc)->Queue{Queue{owner:Some(1),channel_index:0,binding_noted:false,installed:true,growing:false,channel_error:false,growth:None, free_list_generation:0,configuration:None,retained_owner:None,pool_phase:PoolPhase::Populated,release_sent_ns:None,pool:Pool{pages:Some(Pages(10,21)),fail:false}, binding:Some(Binding{context:Context::new(live),pool_alias:Some(1),descriptors:Some(2)}),previous:None,graph:Graph, active:Fifo{len:0},replays:Fifo{len:0},quarantined:false,released:false,retirement_ready:true, retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0)}} impl Queue { + fn clear_binding_note(&mut self){if self.binding_noted{if let Some(binding)=&self.binding{binding.context.note_compute_binding(false);}self.binding_noted=false;}} + fn clear_owner(&mut self,stamp:bool){self.clear_binding_note();self.owner=None;self.channel_index=0;if stamp{self.released_at=now_ns();}} ''' + item(source,'pub(crate) fn release_owner(') + item(source,'pub(crate) fn reusable(') + '\n}\n' methods = '\n'.join(item(source, sig) for sig in ['pub(crate) fn begin_growth(', 'pub(crate) fn finish_growth(', 'pub(crate) fn growth_token(', 'pub(crate) fn abort_growth(', 'pub(crate) fn observe_vacancy(']) replace = item((ROOT / 'freelist.rs').read_text(), 'pub(crate) fn replace_pages(') diff --git a/tools/asahi/g17-m5-cross-qid-direct-tests.py b/tools/asahi/g17-m5-cross-qid-direct-tests.py index e175d8cdfe702..6ea0455c62917 100755 --- a/tools/asahi/g17-m5-cross-qid-direct-tests.py +++ b/tools/asahi/g17-m5-cross-qid-direct-tests.py @@ -290,7 +290,7 @@ def build_rust_harness(mutation=None): '(has_sources && !m5)' in compute_direct_fn and ordered_ok( compute_direct_fn, - 'let target_qid = cell.qid()?;', + 'let target_qid = cells[0].as_ref()?.qid()?;', 'self.resolve_direct_sources(port, generation, target_qid, sources)?', 'queue.qid() != target_qid', 'queue.publish(', diff --git a/tools/asahi/g17-m5-multiqueue-contention-tests.py b/tools/asahi/g17-m5-multiqueue-contention-tests.py index 23bf0512d2c3f..40ff20930b2ed 100755 --- a/tools/asahi/g17-m5-multiqueue-contention-tests.py +++ b/tools/asahi/g17-m5-multiqueue-contention-tests.py @@ -141,7 +141,7 @@ def build_harness(mutation=None): compute_direct, 'held.take()', 'let result = (|| {', - 'let mut queue = cell.lock()?;', + '.lock()?;', '})();', 'if outcome.is_none() && from_held {', '*held = Some(claim);', diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py new file mode 100755 index 0000000000000..5042a66f7e917 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -0,0 +1,660 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for M5 Pro in-context sibling compute channels. + +Compiles production `Context::next_compute_identity()`, `multi_channel()`, +channel selection, sibling admission, release ordering, and multi-channel exit +acknowledgment logic extracted from the G17 driver against host stubs, and +checks structural invariants for dedicated per-sibling ComputePool, lock-free +primary-first `compute_direct()` routing, and recovery/quarantine interaction: +1. Per-context atomic monotonic `(predecessor_id, current_id)` in `object_ids` + and aligned 1-based `submit_sequence == completion_ordinal` (including + multi-threaded concurrency proving zero ID collisions across sibling QIDs). +2. Dedicated per-sibling `ComputePool` (no `PoolBorrow`, no shared `0x7c/0x80` + pool control contention): a warm reusable sibling requires a same-VM + populated fitting pool, a vacant or other-VM idle queue is re-armed with + fresh backing, and a fresh sibling allocates its own `PoolBacking::new` + + pool descriptor (g17-m5-sibling-rearm-tests.py runs the re-arm path). +3. Lock-free `ComputeCell` atomic `(configuring, active_len, last_published)` + mirror updated via `QueueGuard::drop()`, with primary-first routing in + `compute_direct()` so idle channel 0 never locks sibling cell mutexes. +4. `multi_channel()` board selection, lazy sibling acquisition (cap at 3), + `select_compute_channel()` spread & dependent-kick stickiness, + sibling-before-primary release/rollback/growth order, and multi-channel + exit acknowledgment + `compute_bound()` / `release_compute_witness()`. + +The fan-out gate (input sources and short kicks stay on the primary channel) has +its own test, g17-m5-sibling-gate-tests.py; here the primary runs sustained heavy +work so every sibling path is open. +""" +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: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +def build_harness(mutation=None): + freelist_src = (G17 / 'freelist.rs').read_text() + context_src = (G17 / 'context.rs').read_text() + fw_src = (G17 / 'fw/m5/compute.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + backend_src = (G17 / 'runtime/backend.rs').read_text() + exit_src = (G17 / 'runtime/compute_exit.rs').read_text() + queue_src = (G17 / 'queue/compute.rs').read_text() + pairs_src = (G17 / 'pairs.rs').read_text() + min_in_flight = re.search(r'pub\(crate\) const SIBLING_MIN_IN_FLIGHT: usize = [0-9]+;', pairs_src).group(0) + overlaps_fn = (min_in_flight + '\n' + item(pairs_src, 'pub(crate) fn overlaps(')).replace('pub(crate) ', '') + + next_id_fn = item(context_src, 'pub(crate) fn next_compute_identity(').replace('pub(crate) ', 'pub ') + multi_fn = item(fw_src, 'pub(crate) fn multi_channel(').replace('pub(crate) ', '') + initdata_src = (G17 / 'fw/m5/initdata.rs').read_text() + channels_fn = item(initdata_src, 'pub(crate) const fn compute_channels(').replace('pub(crate) ', '') + + cell_struct = item(runtime_src, 'pub(super) struct ComputeCell') + cell_impl = item(runtime_src, 'impl ComputeCell') + guard_drop = item(runtime_src, 'impl Drop for QueueGuard<') + channels_of_fn = item(runtime_src, 'fn compute_channels_of(') + next_sib_fn = item(runtime_src, 'fn next_sibling_index(') + source_fn = item(runtime_src, 'fn sibling_source(') + source_enum = item(runtime_src, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + headroom_fn = item(runtime_src, 'fn has_compute_sibling_headroom(') + wants_sib_fn = item(runtime_src, 'fn wants_compute_sibling(') + bind_sib_fn = item(runtime_src, 'fn bind_reusable_sibling(') + try_add_sib_fn = item(runtime_src, 'fn try_add_compute_sibling(') + select_fn = item(runtime_src, 'fn select_compute_channel(') + release_fn = item(runtime_src, 'pub(super) fn release_compute(') + ack_exit_fn = item(exit_src, 'pub(super) fn acknowledge_compute_exit(') + pub_exit_fn = item(exit_src, 'fn publish_compute_exit(') + rollback_fn = item(backend_src, 'fn rollback_unpublished_compute(') + grow_fn = item(runtime_src, 'fn grow_compute(') + drain_sib_fn = item(runtime_src, 'fn drain_compute_siblings(') + direct_fn = item(runtime_src, 'fn compute_direct(') + readiness_fn = item(runtime_src, 'fn compute_readiness(&self, packet:') + remember_fn = item(runtime_src, 'fn remember_direct(') + claim_outer_fn = item(runtime_src, 'fn claim_outer(') + bound_fn = item(runtime_src, 'fn compute_bound(') + witness_fn = item(runtime_src, 'fn release_compute_witness(') + parent_pred_start = queue_src.index('let parent_retired = self.active.len == 0') + parent_pred_end = queue_src.index('let m5_args =', parent_pred_start) + parent_pred = queue_src[parent_pred_start:parent_pred_end] + m5_args_start = parent_pred_end + m5_args_end = queue_src.index('let mut m5_dependency_types =', m5_args_start) + m5_args_block = queue_src[m5_args_start:m5_args_end] + + if mutation == 'fixed-object-ids': + next_id_fn = ( + 'pub fn next_compute_identity(&self) -> (u32, u64) {\n' + ' let next = self.compute_ordinal.fetch_add(1, Ordering::AcqRel).wrapping_add(1);\n' + ' (next, 0x0000_0001_0000_0001)\n' + '}' + ) + elif mutation == 'primary-before-sibling': + release_fn = release_fn.replace('for primary_pass in [false, true]', + 'for primary_pass in [true, false]', 1) + elif mutation == 'exit-ack-stops-first': + ack_exit_fn = ack_exit_fn.replace( + 'matched |= queue.acknowledge_exit(cookie);', + 'if queue.acknowledge_exit(cookie) { return; }', + 1, + ) + elif mutation == 'direct-allows-multi-barrier': + direct_fn = direct_fn.replace( + ' || (bound_count > 1 && packet.order.wait_through[1].is_some())\n', '', 1) + elif mutation == 'direct-blocks-sibling': + direct_fn = direct_fn.replace( + ' } else if can_add_sibling && all_busy {\n' + ' return None;\n' + ' } else {\n', + ' } else {\n', + 1, + ) + elif mutation == 'direct-locks-sibling-when-idle': + direct_fn = direct_fn.replace( + 'let (configuring, active, last_published) = cell.load_hint();', + 'let queue = cell.lock()?; let (configuring, active, last_published) = (queue.configuring(), queue.active_len() as u32, queue.last_published());', + 1, + ) + elif mutation == 'direct-skips-multi': + direct_fn = direct_fn.replace( + 'bound_count > super::pairs::COMPUTE_CHANNELS_MAX', + 'bound_count > 1', + 1, + ) + elif mutation == 'same-qid-pipelined': + parent_pred = parent_pred.replace( + 'parent_dependency(board, parent_retired)', + 'parent_dependency(board, true)', + 1, + ) + + reg_methods = '\n'.join([ + channels_of_fn, + next_sib_fn, + source_fn, + headroom_fn, + wants_sib_fn, + select_fn, + release_fn, + ]) + reg_methods = reg_methods.replace('pub(super) ', 'pub ') + reg_methods = reg_methods.replace('super::job::Packet', 'Packet') + reg_methods = reg_methods.replace('super::freelist::ComputeCapacity', 'ComputeCapacity') + reg_methods = reg_methods.replace('super::pairs::', '') + + ack_code = ack_exit_fn.replace('pub(super) ', 'pub ') + ack_code = re.sub(r'crate::g17::trace::teardown\([^;]*\);', '', ack_code) + + # Structural invariant booleans compiled into the host binary so every check + # fails with a Rust assertion panic (exit 101) when violated. + dedicated_pool_ok = ( + 'PoolBorrow' not in freelist_src + and 'PoolBorrow' not in queue_src + and 'shared_pool' not in queue_src + and 'PoolBacking::new(' in try_add_sib_fn + and 'install_compute_pool(pool.pool_descriptor()?)' in try_add_sib_fn + and ordered_ok(source_fn, 'if queue.pool_vacant() {', '} else if queue.pool_serves(vm) {', + '!queue.pool_fits(required)', '&mut warm') + and 'let Some(SiblingSource::Warm(qid)) = self.sibling_source(owner, context, required) else' in bind_sib_fn + and 'qid,\n channel_index,\n required,' in try_add_sib_fn + ) + identity_wired_ok = ( + 'packet.context.next_compute_identity()' in parent_pred + and 'object_ids: m5_object_ids,' in m5_args_block + and 'submit_sequence: if board.completion_inputs() { u64::from(m5_ordinal) } else { 0 },' in m5_args_block + and 'completion_ordinal: crate::g17::fw::m5::compute::completion_ordinal(board, m5_ordinal),' in m5_args_block + and 'peek_compute_ordinal' not in queue_src + ) + cell_atomic_ok = ( + 'active_len: core::sync::atomic::AtomicU32' in cell_struct + and 'configuring: core::sync::atomic::AtomicBool' in cell_struct + and 'last_published: core::sync::atomic::AtomicU64' in cell_struct + and 'fn sync_stats(' in cell_impl + and 'fn load_hint(' in cell_impl + and 'self.cell.sync_stats(Some(queue));' in guard_drop + ) + rollback_order_ok = ordered_ok( + rollback_fn, + 'for primary_pass in [false, true]', + 'queue.is_primary() == primary_pass', + '.rollback_unpublished(self.owner, &self.context)?', + ) + grow_releases_siblings_ok = ( + ordered_ok( + drain_sib_fn, + 'queue.owner() == Some(owner) && !queue.is_primary()', + 'if busy {', + 'return Err(EAGAIN);', + '.release_owner()?', + 'entry.queue.take()', + ) + and ordered_ok( + grow_fn, + 'retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?;', + 'firmware.queues.compute_primary(self.owner)', + 'for item in retired_siblings {', + 'self.finish_uninstalled_compute(Some(item))?;', + ) + ) + exit_propagates_ok = ordered_ok( + pub_exit_fn, + 'if context.kill_published()', + 'queue.record_exit(cookie, now);', + 'if other.exit_candidate(context, age)', + 'other.record_exit(cookie, now);', + ) + # Lock-free primary-first selection: compute_direct must NEVER call cell.lock() during + # channel selection, must short-circuit to channel 0 when primary_active == 0 && !primary_configuring, + # and must only lock target_cell once. + select_section = direct_fn[:direct_fn.index('let target_cell =')] + direct_guards_ok = ( + 'cell.lock()' not in select_section + and ordered_ok( + direct_fn, + 'bound_count > super::pairs::COMPUTE_CHANNELS_MAX', + 'bound_count > 1 && packet.order.wait_through[1].is_some()', + 'let (primary_configuring, primary_active, _) = primary.load_hint();', + 'if primary_active == 0 && !primary_configuring', + 'let (configuring, active, last_published) = cell.load_hint();', + 'if can_add_sibling && all_busy', + 'self.outer_compute.lock()', + 'claim.remaining() != 0 && claim.priority() == usize::from(priority)', + 'queue.pool_fits(required)', + 'm5 && queue.outer_slots() != 1', + 'self.context.compute_binding_count() as usize != cached_count', + ) + and 'registry.compute_cells(self.owner)' in remember_fn + ) + readiness_and_outer_ok = ( + ordered_ok( + readiness_fn, + 'bound_count <= super::pairs::COMPUTE_CHANNELS_MAX', + 'cells[1..].iter().flatten()', + 'queue.pool_fits(required)', + 'queue.claim()', + 'self.claim_compute_outer_direct(outer_slots)', + ) + and '.map(|queue| queue.outer_slots())' in claim_outer_fn + and '.max()' in claim_outer_fn + ) + same_qid_serialized_ok = ( + 'parent_dependency(board, parent_retired)' in parent_pred + and 'same_context_independent' not in parent_pred + ) + multi_witness_and_bound_ok = ( + 'self.compute_primary(owner)' in bound_fn + and '!queue.is_primary()' in bound_fn + and 'queue.pool_fits(required)' in bound_fn + and 'pending |= queue.spared_pending();' in witness_fn + ) + + return f''' +#![allow(dead_code, unused_variables, unused_mut)] +use std::cell::RefCell; +use std::collections::HashSet; +use std::sync::{{Arc, atomic::{{AtomicU32, AtomicUsize, Ordering}}}}; + +const EINVAL: i32 = -22; +const EAGAIN: i32 = -11; +const EIO: i32 = -5; +const EOVERFLOW: i32 = -75; +type Result = std::result::Result; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +{source_enum} + +{overlaps_fn} + +struct Board {{ + compute_channels: u8, +}} +impl Board {{ + {channels_fn} +}} + +{multi_fn} + +struct Order {{ + wait_through: [Option; 2], +}} +struct Completion {{ + sources: Option<()>, +}} +impl Completion {{ + fn sources(&self) -> Option<&()> {{ self.sources.as_ref() }} +}} +struct Packet {{ + order: Order, + completion: Completion, +}} + +struct Context {{ + id: u32, + vm_id: u32, + compute_ordinal: AtomicU32, +}} +impl Context {{ + fn new(id: u32, vm_id: u32) -> Arc {{ + Arc::new(Self {{ id, vm_id, compute_ordinal: AtomicU32::new(0) }}) + }} + fn vm(&self) -> u32 {{ self.vm_id }} + {next_id_fn} +}} + +struct Queue {{ + qid: u8, + owner: Option, + channel_index: u8, + active_len: usize, + replays: usize, + configuring: bool, + last_published: u64, + sustained: bool, + reusable: bool, + needs_fresh_backing: bool, + pool_vacant: bool, + pool_vm: u32, + pool_cap: u32, + has_ring: bool, + context: Option>, + exit_cookie: Option, + exit_acked: bool, + unpublished: bool, + released_log: Arc>>, +}} +impl Queue {{ + fn qid(&self) -> u8 {{ self.qid }} + fn owner(&self) -> Option {{ self.owner }} + fn channel_index(&self) -> u8 {{ self.channel_index }} + fn is_primary(&self) -> bool {{ self.channel_index == 0 }} + fn active_len(&self) -> usize {{ self.active_len }} + fn has_replays(&self) -> bool {{ self.replays != 0 }} + fn configuring(&self) -> bool {{ self.configuring }} + fn last_published(&self) -> u64 {{ self.last_published }} + fn sustained(&self) -> bool {{ self.sustained }} + fn reusable(&self) -> bool {{ self.reusable }} + fn needs_fresh_backing(&self) -> bool {{ self.needs_fresh_backing }} + fn pool_vacant(&self) -> bool {{ self.pool_vacant }} + fn pool_serves(&self, vm: u32) -> bool {{ self.pool_vm == vm }} + fn pool_fits(&self, req: ComputeCapacity) -> bool {{ self.pool_cap >= req.0 }} + fn has_ring(&self) -> bool {{ self.has_ring }} + fn context(&self) -> Option<&Arc> {{ self.context.as_ref() }} + fn rearm_open(&self, _owner: u64) -> bool {{ true }} + fn released_at(&self) -> u64 {{ self.last_published }} + fn vacancy_pending(&self) -> bool {{ false }} + fn release_owner(&mut self) -> Result {{ + self.released_log.borrow_mut().push((self.qid, self.channel_index)); + self.owner = None; + self.channel_index = 0; + Ok(self.unpublished) + }} + fn acknowledge_exit(&mut self, cookie: u64) -> bool {{ + if self.exit_cookie == Some(cookie) {{ + self.exit_acked = true; + true + }} else {{ + false + }} + }} +}} + +struct Slot(Option>); +impl Slot {{ + fn as_deref(&self) -> Option> {{ + self.0.as_ref().map(|q| q.borrow()) + }} + fn as_deref_mut(&mut self) -> Option> {{ + self.0.as_ref().map(|q| q.borrow_mut()) + }} +}} + +struct Entry {{ + reservation: Reservation, + queue: Slot, +}} +#[derive(Copy, Clone)] +struct Reservation {{ id: u8 }} + +struct Qids {{ fit: bool, cancelled: Vec }} +impl Qids {{ + fn compute_fits(&self, _queues: usize) -> bool {{ self.fit }} + fn cancel_unpublished(&mut self, id: u8) -> Result {{ + self.cancelled.push(id); + Ok(()) + }} +}} + +struct Admission {{ queues: u32 }} +impl Admission {{ fn queues(&self) -> u32 {{ self.queues }} }} + +struct Teardown {{ releasing_id: Option, render_acked: bool }} +impl Teardown {{ + fn releasing(&self, ctx: &Arc) -> bool {{ self.releasing_id == Some(ctx.id) }} + fn acknowledge_render_kill(&mut self, _cookie: u64) -> bool {{ + self.render_acked = true; + true + }} +}} + +static RENDER_KILLS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)]; +const RENDER_KILL_ACKNOWLEDGED: usize = 0; + +struct Registry {{ + compute: Vec>, + qids: Qids, + admission: Admission, + teardown: Teardown, + build_room_noted: usize, +}} + +impl Registry {{ + fn note_build_room(&mut self) {{ self.build_room_noted += 1; }} + {reg_methods} + {ack_code} +}} + +fn make_entry(q: Queue) -> Option {{ + let qid = q.qid; + Some(Entry {{ + reservation: Reservation {{ id: qid }}, + queue: Slot(Some(RefCell::new(q))), + }}) +}} + +fn test_atomic_compute_identity() {{ + let ctx = Context::new(1, 100); + // Sequential check: 1-based ordinal with monotonic (predecessor_id << 32) | current_id. + assert_eq!(ctx.next_compute_identity(), (1, (1u64 << 32) | 1)); + assert_eq!(ctx.next_compute_identity(), (2, (1u64 << 32) | 2)); + assert_eq!(ctx.next_compute_identity(), (3, (2u64 << 32) | 3)); + assert_eq!(ctx.next_compute_identity(), (4, (3u64 << 32) | 4)); + + // Concurrent check across 4 threads simulating direct sibling compute kicks: + // every kick must receive a unique ordinal and a unique non-zero current_id. + let shared = Context::new(2, 200); + let mut threads = Vec::new(); + for _ in 0..4 {{ + let c = shared.clone(); + threads.push(std::thread::spawn(move || {{ + let mut out = Vec::with_capacity(500); + for _ in 0..500 {{ + out.push(c.next_compute_identity()); + }} + out + }})); + }} + let mut ordinals = HashSet::new(); + let mut current_ids = HashSet::new(); + for t in threads {{ + for (ord, ids) in t.join().unwrap() {{ + let pred = (ids >> 32) as u32; + let cur = ids as u32; + assert_ne!(pred, 0); + assert_ne!(cur, 0); + assert_eq!(cur, ord); + assert!(ordinals.insert(ord), "duplicate shared ordinal {{}}", ord); + assert!(current_ids.insert(cur), "duplicate object_ids current_id {{}}", cur); + }} + }} + assert_eq!(ordinals.len(), 2000); +}} + +fn main() {{ + // 1. Structural guards for dedicated pools, monotonic identities, lock-free ComputeCell hints, + // compute_direct primary-first routing, grow, rollback, and exit propagation. + assert!({str(dedicated_pool_ok).lower()}, "siblings must own dedicated ComputePools with no PoolBorrow"); + assert!({str(identity_wired_ok).lower()}, "multi-channel M5 compute must wire atomic next_compute_identity to object_ids, submit_sequence, and completion_ordinal"); + assert!({str(cell_atomic_ok).lower()}, "ComputeCell must mirror active_len/configuring/last_published atomically via QueueGuard::drop"); + assert!({str(rollback_order_ok).lower()}, "rollback_unpublished_compute must roll back siblings before primary"); + assert!({str(grow_releases_siblings_ok).lower()}, "grow_compute must drain and release siblings before primary growth"); + assert!({str(exit_propagates_ok).lower()}, "publish_compute_exit must propagate kill cookie across all channels of context"); + assert!({str(direct_guards_ok).lower()}, "compute_direct must use lock-free primary-first routing without locking sibling cells, guard barriers, reuse outer_compute, and yield when siblings can be added"); + assert!({str(readiness_and_outer_ok).lower()}, "compute_readiness/claim_outer must validate all bound channels and take max outer_slots"); + assert!({str(same_qid_serialized_ok).lower()}, "multi-channel M5 Pro must keep COMPLETION_DEPENDENCY while a physical QID has an active parent"); + assert!({str(multi_witness_and_bound_ok).lower()}, "compute_bound and release_compute_witness must inspect all channels of owner"); + + // 2. Per-context monotonic object_ids & aligned submit_sequence == completion_ordinal. + test_atomic_compute_identity(); + + // 3. multi_channel() board selection. + assert!(multi_channel(&Board {{ compute_channels: 3 }})); + assert!(multi_channel(&Board {{ compute_channels: 2 }})); + assert!(!multi_channel(&Board {{ compute_channels: 1 }})); + + // 4. Lazy sibling admission + dedicated-pool headroom + round-robin selection + release order. + let ctx = Context::new(1, 77); + let req = ComputeCapacity(16); + let log = Arc::new(RefCell::new(Vec::new())); + let mut reg = Registry {{ + compute: vec![ + make_entry(Queue {{ + qid: 10, owner: Some(1), channel_index: 0, active_len: 1, replays: 0, + configuring: false, last_published: 100, sustained: true, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: false, released_log: log.clone(), + }}), + make_entry(Queue {{ + qid: 11, owner: Some(1), channel_index: 1, active_len: 1, replays: 0, + configuring: false, last_published: 101, sustained: false, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: true, released_log: log.clone(), + }}), + ], + qids: Qids {{ fit: true, cancelled: Vec::new() }}, + admission: Admission {{ queues: 1 }}, + teardown: Teardown {{ releasing_id: None, render_acked: false }}, + build_room_noted: 0, + }}; + assert_eq!(reg.compute_channels_of(1), (2, 0b11)); + assert_eq!(reg.next_sibling_index(1, 3), Some(2)); + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + + // When surplus QIDs are exhausted, a reusable queue must provide the sibling. + reg.qids.fit = false; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + // An idle reusable queue still holding another VM's pool counts: it is given back and + // re-armed for this VM (no lockout once earlier clients took every QID). + reg.compute.push(make_entry(Queue {{ + qid: 13, owner: None, channel_index: 0, active_len: 0, replays: 0, + configuring: false, last_published: 10, sustained: false, reusable: true, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 99, pool_cap: 16, + has_ring: true, context: None, exit_cookie: None, exit_acked: false, + unpublished: false, released_log: log.clone(), + }})); + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Foreign(13))); + // So does a vacant one, before it. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vacant = true; + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Vacant(13))); + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vacant = false; + // A queue with an owner never does. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().reusable = false; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().reusable = true; + // Same-VM fitting populated reusable queue DOES count, first. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_vm = 77; + assert!(reg.wants_compute_sibling(1, &ctx, 3, req)); + assert_eq!(reg.sibling_source(1, &ctx, req), Some(SiblingSource::Warm(13))); + // Undersized same-VM pool does NOT count. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().pool_cap = 8; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute.pop(); + reg.qids.fit = true; + + // If a bound channel has pending replays, refuse new siblings. + reg.compute[1].as_mut().unwrap().queue.as_deref_mut().unwrap().replays = 1; + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + reg.compute[1].as_mut().unwrap().queue.as_deref_mut().unwrap().replays = 0; + + // Add 3rd channel (index 2): cap reached, wants_compute_sibling becomes false. + reg.compute.push(make_entry(Queue {{ + qid: 12, owner: Some(1), channel_index: 2, active_len: 0, replays: 0, + configuring: false, last_published: 50, sustained: false, reusable: false, + needs_fresh_backing: false, pool_vacant: false, pool_vm: 77, pool_cap: 16, + has_ring: true, context: None, exit_cookie: Some(0xabc), exit_acked: false, + unpublished: false, released_log: log.clone(), + }})); + assert_eq!(reg.next_sibling_index(1, 3), None); + assert!(!reg.wants_compute_sibling(1, &ctx, 3, req)); + + // Independent packet picks least-loaded idle sibling (qid 12). + let indep = Packet {{ order: Order {{ wait_through: [None, None] }}, completion: Completion {{ sources: None }} }}; + assert_eq!(reg.select_compute_channel(1, &indep), Some(12)); + + // When all 3 have equal active_len=1, oldest last_published (qid 12, lp=50) wins. + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 1; + assert_eq!(reg.select_compute_channel(1, &indep), Some(12)); + + // Dependent packet when only ONE channel is active stays on that sole active channel. + reg.compute[0].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 0; + reg.compute[2].as_mut().unwrap().queue.as_deref_mut().unwrap().active_len = 0; + let dep = Packet {{ order: Order {{ wait_through: [None, Some(42)] }}, completion: Completion {{ sources: None }} }}; + assert_eq!(reg.select_compute_channel(1, &dep), Some(11)); + + // 5. Multi-channel exit acknowledgment must mark ALL channels sharing the cookie. + reg.acknowledge_compute_exit(0xabc); + for slot in 0..3 {{ + assert!(reg.compute[slot].as_ref().unwrap().queue.as_deref().unwrap().exit_acked, + "channel slot {{}} did not receive shared exit cookie ack", slot); + }} + assert!(!reg.teardown.render_acked); + + // 6. Sibling-before-primary release order. + reg.release_compute(1).unwrap(); + let entries = log.borrow(); + assert_eq!(entries.len(), 3); + assert_ne!(entries[0].1, 0, "first release must be a sibling"); + assert_ne!(entries[1].1, 0, "second release must be a sibling"); + assert_eq!(entries[2].1, 0, "primary must be released last"); + assert_eq!(reg.qids.cancelled, vec![11]); + assert!(reg.compute[1].is_none()); + + println!("PASS g17-m5-sibling-compute: all checks passed"); +}} +''' + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--mutation', choices=[ + 'fixed-object-ids', + 'primary-before-sibling', + 'exit-ack-stops-first', + 'direct-allows-multi-barrier', + 'direct-blocks-sibling', + 'direct-locks-sibling-when-idle', + 'direct-skips-multi', + 'same-qid-pipelined', + ]) + args = ap.parse_args() + + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-sib-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + cc = subprocess.run([rustc, '--edition=2021', '-O', str(rs), '-o', str(exe)], + capture_output=True, text=True) + if cc.returncode != 0: + sys.stderr.write(cc.stderr) + return cc.returncode + run = subprocess.run([str(exe)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py new file mode 100755 index 0000000000000..b943c2a6d9c15 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -0,0 +1,527 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for the M5 Pro sibling compute fan-out gate. + +Compiles the production gate against host stubs: the heavy-kick run in +drivers/gpu/drm/asahi/g17/pairs.rs, `Backend::fans_out()`, the lock-free channel +selection section of `compute_direct()`, the `ComputeCell` hint mirror, and the +registry's `select_compute_channel()` / `wants_compute_sibling()`. It checks: + +a. A command with cross-queue input sources never leaves the primary channel and + never brings up a sibling, on the direct and the device-mutex paths, and the + direct path still resolves those sources before routing (published sources, + binding loans). +b. Kicks whose firmware execution records stay under the heavy threshold stream + down the primary ring: no sibling routing, no detour to the device-mutex path + to add one, no new sibling; one long kick among short ones does not open the + gate and one short kick closes it. +c. Sustained heavy kicks fan out onto an idle sibling (or ask for one when every + channel is busy) only once two kicks of the owner are already in flight, so a + kick queued behind one in flight stays on the primary ring; each sibling has + its own compute pool, with monotonic per-context ordinals and object ids, and + the gate is read through the primary cell's lock-free hint. +d. The sibling channels keep the published-source, binding-loan and idle + housekeeping paths of the queues they share a context with. + +Each mutation restores one old behaviour or drops one part of the rule, and must +fail an assertion of the compiled harness. +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ASAHI = ROOT / 'drivers/gpu/drm/asahi' +G17 = 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 const(source, name): + match = re.search(r'(?:pub\(crate\) )?const ' + name + r': [^=]+= [^;]+;', source, re.S) + assert match, name + return match.group(0).replace('pub(crate) ', '') + + +def ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # (a) a command with sources fans out like any other. + 'sources-fan-out': [('runtime', ' && packet.completion.sources().is_none()\n && primary_sustained()', + ' && primary_sustained()')], + 'select-sources-anywhere': [('runtime', ' if let Some((qid, _)) = primary.filter(|_| packet.completion.sources().is_some()) {\n return Some(qid);\n }\n', '')], + # (b) short kicks fan out. + 'tiny-fans-out': [('pairs', 'if end.saturating_sub(start) >= SIBLING_EXECUTION_TICKS {', 'if end >= start {')], + 'no-sustain-run': [('pairs', 'run >= SIBLING_SUSTAINED_KICKS', 'run >= 1')], + 'short-keeps-run': [('pairs', ' } else {\n 0\n }\n}', ' } else {\n run\n }\n}')], + 'direct-ignores-gate': [('runtime', 'let target_idx = if cached_count == 1 || !fans_out {', 'let target_idx = if cached_count == 1 {')], + 'direct-can-add-ungated': [('runtime', ' let can_add_sibling = fans_out\n && cached_count', + ' let can_add_sibling = packet.order.wait_through[1].is_none()\n && cached_count')], + 'wants-ignores-sustained': [('runtime', 'if !sustained_primary || !all_busy', 'if !all_busy')], + 'select-ignores-sustained': [('runtime', ' if let Some((qid, false)) = primary {\n return Some(qid);\n }\n', '')], + # (c) the lock-free hint loses the gate, or the gate takes a lock first. + 'cell-drops-sustained': [('runtime', 'self.sustained.store(queue.sustained(), Ordering::Release);', + 'self.sustained.store(false, Ordering::Release);')], + 'fans-out-locks-first': [('runtime', ' self.compute_channels > 1\n && packet.order.wait_through[1].is_none()\n' + ' && packet.completion.sources().is_none()\n && primary_sustained()', + ' primary_sustained()\n && self.compute_channels > 1\n' + ' && packet.order.wait_through[1].is_none()\n && packet.completion.sources().is_none()')], + # (c) A kick overlaps the owner's work while only one kick is in flight. + 'overlap-at-one': [('pairs', 'in_flight >= SIBLING_MIN_IN_FLIGHT', 'in_flight >= 1')], + 'direct-ignores-in-flight': [('runtime', ' if !super::pairs::overlaps(in_flight) {\n 0\n } else if', + ' if false {\n 0\n } else if')], + 'select-ignores-in-flight': [('runtime', ' if let Some((qid, _)) = primary.filter(|_| !super::pairs::overlaps(in_flight)) {\n' + ' return Some(qid);\n }\n', '')], + 'wants-ignores-in-flight': [('runtime', ' || !super::pairs::overlaps(in_flight) {', ' {')], + 'detour-at-one': [('runtime', ' && super::pairs::overlaps(queue.active_len()))', + ' && (queue.active_len() != 0 || queue.configuring()))')], + # A reused channel keeps the previous owner's run of heavy kicks. + 'keep-run-across-owners': [('queue', ' self.channel_index = channel_index;\n self.heavy_run = 0;\n', + ' self.channel_index = channel_index;\n')], +} + + +def build(mutation=None): + files = { + 'pairs': (G17 / 'pairs.rs').read_text(), + 'runtime': (G17 / 'runtime.rs').read_text(), + 'queue': (G17 / 'queue/compute.rs').read_text(), + } + for name, old, new in MUTATIONS.get(mutation, []): + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + pairs, runtime, queue = files['pairs'], files['runtime'], files['queue'] + context = (G17 / 'context.rs').read_text() + hw = (ASAHI / 'hw/t8140.rs').read_text() + events = (G17 / 'runtime/events.rs').read_text() + submit = (G17 / 'runtime/render/submit.rs').read_text() + + hz = const(hw, 'COMMAND_TIMESTAMP_HZ') + gate = '\n'.join([ + const(pairs, 'SIBLING_EXECUTION_NS'), + const(pairs, 'SIBLING_EXECUTION_TICKS').replace('crate::hw::t8140::resources::', ''), + const(pairs, 'SIBLING_SUSTAINED_KICKS'), + const(pairs, 'SIBLING_MIN_IN_FLIGHT'), + item(pairs, 'pub(crate) fn heavy_run('), + item(pairs, 'pub(crate) fn sustained('), + item(pairs, 'pub(crate) fn overlaps('), + ]).replace('pub(crate) ', '') + next_id = item(context, 'pub(crate) fn next_compute_identity(').replace('pub(crate) ', '') + queue_sustained = item(queue, 'pub(crate) fn sustained(&self)').replace('pub(crate) ', 'pub ') \ + .replace('crate::g17::pairs::sustained', 'crate::sustained') + sync_stats = item(runtime, 'fn sync_stats(') + load_hint = item(runtime, 'pub(super) fn load_hint(').replace('pub(super) ', '') + cell_sustained = item(runtime, 'pub(super) fn sustained(&self)').replace('pub(super) ', '') + fans_out = item(runtime, 'fn fans_out(').replace('super::job::Packet', 'Packet') + direct = item(runtime, 'fn compute_direct(') + select_start = direct.index(' let primary = cells[0].as_ref()?;') + select_end = direct.index(' let target_cell = cells[target_idx].as_ref()?;') + route = direct[select_start:select_end].replace('super::pairs::', '') + registry = '\n'.join(item(runtime, signature) for signature in [ + 'fn compute_channels_of(', 'fn next_sibling_index(', 'fn sibling_source(', + 'fn has_compute_sibling_headroom(', 'fn wants_compute_sibling(', 'fn select_compute_channel(', + ]).replace('super::job::Packet', 'Packet').replace('super::freelist::ComputeCapacity', 'ComputeCapacity') \ + .replace('super::pairs::', '') + sibling_source = item(runtime, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + inline = item(runtime, 'fn compute_inline(') + packet_fn = item(runtime, ' fn compute_packet(') + readiness = item(runtime, 'fn compute_readiness(&self, packet:') + bind_owner = item(queue, 'fn bind_owner_channel(') + clear_owner = item(queue, 'fn clear_owner(') + publish = item(queue, 'pub(in crate::g17) fn publish_with_native_waits(') + retire_arm_start = queue.index('Ok(Some((timestamps, stampless))) => {') + retire_arm = queue[retire_arm_start:queue.index('Ok(None) | Err(EAGAIN) => {', retire_arm_start)] + render_deps = item(submit, 'fn render_dependencies(') + + # Structural rules that the compiled part cannot see, each a Rust assertion below. + structure = { + # (a) Both device-mutex paths ask the gate before any sibling work. + 'mutex paths ask fans_out before binding a sibling': ( + ordered_ok(inline, 'if self.fans_out(packet, || {', 'compute_primary(self.owner)', + '.is_some_and(|queue| queue.sustained())', 'wants_compute_sibling(', + 'bind_reusable_sibling(') + and ordered_ok(packet_fn, 'if !sibling_tried', '&& self.fans_out(packet, || {', + '.is_some_and(|queue| queue.sustained())', 'wants_compute_sibling(', + 'bind_reusable_sibling(', 'self.try_add_compute_sibling(required, &admission)?') + and 'packet.order.wait_through[1].is_none()\n {' not in packet_fn), + # (a, d) Direct sources still resolve lock-free from their PublishedSource snapshots with + # binding loans before any routing, and the holds follow the publication. + 'direct sources resolve before routing, holds follow publication': ordered_ok( + direct, 'if (has_sources && !m5)', 'let generation = port.generation();', + 'self.resolve_direct_sources(port, generation, target_qid, sources)?', + 'let fans_out = self.fans_out(packet, || primary.sustained());', + 'let target_cell = cells[target_idx].as_ref()?;', 'direct_frontier.as_slice()', + 'if packet.is_published() {', 'sources.set_holds(direct_holds);', 'drop(direct_holds);'), + 'readiness claims the primary for M5 sources': ordered_ok( + readiness, 'let sources_checked =', '(!sources_checked || self.context.is_m5())', + 'cells[1..].iter().flatten()', 'queue.claim()', 'self.hold_claim(Some(primary));'), + # (b, c) The direct path detours to the device-mutex path for a sibling only when it may + # add one: a busy single channel under a closed gate, or with a single kick in flight, + # keeps publishing directly. + 'direct detours only when it may add a sibling': ordered_ok( + direct, '(cached_count == 1\n && can_add_sibling\n' + ' && super::pairs::overlaps(queue.active_len()))'), + # (b, c) The run is measured on exact execution records only, once per retired kick, + # and starts over for every owner. + 'only exact records measure a kick': ordered_ok( + retire_arm, 'let execution = front.observed.map(|record| record.timestamps);', + 'defer(match producers {', 'self.retire_pending = false;', + 'if let Some([start, end]) = execution {', + 'self.heavy_run = crate::g17::pairs::heavy_run(self.heavy_run, start, end);'), + 'a new owner starts a new run': ( + 'self.heavy_run = 0;' in clear_owner + and ordered_ok(bind_owner, 'self.channel_index = channel_index;', 'self.heavy_run = 0;')), + # (d) A sibling's own QID and source readers are what its PublishedSource names; the + # shared context keeps one ordinal sequence across channels. + 'siblings publish their own QID as a source': ordered_ok( + publish, 'packet.context.next_compute_identity()', + 'crate::g17::fw::kick::KickDependency::new(qid, kick_timestamp)', + 'packet.completion.note_source_published(', 'readers: self.source_readers.clone(),'), + # (d) The deferred idle housekeeping counts every compute queue, siblings included, as + # in flight; renders wait on every compute channel of the owner. + 'idle housekeeping sees sibling work': ordered_ok( + events, '.compute', '.iter()', '.flatten()', '.filter_map(|entry| entry.queue.as_deref())', + '.any(|queue| queue.in_flight())', 'firmware.idle_check(now, in_flight)?'), + 'renders wait on every compute channel': ordered_ok( + render_deps, '.filter(|queue| queue.owner() == Some(owner))', '.compute_count', + 'dependencies.compute_count += 1;'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' + for name, ok in structure.items()) + + return (TEMPLATE + .replace('@@HZ@@', hz) + .replace('@@GATE@@', gate) + .replace('@@NEXT_ID@@', next_id) + .replace('@@QUEUE_SUSTAINED@@', queue_sustained) + .replace('@@SYNC_STATS@@', sync_stats) + .replace('@@LOAD_HINT@@', load_hint) + .replace('@@CELL_SUSTAINED@@', cell_sustained) + .replace('@@FANS_OUT@@', fans_out) + .replace('@@ROUTE@@', route) + .replace('@@REGISTRY@@', registry) + .replace('@@SIBLING_SOURCE@@', sibling_source) + .replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports)] +use std::cell::{Cell, RefCell}; +use std::collections::HashSet; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +const EIO: i32 = -5; +type Result = std::result::Result; + +@@HZ@@ +@@GATE@@ + +thread_local! { static NOW: Cell = Cell::new(1_000_000_000); } +fn now_ns() -> u64 { NOW.with(|now| now.get()) } + +/// Ticks of an execution record lasting `us` microseconds. +fn ticks(us: u64) -> u64 { us * COMMAND_TIMESTAMP_HZ / 1_000_000 } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +@@SIBLING_SOURCE@@ + +struct Completion { sources: Option<()> } +impl Completion { fn sources(&self) -> Option<&()> { self.sources.as_ref() } } +struct Order { wait_through: [Option; 2] } +struct Packet { order: Order, completion: Completion } +fn packet(sources: bool, through: Option) -> Packet { + Packet { order: Order { wait_through: [None, through] }, + completion: Completion { sources: sources.then_some(()) } } +} + +struct Context { vm_id: u32, compute_ordinal: AtomicU32 } +impl Context { + fn new(vm_id: u32) -> Arc { Arc::new(Self { vm_id, compute_ordinal: AtomicU32::new(0) }) } + fn vm(&self) -> u32 { self.vm_id } + @@NEXT_ID@@ +} + +mod compute { + /// The routing-relevant state of one physical compute channel. + pub struct Queue { + pub qid: u8, pub owner: Option, pub channel_index: u8, pub active: usize, + pub replays: usize, pub configuring: bool, pub last_published: u64, pub heavy_run: u8, + pub reusable: bool, pub pool_vm: u32, pub pool_cap: u32, + } + impl Queue { + pub fn active_len(&self) -> usize { self.active } + pub fn configuring(&self) -> bool { self.configuring } + pub fn last_published(&self) -> u64 { self.last_published } + @@QUEUE_SUSTAINED@@ + } +} + +/// The hint fields of the production cell; the mutex-held queue is passed in. +struct ComputeCell { + active_len: AtomicU32, configuring: AtomicBool, last_published: AtomicU64, sustained: AtomicBool, +} +impl ComputeCell { + fn new() -> Arc { + Arc::new(Self { active_len: AtomicU32::new(0), configuring: AtomicBool::new(false), + last_published: AtomicU64::new(0), sustained: AtomicBool::new(false) }) + } + @@SYNC_STATS@@ + @@LOAD_HINT@@ + @@CELL_SUSTAINED@@ +} + +struct Backend { compute_channels: u8, sibling_backoff_until: AtomicU64, gate_asked: Cell } +impl Backend { + @@FANS_OUT@@ + /// compute_direct()'s lock-free channel selection: `None` sends the packet to the + /// device-mutex path, otherwise `(target channel, may add a sibling)`. + fn route(&self, packet: &Packet, cells: &[Option>; 3], cached_count: usize) + -> Option<(usize, bool)> + { +@@ROUTE@@ + Some((target_idx, can_add_sibling)) + } +} + +impl compute::Queue { + fn qid(&self) -> u8 { self.qid } + fn owner(&self) -> Option { self.owner } + fn channel_index(&self) -> u8 { self.channel_index } + fn is_primary(&self) -> bool { self.channel_index == 0 } + fn has_replays(&self) -> bool { self.replays != 0 } + fn reusable(&self) -> bool { self.reusable } + fn needs_fresh_backing(&self) -> bool { false } + fn pool_vacant(&self) -> bool { false } + fn rearm_open(&self, _: u64) -> bool { true } + fn released_at(&self) -> u64 { 0 } + fn vacancy_pending(&self) -> bool { false } + fn pool_serves(&self, vm: u32) -> bool { self.pool_vm == vm } + fn pool_fits(&self, required: ComputeCapacity) -> bool { self.pool_cap >= required.0 } + fn has_ring(&self) -> bool { true } + fn context(&self) -> Option<&Arc> { None } +} + +struct Slot(RefCell); +impl Slot { fn as_deref(&self) -> Option> { Some(self.0.borrow()) } } +struct Entry { queue: Slot } +struct Qids { fit: bool } +impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } +struct Admission; +impl Admission { fn queues(&self) -> u32 { 1 } } +struct Teardown; +impl Teardown { fn releasing(&self, _: &Arc) -> bool { false } } +struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } +impl Registry { +@@REGISTRY@@ +} + +const OWNER: u64 = 7; + +fn channel(qid: u8, channel_index: u8, active: usize, heavy_run: u8) -> compute::Queue { + compute::Queue { qid, owner: Some(OWNER), channel_index, active, replays: 0, configuring: false, + last_published: u64::from(qid), heavy_run, reusable: false, pool_vm: 70, pool_cap: 16 } +} + +fn registry(queues: Vec) -> Registry { + Registry { compute: queues.into_iter().map(|queue| Some(Entry { queue: Slot(RefCell::new(queue)) })).collect(), + qids: Qids { fit: true }, admission: Admission, teardown: Teardown } +} + +/// The cells compute_direct() caches, each hint mirrored from its queue by the production +/// sync_stats(), as the queue guard does when it drops. +fn cells(queues: &[compute::Queue]) -> [Option>; 3] { + let mut cells = [None, None, None]; + for queue in queues { + let cell = ComputeCell::new(); + cell.sync_stats(Some(queue)); + cells[usize::from(queue.channel_index)] = Some(cell); + } + cells +} + +fn backend() -> Backend { + Backend { compute_channels: 3, sibling_backoff_until: AtomicU64::new(0), gate_asked: Cell::new(0) } +} + +fn run_of(records_us: &[u64]) -> u8 { + records_us.iter().fold(0, |run, &us| heavy_run(run, 5_000, 5_000 + ticks(us))) +} + +fn main() { +@@STRUCTURE@@ + + // The threshold, from the record's 24 MHz command timestamps. + assert_eq!(SIBLING_EXECUTION_TICKS, ticks(SIBLING_EXECUTION_NS / 1_000)); + assert_eq!(SIBLING_EXECUTION_TICKS, 2_400, "100 us at 24 MHz"); + + // (b) Short kicks never build a run; one long kick among short ones does not open the + // gate; a short kick closes it at once. + assert_eq!(run_of(&[3; 64]), 0, "a stream of 3 us kicks has no heavy run"); + assert_eq!(run_of(&[99]), 0, "just under the threshold is short"); + assert!(!sustained(run_of(&[3, 3, 900, 3, 3])), "one long kick does not fan a stream out"); + assert!(!sustained(run_of(&[270])), "one heavy kick is not yet sustained"); + assert!(sustained(run_of(&[100, 270])), "two consecutive heavy kicks are"); + assert!(sustained(run_of(&[490, 490, 490]))); + assert!(!sustained(run_of(&[490, 490, 490, 3])), "a short kick closes the gate"); + assert_eq!(run_of(&[490; 300]), u8::MAX, "the run saturates"); + assert_eq!(heavy_run(5, 9_000, 1_000), 0, "a backwards record measures nothing"); + + let b = backend(); + // (a, b) The gate: only independent commands without sources, and the primary's state is + // asked last so a command that cannot fan out never looks at (or locks) the primary. + let ask = |answer: bool| { b.gate_asked.set(b.gate_asked.get() + 1); answer }; + assert!(b.fans_out(&packet(false, None), || ask(true))); + assert!(!b.fans_out(&packet(false, None), || ask(false)), "a light primary keeps its kicks"); + let asked = b.gate_asked.get(); + assert!(!b.fans_out(&packet(true, None), || ask(true)), "sources never fan out"); + assert!(!b.fans_out(&packet(false, Some(4)), || ask(true)), "nor in-queue barriers"); + assert_eq!(b.gate_asked.get(), asked, "the primary is not asked for them"); + let single = Backend { compute_channels: 1, ..backend() }; + assert!(!single.fans_out(&packet(false, None), || ask(true)), "one channel per owner"); + + // (c) The lock-free mirror of the gate. + let heavy_primary = channel(10, 0, 1, 2); + let cell = ComputeCell::new(); + cell.sync_stats(Some(&heavy_primary)); + assert!(cell.sustained()); + assert_eq!(cell.load_hint(), (false, 1, 10)); + cell.sync_stats(None); + assert!(!cell.sustained(), "an emptied cell is not sustained"); + + let light = [channel(10, 0, 4, 0), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy = [channel(10, 0, 2, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy_one = [channel(10, 0, 1, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]; + let heavy_busy = [channel(10, 0, 1, 2), channel(11, 1, 1, 0)]; + let indep = packet(false, None); + let sourced = packet(true, None); + + // (b) Short kicks stay on the busy primary ring even with idle siblings bound, and a lone + // busy primary does not detour to the device-mutex path to add a sibling. + assert_eq!(b.route(&indep, &cells(&light), 3), Some((0, false)), "short kicks stream down channel 0"); + assert_eq!(b.route(&indep, &cells(&light[..1]), 1), Some((0, false)), + "a busy light primary keeps publishing directly"); + // (a) A command with sources takes the primary even when it is busy and heavy. + assert_eq!(b.route(&sourced, &cells(&heavy), 3), Some((0, false)), "sources stay on channel 0"); + assert_eq!(b.route(&sourced, &cells(&heavy[..1]), 1), Some((0, false)), + "sources never ask for a sibling"); + // (c) Sustained heavy work fans out onto the least-loaded idle sibling, asks the + // device-mutex path for a sibling when every bound channel is busy, and a lone heavy + // busy primary may add one. + assert_eq!(b.route(&indep, &cells(&heavy), 3), Some((1, false)), "heavy kicks take an idle sibling"); + // (c) ... once two are in flight: behind a single kick the next one queues on channel 0. + assert_eq!(b.route(&indep, &cells(&heavy_one), 3), Some((0, false)), + "a kick queues behind a single kick in flight"); + assert_eq!(b.route(&indep, &cells(&[channel(10, 0, 1, 2), channel(11, 1, 0, 0)]), 2).map(|(idx, _)| idx), + Some(0), "also with an idle sibling bound"); + assert_eq!(b.route(&indep, &cells(&heavy_busy), 2), None, "all busy: bring up the third channel"); + assert_eq!(b.route(&indep, &cells(&heavy[..1]), 1), Some((0, true))); + b.sibling_backoff_until.store(now_ns() + 1, Ordering::Relaxed); + assert_eq!(b.route(&indep, &cells(&heavy_busy), 2), Some((0, false)), + "after a headroom miss the bound channels are used"); + b.sibling_backoff_until.store(0, Ordering::Relaxed); + let idle_heavy = [channel(10, 0, 0, 2), channel(11, 1, 1, 0)]; + assert_eq!(b.route(&indep, &cells(&idle_heavy), 2), Some((0, true)), + "an idle primary comes first; only a busy lone channel detours for a sibling"); + + // (c) Fanned-out kicks get one monotonic sequence of ordinals and object ids from their + // shared context, whichever channel publishes them. + let context = Context::new(70); + let mut seen = HashSet::new(); + let mut last = 0; + for kick in 0..64u32 { + let (ordinal, object_ids) = context.next_compute_identity(); + assert_eq!(ordinal, kick + 1); + assert!(ordinal > last && seen.insert(object_ids as u32)); + assert_eq!((object_ids >> 32) as u32, last.max(1), "each id names its predecessor"); + last = ordinal; + } + + // Device-mutex selection and sibling admission follow the same gate. + let req = ComputeCapacity(16); + let ctx = Context::new(70); + // (b) A light primary brings up no sibling though every channel is busy and QIDs are free. + let reg = registry(vec![channel(10, 0, 3, 0), channel(11, 1, 1, 0)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req), "a light primary wants no sibling"); + // (c) A sustained heavy primary does. + let reg = registry(vec![channel(10, 0, 1, 2), channel(11, 1, 1, 0)]); + assert!(reg.wants_compute_sibling(OWNER, &ctx, 3, req)); + // ... only while every channel is busy. + let reg = registry(vec![channel(10, 0, 1, 2), channel(11, 1, 0, 0)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req)); + // ... and two kicks are in flight: one kick behind which the next queues brings up none. + let reg = registry(vec![channel(10, 0, 1, 2)]); + assert!(!reg.wants_compute_sibling(OWNER, &ctx, 3, req), "one kick in flight wants no sibling"); + let reg = registry(vec![channel(10, 0, 2, 2)]); + assert!(reg.wants_compute_sibling(OWNER, &ctx, 3, req), "two kicks in flight do"); + + let reg = registry(light.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(10), "short kicks take the primary"); + let reg = registry(heavy.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(11), "heavy kicks spread"); + let reg = registry(heavy_one.into_iter().collect()); + assert_eq!(reg.select_compute_channel(OWNER, &indep), Some(10), + "behind a single kick in flight the next one queues on the primary"); + let reg = registry(vec![channel(10, 0, 2, 2), channel(11, 1, 0, 0), channel(12, 2, 0, 0)]); + assert_eq!(reg.select_compute_channel(OWNER, &sourced), Some(10), "sources take the primary"); + assert_eq!(reg.select_compute_channel(OWNER, &packet(true, Some(3))), Some(10), + "even when a dependency could stay on another channel"); + // A dependent command still follows the sole active channel (no cross-channel barrier). + let reg = registry(vec![channel(10, 0, 0, 2), channel(11, 1, 2, 0)]); + assert_eq!(reg.select_compute_channel(OWNER, &packet(false, Some(3))), Some(11)); + + // The threshold itself. + assert!(!overlaps(0) && !overlaps(1) && overlaps(2) && overlaps(3)); + + println!("PASS g17-m5-sibling-gate: sources, short kicks and a kick behind a single one stay on the primary ring, sustained heavy kicks fan out"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-sibling-gate-') as tmp: + path = Path(tmp) / 'gate.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py new file mode 100755 index 0000000000000..6fbdd10e119d1 --- /dev/null +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -0,0 +1,646 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: M5 sibling compute channels come from vacant and other-VM idle queues too. + +Once earlier clients have taken compute QIDs up to the fresh-QID ceiling +(`compute_fits()` false), every idle compute queue is either vacant (its pool +given back after the idle expiry) or still holds the pool of a VM that is gone. +A sibling that could only bind a populated pool of its own VM, or a fresh QID, +then never came up again until the GPU slept. This test compiles the production +code that decides and performs the sibling's acquisition against host stubs: + +- the queue predicates of drivers/gpu/drm/asahi/g17/queue/compute.rs that say + which queue may change owner (`reusable`, `can_rearm`, `rearm_open`, + `shareable`, `recycled_pending`, `vacancy_pending`, `vacate_candidate`) and + the queue's pool give-back and re-arm transitions (`require_fresh_backing`, + `vacate`, `observe_vacancy`, `rearm`, `bind_sibling`); +- the registry's `sibling_source()`, `has_compute_sibling_headroom()`, + `wants_compute_sibling()`, `bind_reusable_sibling()`, `give_back_foreign()`, + `reserve_rearm()`, `rearm_compute()`, `bind_rearmed()` and the pool pass + `vacate_idle_pools()` from drivers/gpu/drm/asahi/g17/runtime.rs. + +It checks that with no fresh QID a new client still gets every sibling it +wants, first from vacant queues (re-armed with fresh backing, bound as sibling +channels) and then from other VMs' idle queues (given back one at a time, +vacated by the pool pass, re-armed), across clients that come and go; that a +queue with an owner or work, an open client's idle channel, a queue another +client is re-arming, one whose scheduler release is in flight and one whose +pool release is in flight are never taken; that a fresh QID comes before +another VM's pool is given back; and, structurally, that +`try_add_compute_sibling()` takes these sources through the primary's re-arm +path, lets an owner waiting for its first channel go first and that the primary +path gives back other VMs' queues through the same helper. + +Each mutation restores the old rule or drops one part of the new one and must +fail an assertion of the compiled harness. +""" +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 ordered_ok(source, *parts): + at = -1 + for part in parts: + idx = source.find(part, at + 1) + if idx < 0: + return False + at = idx + return True + + +# The headroom rule before this change: a populated same-VM pool or a fresh QID only. +OLD_SOURCE = '''fn sibling_source( + &self, + owner: u64, + context: &Arc, + required: super::freelist::ComputeCapacity, + ) -> Option { + let teardown = &self.teardown; + let vm = context.vm(); + let warm = self + .compute + .iter() + .flatten() + .filter_map(|entry| entry.queue.as_deref()) + .filter(|queue| { + queue.reusable() + && !queue.needs_fresh_backing() + && !queue.pool_vacant() + && queue.pool_serves(vm) + && queue.pool_fits(required) + && queue.has_ring() + && !queue.context().is_some_and(|bound| teardown.releasing(bound)) + }) + .map(|queue| (queue.released_at(), queue.qid())) + .min_by_key(|(key, _)| *key) + .map(|(_, qid)| SiblingSource::Warm(qid)); + warm.or_else(|| { + self.qids + .compute_fits(self.admission.queues() as usize) + .then_some(SiblingSource::Fresh) + }) + }''' + +# name -> [(file, old, new)]: each must apply exactly once. +MUTATIONS = { + # The old rule: no vacant and no other-VM queue is ever a sibling source. + 'old-headroom': [('source', None, OLD_SOURCE)], + 'no-vacant-sibling': [('runtime', ' if let Some((_, qid)) = vacant {\n', ' if let Some((_, qid)) = vacant.filter(|_| false) {\n')], + 'no-foreign-sibling': [('runtime', ' foreign.map(|(_, qid)| SiblingSource::Foreign(qid))\n', ' None\n')], + # Never steal: an open client's idle channel, a busy queue, a queue another client re-arms, + # a queue whose scheduler release is in flight. + 'steal-shareable': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.reusable() || queue.shareable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {')], + 'steal-unowned': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.owner() != Some(owner))\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {')], + 'ignore-rearm-reservation': [('runtime', ' if !queue.rearm_open(owner) {\n continue;\n' + ' }\n &mut vacant\n', ' &mut vacant\n')], + 'ignore-releasing': [('runtime', ' .filter(|queue| queue.reusable())\n' + ' .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound)))\n' + ' {\n let best = if queue.pool_vacant() {', + ' .filter(|queue| queue.reusable())\n' + ' {\n let best = if queue.pool_vacant() {')], + # Give back several other-VM pools at once. + 'parallel-give-back': [('runtime', ' .any(|queue| queue.vacancy_pending())\n {\n return None;\n }\n' + ' foreign.map(', ' .any(|queue| queue.vacancy_pending() && false)\n {\n' + ' return None;\n }\n foreign.map(')], + # Give another VM's pool back while a fresh QID fits. + 'foreign-before-fresh': [('runtime', ' if self.qids.compute_fits(self.admission.queues() as usize) {\n' + ' return Some(SiblingSource::Fresh);\n }\n // A pool release', + ' if foreign.is_none() && self.qids.compute_fits(self.admission.queues() as usize) {\n' + ' return Some(SiblingSource::Fresh);\n }\n // A pool release')], + # A re-armed sibling is bound as the owner's primary. + 'rearm-binds-primary': [('runtime', ' if channel_index == 0 {\n queue.bind_owner(owner, context.clone())', + ' if true {\n queue.bind_owner(owner, context.clone())')], + # Structural: try_add_compute_sibling() without the re-arm, the waiter rule, the shared give-back. + 'try-add-ignores-waiters': [('runtime', ' || self.shared.channels.has_waiters()\n', '')], + 'try-add-skips-rearm': [('runtime', ' firmware.queues.reserve_rearm(qid, self.owner)?;\n Err(qid)\n', + ' return Ok(false);\n')], + 'rearm-any-index': [('runtime', ' && (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' + ' == Some(channel_index));\n', ';\n')], + 'primary-own-give-back': [('runtime', ' if let Some(qid) = foreign {\n self.give_back_foreign(qid)?;\n', + ' if let Some(qid) = foreign {\n self.compute_queue_mut(qid).ok_or(EIO)?.require_fresh_backing();\n')], +} + + +def build(mutation=None): + files = { + 'runtime': (G17 / 'runtime.rs').read_text(), + 'queue': (G17 / 'queue/compute.rs').read_text(), + 'pairs': (G17 / 'pairs.rs').read_text(), + 'freelist': (G17 / 'freelist.rs').read_text(), + } + old_source = False + for name, old, new in MUTATIONS.get(mutation, []): + if name == 'source': + old_source = True + continue + assert files[name].count(old) == 1, (mutation, old) + files[name] = files[name].replace(old, new) + runtime, queue, pairs, freelist = files['runtime'], files['queue'], files['pairs'], files['freelist'] + source_fn = item(runtime, 'fn sibling_source(') + if old_source: + runtime = runtime.replace(source_fn, OLD_SOURCE) + source_fn = OLD_SOURCE + + queue_fns = '\n'.join(item(queue, signature) for signature in [ + 'pub(crate) fn reusable(&self)', 'pub(crate) fn can_rearm(&self)', 'pub(crate) fn rearm_open(', + 'pub(crate) fn reserve_rearm(', 'pub(crate) fn release_rearm(', 'pub(crate) fn require_fresh_backing(', + 'pub(crate) fn needs_fresh_backing(', 'pub(crate) fn pool_vacant(', 'pub(crate) fn pool_serves(', + 'pub(crate) fn pool_fits(', 'pub(crate) fn recycled_pending(', 'pub(crate) fn vacancy_pending(', + 'pub(crate) fn pool_release_pending(', 'pub(crate) fn vacate_candidate(', 'pub(crate) fn released_at(', + 'pub(crate) fn has_ring(', 'pub(crate) fn rearm(\n', 'pub(crate) fn vacate(&mut self', + 'pub(crate) fn observe_vacancy(', 'pub(crate) fn shareable(', 'pub(crate) fn owner(&self)', + 'pub(crate) fn channel_index(&self)', 'pub(crate) fn is_primary(&self)', 'pub(crate) fn active_len(&self)', + 'pub(crate) fn has_replays(&self)', 'pub(crate) fn configuring(&self)', 'pub(crate) fn context(&self)', + 'pub(crate) fn bind_sibling(', 'pub(crate) fn bind_owner(&mut self', + ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') \ + .replace('crate::g17::freelist::Pages', 'Pages').replace('crate::g17::initdata::InitData', 'InitData') \ + .replace('crate::g17::now_ns()', 'now_ns()').replace('crate::g17::freelist::control_consumed', 'control_consumed') + pool_fns = '\n'.join(item(freelist, signature) for signature in [ + 'pub(crate) fn populated(&self)', 'pub(crate) fn serves(&self', 'pub(crate) fn take_pages(', + ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') + registry_fns = '\n'.join(item(runtime, signature) for signature in [ + 'fn compute_channels_of(', 'fn next_sibling_index(', 'fn has_compute_sibling_headroom(', + 'fn wants_compute_sibling(', 'fn bind_reusable_sibling(', 'fn compute_queue_mut(', + 'fn give_back_foreign(', 'fn reserve_rearm(&mut self, qid', 'pub(super) fn release_rearm(', + 'pub(super) fn rearm_compute(', 'pub(super) fn bind_rearmed(', 'pub(super) fn vacate_idle_pools(', + ] if True) + '\n' + source_fn + registry_fns = registry_fns.replace('pub(super) ', '').replace('super::freelist::ComputeCapacity', 'ComputeCapacity') \ + .replace('super::pairs::', '').replace('super::initdata::InitData', 'InitData') \ + .replace('crate::g17::freelist::Pages', 'Pages').replace('compute::DescriptorRing', 'DescriptorRing') \ + .replace('super::freelist::PoolDescriptor', 'PoolDescriptor').replace('compute::Vacated', 'Vacated') + enum = item(runtime, 'pub(super) enum SiblingSource').replace('pub(super) ', '') + pairs_fns = '\n'.join([ + 'const SIBLING_MIN_IN_FLIGHT: usize = ' + + pairs.split('pub(crate) const SIBLING_MIN_IN_FLIGHT: usize = ', 1)[1].split(';', 1)[0] + ';', + item(pairs, 'pub(crate) fn overlaps(').replace('pub(crate) ', ''), + ]) + + try_add = item(runtime, 'fn try_add_compute_sibling(') + rearm_vacant = item(runtime, 'fn rearm_vacant(') + rebind = item(runtime, 'pub(super) fn rebind_compute(') + build_compute = item(runtime, 'fn build_compute(') + structure = { + 'try_add takes every source through its own path': ordered_ok( + try_add, '|| self.shared.channels.has_waiters()', 'wants_compute_sibling(', + 'firmware.queues.sibling_source(self.owner, &self.context, required)', + 'Some(SiblingSource::Warm(_)) =>', 'bind_reusable_sibling(', + 'Some(SiblingSource::Foreign(qid)) =>', 'firmware.queues.give_back_foreign(qid)?;', + 'drop(state);', 'self.shared.queue_events();', 'return Ok(false);', + 'Some(SiblingSource::Vacant(qid)) =>', 'firmware.queues.reserve_rearm(qid, self.owner)?;', 'Err(qid)', + 'Some(SiblingSource::Fresh) =>', 'reserve_compute_channel(self.owner, self.compute_channels)', + 'Err(qid) => {', 'self.rearm_vacant(\n qid,\n channel_index,\n required,', + 'if !bound {', 'firmware.queues.release_rearm(qid, self.owner);', 'admission.check()?;', + 'return Ok(bound);', 'compute::PoolBacking::new('), + 'a re-arm binds the channel it was reserved for, through the primary path': ordered_ok( + rearm_vacant, 'crate::g17::freelist::Pages::for_compute(', 'compute::DescriptorRing::new(', + 'let mut state = self.shared.state.lock();', 'if !lease.is_current()', 'self.admission_open()', + 'queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)', + '&& (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' + ' == Some(channel_index));', + 'firmware.queues.rearm_compute(qid, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', + 'firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?;'), + 'the primary re-arms channel 0': 'self.rearm_vacant(qid, 0, required,' in build_compute, + 'the primary gives back other VMs\' queues through the same helper': ordered_ok( + rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant() && !queue.pool_serves(vm))', + 'if let Some(qid) = foreign {', 'self.give_back_foreign(qid)?;', 'return Err(ENOSPC);'), + } + checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) + return (TEMPLATE.replace('@@ENUM@@', enum).replace('@@PAIRS@@', pairs_fns).replace('@@QUEUE@@', queue_fns) + .replace('@@POOL@@', pool_fns).replace('@@REGISTRY@@', registry_fns).replace('@@STRUCTURE@@', checks)) + + +TEMPLATE = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports, unreachable_code, unused_assignments)] +use std::cell::RefCell; +use std::sync::Arc; +use std::sync::atomic::{fence, AtomicU32, Ordering}; + +const EIO: i32 = -5; +const EAGAIN: i32 = -11; +const EBUSY: i32 = -16; +const EPERM: i32 = -1; +const ENOSPC: i32 = -28; +type Result = std::result::Result; +const GFP_KERNEL: () = (); +struct KVec(Vec); +impl KVec { + fn with_capacity(n: usize, _: ()) -> Result { Ok(Self(Vec::with_capacity(n))) } + fn push(&mut self, value: T, _: ()) -> Result { self.0.push(value); Ok(()) } +} +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } + +fn now_ns() -> u64 { 5_000_000_000 } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct ComputeCapacity(u32); + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +@@ENUM@@ + +@@PAIRS@@ + +pub struct Vm(u32); +impl Vm { pub fn id(&self) -> u32 { self.0 } } +pub struct Context { id: u32, vm: Vm, current: bool } +impl Context { + fn new(id: u32, vm: u32) -> Arc { Arc::new(Self { id, vm: Vm(vm), current: true }) } + fn vm(&self) -> &Vm { &self.vm } + fn is_current(&self) -> bool { self.current } +} + +#[derive(Debug)] +pub struct Pages(u32); +pub struct DescriptorRing; +#[derive(Debug, PartialEq)] +pub struct PoolDescriptor(u32); +pub struct InitData { control_cursor: std::cell::Cell } +pub struct KernelMapping; +pub struct Vacated { _alias: Option, _pages: Option, _descriptors: Option, _ring: Option } +pub struct FreeListRelease; +enum ControlRecord { FreeListRelease(FreeListRelease) } +struct Rings; +impl Rings { + fn publish_control(init: &InitData, _: &ControlRecord) -> Result { + let cursor = init.control_cursor.get() + 1; + init.control_cursor.set(cursor); + Ok(cursor) + } +} +/// The firmware consumed every control record up to `consumer`. +fn control_consumed(consumer: u32, _producer: u32, cursor: u32) -> Result { Ok(consumer >= cursor) } + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum PoolPhase { Populated, ReleaseSent(u32), Vacant } +pub struct Fifo { len: usize } +pub struct SourceHint; +impl SourceHint { fn has_readers(&self, count: &AtomicU32) -> bool { count.load(Ordering::Acquire) != 0 } } +pub struct Graph { ring: Option, m5: bool } +impl Graph { + fn rearm_ring(&mut self, ring: DescriptorRing) -> Option { self.ring.replace(ring) } + fn vacate_ring(&mut self) -> Option { self.ring.take() } +} +pub struct Binding { context: Arc, pool_alias: Option, descriptors: Option } +pub struct Pool { id: u16, client_vm: u32, pages: Option, cap: u32 } +impl Pool { +@@POOL@@ + fn fits_capacity(&self, required: ComputeCapacity) -> bool { self.pages.is_some() && self.cap >= required.0 } + fn rearm(&mut self, pages: Pages) -> Result { if self.pages.is_some() { return Err(EBUSY); } self.pages = Some(pages); Ok(()) } + fn descriptor(&self) -> Result { Ok(PoolDescriptor(u32::from(self.id))) } + fn release_record(&self, _generation: u64) -> FreeListRelease { FreeListRelease } +} + +/// The owner-change state of one physical compute queue, with the production field names. +pub struct Queue { + qid: u8, growing: bool, channel_error: bool, installed: bool, configuration: Option<()>, + pool_phase: PoolPhase, needs_fresh_backing: bool, exit: Option<()>, owner: Option, + released: bool, retirement_ready: bool, quarantined: bool, active: Fifo, replays: Fifo, + previous: Option<()>, source_hint: SourceHint, source_readers: AtomicU32, rearm_for: Option, + pool: Pool, graph: Graph, binding: Option, release_sent_ns: Option, + free_list_generation: u64, released_at: u64, claims: u32, awaiting_witness: bool, + channel_index: u8, sustained: bool, +} +impl Queue { +@@QUEUE@@ + fn qid(&self) -> u8 { self.qid } + fn sustained(&self) -> bool { self.sustained } + /// The production entry check of bind_owner_channel(); the views of the new VM are not modelled. + fn bind_owner_channel(&mut self, owner: u64, context: Arc, channel_index: u8) -> Result { + if !self.reusable() { + return Err(EBUSY); + } + if !self.pool.serves(context.vm()) { + return Err(EPERM); + } + self.pool.client_vm = context.vm().id(); + self.binding = Some(Binding { context, pool_alias: None, descriptors: None }); + self.owner = Some(owner); + self.channel_index = channel_index; + self.rearm_for = None; + self.released = false; + self.retirement_ready = false; + Ok(()) + } +} + +type QueueGuard<'a> = std::cell::RefMut<'a, Queue>; +struct Slot(RefCell); +impl Slot { + fn as_deref(&self) -> Option> { Some(self.0.borrow()) } + fn as_deref_mut(&mut self) -> Option> { Some(self.0.borrow_mut()) } +} +struct Entry { queue: Slot } +struct Qids { fit: bool } +impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } +struct Admission; +impl Admission { fn queues(&self) -> u32 { 4 } } +struct Teardown { releasing: Vec } +impl Teardown { fn releasing(&self, context: &Arc) -> bool { self.releasing.contains(&context.id) } } +struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } +impl Registry { + const POOL_RETRY_NS: u64 = 100_000_000; +@@REGISTRY@@ + fn queue(&self, qid: u8) -> std::cell::Ref<'_, Queue> { + self.compute.iter().flatten().map(|entry| entry.queue.0.borrow()).find(|queue| queue.qid == qid).unwrap() + } + fn queue_mut(&self, qid: u8) -> std::cell::RefMut<'_, Queue> { + self.compute.iter().flatten().map(|entry| entry.queue.0.borrow_mut()).find(|queue| queue.qid == qid).unwrap() + } + /// An event pass: the production pool pass gives back what must go, then the firmware + /// consumes the control ring and the release observation leaves those queues vacant. + fn pool_pass(&mut self, init: &InitData) { + vacate_idle_pools_pass(self, init); + let consumer = init.control_cursor.get(); + for entry in self.compute.iter_mut().flatten() { + let mut queue = entry.queue.0.borrow_mut(); + let _ = queue.observe_vacancy(consumer, consumer).unwrap(); + } + } + fn push(&mut self, queue: Queue) { self.compute.push(Some(Entry { queue: Slot(RefCell::new(queue)) })); } +} +fn vacate_idle_pools_pass(registry: &mut Registry, init: &InitData) { + // Idle pools stay warm (cap 3, no expiry): only queues given back are released. + registry.vacate_idle_pools(init, 3, now_ns(), u64::MAX).unwrap(); +} + +/// An installed queue owned by `owner` (channel 0) with `active` kicks in flight. +fn bound(qid: u8, owner: u64, context: &Arc, active: usize) -> Queue { + Queue { + qid, growing: false, channel_error: false, installed: true, configuration: None, + pool_phase: PoolPhase::Populated, needs_fresh_backing: false, exit: None, owner: Some(owner), + released: false, retirement_ready: true, quarantined: false, active: Fifo { len: active }, + replays: Fifo { len: 0 }, previous: None, source_hint: SourceHint, source_readers: AtomicU32::new(0), + rearm_for: None, pool: Pool { id: u16::from(qid), client_vm: context.vm().id(), pages: Some(Pages(1)), cap: 16 }, + graph: Graph { ring: Some(DescriptorRing), m5: true }, + binding: Some(Binding { context: context.clone(), pool_alias: None, descriptors: None }), + release_sent_ns: None, free_list_generation: 1, released_at: 0, claims: 0, awaiting_witness: false, + channel_index: 0, sustained: true, + } +} +/// An idle queue whose owner released it at `released_at`; its pool still serves `vm`. +fn released(qid: u8, vm: u32, released_at: u64) -> Queue { + let mut queue = bound(qid, 0, &Context::new(1000 + u32::from(qid), vm), 0); + queue.owner = None; + queue.released = true; + queue.released_at = released_at; + queue.sustained = false; + queue +} +/// The same, after its pool was given back (the idle expiry): vacant, without a ring. +fn vacant(qid: u8, released_at: u64) -> Queue { + let mut queue = released(qid, 0, released_at); + queue.pool_phase = PoolPhase::Vacant; + queue.pool.pages = None; + queue.pool.client_vm = 0; + queue.graph.ring = None; + queue +} + +/// try_add_compute_sibling()'s locked decision and the off-lock re-arm, through the production +/// registry calls in the order the backend makes them. Returns whether a sibling was bound. +fn add_sibling(reg: &mut Registry, init: &InitData, owner: u64, context: &Arc) -> Result { + let req = ComputeCapacity(16); + if !reg.wants_compute_sibling(owner, context, 3, req) { + return Ok(false); + } + let Some(channel_index) = reg.next_sibling_index(owner, 3) else { return Ok(false) }; + match reg.sibling_source(owner, context, req) { + None => Ok(false), + Some(SiblingSource::Warm(_)) => Ok(reg.bind_reusable_sibling(owner, context, 3, req)? == Some(true)), + Some(SiblingSource::Foreign(qid)) => { reg.give_back_foreign(qid)?; Ok(false) } + Some(SiblingSource::Fresh) => Ok(false), + Some(SiblingSource::Vacant(qid)) => { + reg.reserve_rearm(qid, owner)?; + // Off the device mutex: fresh pages and a descriptor ring; then, locked again, the + // production rearm_vacant() checks and steps. + let ready = { + let queue = reg.queue(qid); + queue.can_rearm() && queue.rearm_open(owner) + } && reg.next_sibling_index(owner, 3) == Some(channel_index); + if !ready { + reg.release_rearm(qid, owner); + return Ok(false); + } + let (descriptor, _vacated) = reg.rearm_compute(qid, Pages(2), DescriptorRing)?; + assert_eq!(descriptor, PoolDescriptor(u32::from(qid)), "the re-armed queue's row is written"); + reg.bind_rearmed(qid, owner, context, channel_index)?; + Ok(true) + } + } +} + +fn registry() -> Registry { + Registry { compute: Vec::new(), qids: Qids { fit: false }, admission: Admission, teardown: Teardown { releasing: Vec::new() } } +} + +const B: u64 = 2; +const C: u64 = 3; +const D: u64 = 4; +const OTHER: u64 = 9; + +fn main() { +@@STRUCTURE@@ + + let init = InitData { control_cursor: std::cell::Cell::new(0) }; + let req = ComputeCapacity(16); + let b = Context::new(20, 200); + let c = Context::new(30, 300); + let d = Context::new(40, 400); + let mut reg = registry(); + // B's primary runs sustained heavy work with two kicks in flight. No fresh QID fits. + reg.push(bound(10, B, &b, 2)); + // An exited client's queues: one given back at the idle expiry (vacant), one still holding + // the exited VM's pool. + reg.push(vacant(11, 5)); + reg.push(released(12, 999, 6)); + // Never to be taken: C's busy queue, D's idle channel (D is open), a vacant queue another + // client is re-arming and a queue whose scheduler release is in flight. + reg.push(bound(13, C, &c, 1)); + reg.push(bound(14, D, &d, 0)); + let mut reserved = vacant(15, 1); + reserved.rearm_for = Some(OTHER); + reg.push(reserved); + reg.push(released(16, 998, 2)); + reg.teardown.releasing.push(1016); + let untouchable = [13u8, 14, 15, 16]; + assert!(reg.queue(14).shareable(), "D's idle channel is shareable, so only a primary may take it"); + assert!(!reg.queue(14).reusable()); + + // No lockout: the sibling comes from the vacant queue, re-armed and bound as channel 1. + assert!(reg.has_compute_sibling_headroom(B, &b, req), "vacant and other-VM queues are headroom"); + assert!(reg.wants_compute_sibling(B, &b, 3, req)); + assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(false)), "nothing warm to bind at once"); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(11))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(true)); + { + let q = reg.queue(11); + assert_eq!((q.owner, q.channel_index, q.pool_phase), (Some(B), 1, PoolPhase::Populated)); + assert!(q.has_ring() && !q.needs_fresh_backing() && q.rearm_for.is_none()); + } + assert_eq!(reg.compute_channels_of(B), (2, 0b11)); + + // The third channel. While a pool release is in flight (it ends in a vacant queue) no other + // VM's pool is given back, and the releasing queue itself is not taken. + reg.queue_mut(11).active.len = 1; + let mut releasing = released(17, 997, 3); + releasing.pool_phase = PoolPhase::ReleaseSent(u32::MAX); + reg.push(releasing); + assert!(!reg.queue(17).reusable() && reg.queue(17).vacancy_pending()); + assert_eq!(reg.sibling_source(B, &b, req), None); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(false)); + assert!(!reg.queue(12).needs_fresh_backing(), "nothing given back meanwhile"); + reg.compute.pop(); + // Then no vacant queue is left, so the exited VM's queue is given back. + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Foreign(12))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(false), "given back, not yet vacant"); + assert!(reg.queue(12).needs_fresh_backing() && reg.queue(12).vacancy_pending()); + assert!(!reg.queue(12).reusable(), "nobody binds its old pool meanwhile"); + // One give-back at a time: nothing else is offered while that release is pending. + assert_eq!(reg.sibling_source(B, &b, req), None); + assert!(!reg.wants_compute_sibling(B, &b, 3, req)); + // The pool pass releases it; once consumed the queue is vacant and is re-armed for B. + reg.pool_pass(&init); + assert_eq!(reg.queue(12).pool_phase, PoolPhase::Vacant); + assert!(reg.queue(12).pool_serves(b.vm()), "fresh backing serves any VM"); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(12))); + assert_eq!(add_sibling(&mut reg, &init, B, &b), Ok(true)); + assert_eq!((reg.queue(12).owner, reg.queue(12).channel_index), (Some(B), 2)); + assert_eq!(reg.compute_channels_of(B), (3, 0b111)); + assert!(!reg.wants_compute_sibling(B, &b, 3, req), "three channels at most"); + + // Nothing was stolen. + for qid in untouchable { + let q = reg.queue(qid); + assert_ne!(q.owner, Some(B), "queue {} was taken", qid); + assert!(!q.needs_fresh_backing(), "queue {} was given back", qid); + } + assert_eq!(reg.queue(13).owner, Some(C)); + assert_eq!(reg.queue(14).owner, Some(D)); + assert_eq!(reg.queue(15).rearm_for, Some(OTHER)); + + // Clients come and go: each new one gets its siblings back from what the last one left. + for round in 0..4u32 { + let vm = 500 + round; + let next = Context::new(50 + round, vm); + let owner = 100 + u64::from(round); + // The previous owner's channels (B's, then each round's) are released idle; their + // pools serve the exited VM. The newcomer's primary is one of them, rebound (modelled). + let mut freed: Vec = Vec::new(); + for entry in reg.compute.iter().flatten() { + let mut q = entry.queue.0.borrow_mut(); + if q.owner.is_some() && !untouchable.contains(&q.qid) { + q.owner = None; + q.released = true; + q.retirement_ready = true; + q.active.len = 0; + q.released_at = u64::from(round) * 10 + u64::from(q.qid); + freed.push(q.qid); + } + } + assert_eq!(freed.len(), 3, "round {}: three channels released", round); + let primary = freed[0]; + { + let mut q = reg.queue_mut(primary); + q.owner = Some(owner); + q.channel_index = 0; + q.released = false; + q.pool_phase = PoolPhase::Vacant; + q.pool.pages = Some(Pages(3)); + q.pool_phase = PoolPhase::Populated; + q.pool.client_vm = vm; + q.sustained = true; + q.active.len = 2; + } + let mut added = 0; + for _ in 0..8 { + if add_sibling(&mut reg, &init, owner, &next).unwrap() { + added += 1; + // Every bound channel stays busy. + for entry in reg.compute.iter().flatten() { + let mut q = entry.queue.0.borrow_mut(); + if q.owner == Some(owner) && q.active.len == 0 { + q.active.len = 1; + } + } + } else { + reg.pool_pass(&init); + } + } + assert_eq!(added, 2, "round {}: no lockout", round); + assert_eq!(reg.compute_channels_of(owner).0, 3); + for qid in untouchable { + assert_ne!(reg.queue(qid).owner, Some(owner)); + } + } + + // A fresh QID comes before another VM's pool is given back. + let mut reg = registry(); + reg.qids.fit = true; + reg.push(bound(10, B, &b, 2)); + reg.push(released(12, 999, 6)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Fresh)); + // A warm same-VM queue comes before a vacant one. + reg.push(vacant(11, 1)); + reg.push(released(18, 200, 9)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Warm(18))); + assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(true))); + assert_eq!(reg.queue(18).channel_index, 1); + // ... and a vacant one before a fresh QID; the longest released first. + reg.push(vacant(19, 0)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(19))); + + println!("PASS g17-m5-sibling-rearm: vacant and other-VM idle queues become siblings, nothing busy or open is taken"); +} +''' + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source = build(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-sibling-rearm-') as tmp: + path = Path(tmp) / 'rearm.rs' + binary = path.with_suffix('') + path.write_text(source) + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-O', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + sys.stderr.write(built.stderr) + return built.returncode + run = subprocess.run([str(binary)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-pool-release-tests.py b/tools/asahi/g17-pool-release-tests.py index 70004fe94ecf9..dd73e0a3e8977 100644 --- a/tools/asahi/g17-pool-release-tests.py +++ b/tools/asahi/g17-pool-release-tests.py @@ -31,7 +31,8 @@ def fixture(): predicate = '.any(|queue| queue.retirement_polling() || queue.pool_release_pending())' assert events.count(predicate) == 1 methods = '\n'.join(item(runtime, name) for name in [ - 'fn compute_admission_error(', 'pub(super) fn reserve_compute(']).replace('pub(super) ', '').replace('queue: ComputeSlot::new()?', 'queue: None') + 'fn compute_admission_error(', 'pub(super) fn reserve_compute(', + 'pub(super) fn reserve_compute_channel(']).replace('pub(super) ', '').replace('queue: ComputeSlot::new()?', 'queue: None') pending = item(compute, 'pub(crate) fn pool_release_pending(') + '\n' + \ item(compute, 'pub(crate) fn release_settling(') return r''' diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 7c51f27236a39..51c5972e1eab3 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -248,7 +248,8 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', 'crossed-behind-owed', 'owed-classified', 'rebind-check-entry', - 'timeout-fails-retired', 'no-owed-poll'), []), + 'timeout-fails-retired', 'no-owed-poll', 'count-recordless', + 'count-owed-twice'), []), 'g17-compute-deadline-tests.py': [([], PASS)], 'g17-compute-growth-deadline-tests.py': [([], PASS)], 'g17-kill-route-tests.py': [([], PASS)] @@ -272,6 +273,29 @@ def mutations(flag, names, base, expect=KILL): 'same-qid-emits-barrier', 'lock-has-published-epoch', 'lock-same-vm'), []), + 'g17-m5-sibling-compute-tests.py': [([], PASS)] + + mutations('--mutation', ('fixed-object-ids', 'primary-before-sibling', + 'exit-ack-stops-first', 'direct-allows-multi-barrier', + 'direct-blocks-sibling', 'direct-locks-sibling-when-idle', + 'direct-skips-multi', 'same-qid-pipelined'), []), + 'g17-m5-sibling-gate-tests.py': [([], PASS)] + + mutations('--mutation', ('sources-fan-out', 'select-sources-anywhere', 'tiny-fans-out', + 'no-sustain-run', 'short-keeps-run', 'direct-ignores-gate', + 'direct-can-add-ungated', 'wants-ignores-sustained', + 'select-ignores-sustained', 'cell-drops-sustained', + 'fans-out-locks-first', 'keep-run-across-owners', 'overlap-at-one', + 'direct-ignores-in-flight', 'select-ignores-in-flight', + 'wants-ignores-in-flight', 'detour-at-one'), []), + 'g17-m5-sibling-rearm-tests.py': [([], PASS)] + + mutations('--mutation', ('old-headroom', 'no-vacant-sibling', 'no-foreign-sibling', + 'steal-shareable', 'steal-unowned', 'ignore-rearm-reservation', + 'ignore-releasing', 'parallel-give-back', 'foreign-before-fresh', + 'rearm-binds-primary', 'try-add-ignores-waiters', 'try-add-skips-rearm', + 'rearm-any-index', 'primary-own-give-back'), []), + 'g17-compute-multi-channel-feature-tests.py': [([], PASS)] + + mutations('--mutation', ('always-multi', 'never-multi', 'not-reported', 'per-board-gate', + 'colliding-bit', 'unsynced-binding', 'forms-gate', + 'max-channels', 'multi-channel-max'), []), 'g17-firmware-selection-tests.py': [([], PASS)], 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], From e5c2f094869ec4a61a1b57f2a9255c3e5c1c25c5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 14:00:25 -0500 Subject: [PATCH 3/6] drm/asahi: g17: count render-pair demand for a fresh sibling compute QID sibling_source() offers a fresh QID for a sibling compute channel when the QID table has room beside render's reserve. It still sized that reserve by open logical queues, while reserve_compute_channel() now reserves against the admission's render-pair demand (open queues plus non-reclaimable siblings and held pairs), as rebind_compute() does. With siblings held the old check reported a fresh QID that the reservation then refused, so the sibling attempt ended without falling through to an idle other-VM queue. Check the same demand the reservation uses. The sibling host-test harnesses give their mock admission a render_demand() for the extracted sibling_source(). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/runtime.rs | 2 +- tools/asahi/g17-m5-sibling-compute-tests.py | 5 ++++- tools/asahi/g17-m5-sibling-gate-tests.py | 5 ++++- tools/asahi/g17-m5-sibling-rearm-tests.py | 9 ++++++--- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 81b8156bf89fb..a9d201ae4de28 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -445,7 +445,7 @@ impl Registry { if let Some((_, qid)) = vacant { return Some(SiblingSource::Vacant(qid)); } - if self.qids.compute_fits(self.admission.queues() as usize) { + if self.qids.compute_fits(self.admission.render_demand(0)) { return Some(SiblingSource::Fresh); } // A pool release in flight ends in a vacant queue; give back one at a time. diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py index 5042a66f7e917..894d87bffca89 100755 --- a/tools/asahi/g17-m5-sibling-compute-tests.py +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -414,7 +414,10 @@ def build_harness(mutation=None): }} struct Admission {{ queues: u32 }} -impl Admission {{ fn queues(&self) -> u32 {{ self.queues }} }} +impl Admission {{ + fn queues(&self) -> u32 {{ self.queues }} + fn render_demand(&self, extra: usize) -> usize {{ self.queues as usize + extra }} +}} struct Teardown {{ releasing_id: Option, render_acked: bool }} impl Teardown {{ diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py index b943c2a6d9c15..3068c820beb54 100755 --- a/tools/asahi/g17-m5-sibling-gate-tests.py +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -333,7 +333,10 @@ def build(mutation=None): struct Qids { fit: bool } impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } struct Admission; -impl Admission { fn queues(&self) -> u32 { 1 } } +impl Admission { + fn queues(&self) -> u32 { 1 } + fn render_demand(&self, extra: usize) -> usize { 1 + extra } +} struct Teardown; impl Teardown { fn releasing(&self, _: &Arc) -> bool { false } } struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index 6fbdd10e119d1..f690f4473cd17 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -131,9 +131,9 @@ def ordered_ok(source, *parts): ' foreign.map(', ' .any(|queue| queue.vacancy_pending() && false)\n {\n' ' return None;\n }\n foreign.map(')], # Give another VM's pool back while a fresh QID fits. - 'foreign-before-fresh': [('runtime', ' if self.qids.compute_fits(self.admission.queues() as usize) {\n' + 'foreign-before-fresh': [('runtime', ' if self.qids.compute_fits(self.admission.render_demand(0)) {\n' ' return Some(SiblingSource::Fresh);\n }\n // A pool release', - ' if foreign.is_none() && self.qids.compute_fits(self.admission.queues() as usize) {\n' + ' if foreign.is_none() && self.qids.compute_fits(self.admission.render_demand(0)) {\n' ' return Some(SiblingSource::Fresh);\n }\n // A pool release')], # A re-armed sibling is bound as the owner's primary. 'rearm-binds-primary': [('runtime', ' if channel_index == 0 {\n queue.bind_owner(owner, context.clone())', @@ -361,7 +361,10 @@ def build(mutation=None): struct Qids { fit: bool } impl Qids { fn compute_fits(&self, _: usize) -> bool { self.fit } } struct Admission; -impl Admission { fn queues(&self) -> u32 { 4 } } +impl Admission { + fn queues(&self) -> u32 { 4 } + fn render_demand(&self, extra: usize) -> usize { 4 + extra } +} struct Teardown { releasing: Vec } impl Teardown { fn releasing(&self, context: &Arc) -> bool { self.releasing.contains(&context.id) } } struct Registry { compute: Vec>, qids: Qids, admission: Admission, teardown: Teardown } From b15be7d699b0988b8e5989aeb1c67e69e696b6ba Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 05:24:27 -0500 Subject: [PATCH 4/6] drm/asahi: g17: wrap the submission state initializer to 100 columns Split the Submission::state initializer that "drm/asahi: g17: deduplicate sync-input chains and resolve M5 cross-QID sources directly" left at 111 columns, as checkpatch asks. No functional change. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/fence.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index 888202bed8d96..d47b4f2f88fd8 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -278,7 +278,10 @@ impl Submission { let vm_status = work.as_ref().map(|work| work.status().clone()); Arc::pin_init( pin_init!(Self { - state <- new_mutex!(State { work, ready: None, published: None }, "G17 submission work state"), + state <- new_mutex!( + State { work, ready: None, published: None }, + "G17 submission work state" + ), vm_status, remaining: AtomicU8::new(1), error: AtomicI32::new(0), From d60d7b9124022ee8c49ba2c533148cbcd108f3c5 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 05:26:09 -0500 Subject: [PATCH 5/6] drm/asahi: g17: wrap the sibling compute lines to 100 columns Split the nine lines that "drm/asahi: g17: fan M5 Pro compute out to sibling channels for sustained heavy kicks" left past 100 columns, as checkpatch asks, and follow the one that g17-compute-owed-stamp-tests.py matches in its retire-unchecked mutation. No functional change. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/queue/compute.rs | 7 +++++-- drivers/gpu/drm/asahi/g17/queue/render.rs | 10 ++++++---- drivers/gpu/drm/asahi/g17/runtime.rs | 11 ++++++++--- drivers/gpu/drm/asahi/g17/runtime/compute_control.rs | 6 +++++- drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs | 8 +++++++- tools/asahi/g17-compute-owed-stamp-tests.py | 3 ++- 6 files changed, 33 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 3658d8b0811a5..5b0eb70a6fec2 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -762,7 +762,8 @@ impl Queue { #[expect( clippy::too_many_arguments, - reason = "A sibling compute queue takes the same physical graph inputs plus its channel identity." + reason = "A sibling compute queue takes the same physical graph inputs plus its channel \ + identity." )] pub(crate) fn new_channel( alloc: &Allocator<'_>, @@ -2152,7 +2153,9 @@ impl Queue { /// A recycled vacant sibling queue whose descriptor ring still awaits off-lock release /// before re-arming with fresh backing. pub(crate) fn take_recycled_ring(&mut self) -> Option { - if !self.recycled_pending() || self.pool_phase != PoolPhase::Vacant || self.graph.ring.is_none() + if !self.recycled_pending() + || self.pool_phase != PoolPhase::Vacant + || self.graph.ring.is_none() { return None; } diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index a3692605b4851..2bf03c518a196 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -677,10 +677,12 @@ impl Pair { struct RenderBarriers { tiling: [KickDependency; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], tiling_count: usize, - fragment: [KickDependency; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], + fragment: [KickDependency; + 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], fragment_count: usize, tiling_types: [u8; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX], - fragment_types: [u8; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], + fragment_types: [u8; + 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS], } /// The last fragment kick published on any pair, and the last one of a render with an API task @@ -749,8 +751,8 @@ fn render_barriers( let fragment_stage = fragment_stage || stage_prefixes; let mut tiling_barriers = [KickDependency::ZERO; 4 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; let mut tiling_count = 0; - let mut fragment_barriers = - [own_tiling; 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; + let mut fragment_barriers = [own_tiling; + 3 + crate::g17::pairs::COMPUTE_CHANNELS_MAX + crate::g17::hazard::PUBLICATION_BARRIERS]; let mut fragment_count = 1; let mut tiling_types = [1; 5 + crate::g17::pairs::COMPUTE_CHANNELS_MAX]; let mut fragment_types = diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 3790372db1496..3c85e7d73750f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2569,8 +2569,9 @@ impl super::Firmware { } #[inline(never)] - fn publish_compute_inputs(&mut self, owner: u64, target_qid: u8, packet: Arc, - dependencies: &[super::fw::kick::KickDependency], deferred: &mut DeferredBatch) -> Result + fn publish_compute_inputs(&mut self, owner: u64, target_qid: u8, + packet: Arc, dependencies: &[super::fw::kick::KickDependency], + deferred: &mut DeferredBatch) -> Result { if self.recovery.pending() || super::recovery::Memory::recovery_state(&self.init)? != 0 { return Err(EAGAIN); @@ -3115,7 +3116,11 @@ impl Backend { /// [`compute::Queue::sustained`]). Every other command streams down the primary ring: short /// kicks run faster there than spread over several QIDs, and a semaphore hop between queues /// stays on one ring per queue. - fn fans_out(&self, packet: &super::job::Packet, primary_sustained: impl FnOnce() -> bool) -> bool { + fn fans_out( + &self, + packet: &super::job::Packet, + primary_sustained: impl FnOnce() -> bool, + ) -> bool { self.compute_channels > 1 && packet.order.wait_through[1].is_none() && packet.completion.sources().is_none() diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs index 4e0dfece644a6..881caee85111e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_control.rs @@ -79,7 +79,11 @@ impl Backend { return Ok(Decision::Own); } firmware.scan_compute(None, deferred)?; - if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) { + if !firmware + .queues + .compute_for_packet(self.owner, packet) + .is_some_and(|queue| queue.retired_held(packet)) + { return Ok(Decision::Own); } static REPORTED: AtomicU32 = AtomicU32::new(0); diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs index 55cd94b8b003f..f00e07a848eb0 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_replay.rs @@ -150,7 +150,13 @@ impl Firmware { require_visible, &mut dependencies, )?; - self.publish_compute_on(owner, Some(qid), packet.clone(), dependencies.as_slice(), deferred) + self.publish_compute_on( + owner, + Some(qid), + packet.clone(), + dependencies.as_slice(), + deferred, + ) })() }; let recovery_wait = matches!(result, Err(EAGAIN) | Err(EBUSY)) && (self.recovery.pending() diff --git a/tools/asahi/g17-compute-owed-stamp-tests.py b/tools/asahi/g17-compute-owed-stamp-tests.py index edca687c3989b..76165e3cbbcd9 100644 --- a/tools/asahi/g17-compute-owed-stamp-tests.py +++ b/tools/asahi/g17-compute-owed-stamp-tests.py @@ -733,7 +733,8 @@ def fixture(): MUTATIONS = { 'own-finished': [('_ if own.finished => Decision::Retire,', '_ if own.finished => Decision::Own,')], 'no-retire-glue': [('verdict.decision = self.retire_on_record(firmware, packet, &mut deferred)?;', '')], - 'retire-unchecked': [('if !firmware.queues.compute_for_packet(self.owner, packet).is_some_and(|queue| queue.retired_held(packet)) {', + 'retire-unchecked': [('if !firmware\n .queues\n .compute_for_packet(self.owner, packet)\n' + ' .is_some_and(|queue| queue.retired_held(packet))\n {', 'if false {')], 'no-expiry': [('if observed_at == Some(STAMP_WAIT_EXPIRED) {', 'if false {')], 'no-step-past': [('Ok(Some(_)) | Err(EAGAIN) if owed => at += 1,', 'Ok(Some(_)) | Err(EAGAIN) if owed => break,'), From df36284f753bcf69c83ca964d0ba84ae45438c79 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Wed, 25 Nov 2026 08:42:17 -0500 Subject: [PATCH 6/6] drm/asahi: g17: collect given-up compute channels without allocating under the lock rollback_unpublished_compute() and drain_compute_siblings() take compute queues out of the registry under the device mutex. The empty entry keeps the QID until finish_uninstalled_compute() drops the queue off-lock and cancels its reservation. Both collected the queues, and the rollback its displaced bindings, into empty KVecs while holding the mutex. A failed push dropped the queue or binding under the mutex and skipped the cancellation. The empty entry then stayed for good, and reserve_compute_channel() refused its owner with EINVAL from then on. The drain also lost the queues it had already taken when a later sibling was still busy (EAGAIN), and the rollback lost them when a later channel's rollback failed. An owner holds at most COMPUTE_CHANNELS_MAX channels, so collect into fixed per-channel arrays that the caller owns: nothing is allocated under the mutex, a channel is refused before it changes if it would have no place, and after a failure the caller still has everything taken before it. The caller drops the displaced bindings and finishes every taken queue after releasing the mutex, and goes on past a failed cancellation. The rollback loop moves into the registry beside the drain, so no early return can skip that. Also remove Registry::compute_mut(), which has no caller left in this series and was the driver's only g17 dead-code warning. The new g17-compute-retired-tests host test runs the production rollback, drain, finish and reservation code for an owner with all three channels, including a failing rollback, a busy sibling and a failing cancellation. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/runtime.rs | 90 +++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 44 +- .../g17-compute-growth-deadline-tests.py | 10 +- tools/asahi/g17-compute-retired-tests.py | 471 ++++++++++++++++++ tools/asahi/g17-m5-sibling-compute-tests.py | 15 +- tools/asahi/run-host-tests.py | 4 + 6 files changed, 576 insertions(+), 58 deletions(-) create mode 100755 tools/asahi/g17-compute-retired-tests.py diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 3c85e7d73750f..d88964fbcd92b 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -72,6 +72,16 @@ struct ComputeEntry { queue: ComputeSlot, } +/// A compute queue taken out of the registry under the device mutex. Its empty entry keeps the +/// reservation's QID until [`Backend::finish_uninstalled_compute`] drops the queue (and its +/// aliases) after that mutex is released and then cancels the reservation. +type Uninstalled = (ComputeReservation, KBox); + +/// One place per compute channel of an owner. An owner holds at most `COMPUTE_CHANNELS_MAX` +/// channels, so what its channels give up under the device mutex is kept here without +/// allocating there, and is dropped or finished only after that mutex is released. +type PerChannel = [Option; super::pairs::COMPUTE_CHANNELS_MAX]; + /// A physical compute queue behind its own lock. Publication into a bound queue takes only /// this lock; device-mutex holders take it to observe or change the queue (device mutex -> /// cell). A logical queue may keep the cell after the registry gave the queue up: the cell is @@ -343,10 +353,6 @@ impl Registry { .find(|queue| queue.owner() == Some(owner) && queue.is_primary()) } - pub(super) fn compute_mut(&mut self, owner: u64) -> Option> { - self.compute(owner) - } - pub(super) fn compute_for_packet( &self, owner: u64, @@ -1144,13 +1150,15 @@ impl Registry { } /// Releases idle sibling channels of `owner` before primary pool growth. Returns `Err(EAGAIN)` - /// while any sibling still has active, replaying or configuring work, and returns any - /// unpublished sibling queues for off-lock alias drop and QID cancellation. + /// while any sibling still has active, replaying or configuring work. Each unpublished + /// sibling queue goes to `retired`, which starts empty, for off-lock alias drop and QID + /// cancellation; on failure it still holds every queue taken before it. fn drain_compute_siblings( &mut self, owner: u64, - ) -> Result)>> { - let mut retired = KVec::new(); + retired: &mut PerChannel, + ) -> Result { + let mut channel = 0; for slot in 0..self.compute.len() { let is_sibling = self.compute[slot] .as_ref() @@ -1168,15 +1176,58 @@ impl Registry { if busy { return Err(EAGAIN); } + // Refuse before releasing a channel whose queue would have no place in `retired`. + let place = retired.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + channel += 1; let entry = self.compute[slot].as_mut().ok_or(EIO)?; let unpublished = entry.queue.as_deref_mut().ok_or(EIO)?.release_owner()?; if unpublished { - if let Some(queue) = entry.queue.take() { - retired.push((entry.reservation, queue), GFP_KERNEL)?; + *place = entry.queue.take().map(|queue| (entry.reservation, queue)); + } + } + Ok(()) + } + + /// Rolls back `owner`'s unpublished bindings to `context` on every channel, siblings before + /// the primary for deterministic teardown. Each displaced binding goes to `bindings` and each + /// cancelled queue to `retired`, both starting empty, for the caller to drop (and finish) + /// after releasing the device mutex; on failure they still hold everything taken before it. + fn rollback_unpublished_compute( + &mut self, + owner: u64, + context: &Arc, + retired: &mut PerChannel, + bindings: &mut PerChannel, + ) -> Result { + let mut channel = 0; + for primary_pass in [false, true] { + for slot in 0..self.compute.len() { + let matches = self.compute[slot] + .as_ref() + .and_then(|entry| entry.queue.as_deref()) + .is_some_and(|queue| { + queue.owner() == Some(owner) && queue.is_primary() == primary_pass + }); + if !matches { + continue; + } + // Refuse before rolling back a channel whose binding or queue would have no place. + let binding = bindings.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + let place = retired.get_mut(channel).filter(|place| place.is_none()).ok_or(EIO)?; + channel += 1; + let entry = self.compute[slot].as_mut().ok_or(EIO)?; + let (cancel, replaced) = entry + .queue + .as_deref_mut() + .ok_or(EIO)? + .rollback_unpublished(owner, context)?; + *binding = replaced; + if cancel { + *place = entry.queue.take().map(|queue| (entry.reservation, queue)); } } } - Ok(retired) + Ok(()) } pub(super) fn release_compute(&mut self, owner: u64) -> Result { @@ -1663,6 +1714,15 @@ impl Backend { Ok(()) } + /// Finishes every queue in `retired` as [`Self::finish_uninstalled_compute`] finishes one, + /// going on past a failure so no other reservation stays behind; returns the first failure. + fn finish_retired_compute(&self, retired: &mut PerChannel) -> Result { + retired.iter_mut().fold(Ok(()), |result, item| { + let finished = self.finish_uninstalled_compute(item.take()); + result.and(finished) + }) + } + fn grow_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; { @@ -1694,7 +1754,7 @@ impl Backend { // Growth waits for this queue's retirement and for firmware to consume the pool // release; both are progress the event worker reports. let observed = self.shared.progress.observe(); - let mut retired_siblings = KVec::new(); + let mut retired_siblings: PerChannel = Default::default(); let result = (|| { let mut state = self.shared.state.lock(); admission.check()?; @@ -1704,7 +1764,7 @@ impl Backend { firmware.scan_compute(None, &mut deferred)?; // Release sibling channels before growing the primary channel so undersized // sibling pools are detached and later re-acquired at the grown capacity. - retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?; + firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?; let mut queue = firmware.queues.compute_primary(self.owner).ok_or(EAGAIN)?; if queue.pool_fits(required) { return Ok(None); } if growth.is_none() { @@ -1719,9 +1779,7 @@ impl Backend { } queue.finish_growth(&firmware.init, &mut pages, &mut alias).map(Some) })(); - for item in retired_siblings { - self.finish_uninstalled_compute(Some(item))?; - } + self.finish_retired_compute(&mut retired_siblings)?; deferred.finish(); match result { Ok(old) => { drop(old); return Ok(()); } diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index ff0f4e897123d..b3f54f9f45060 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -2,10 +2,11 @@ //! Scheduler callbacks and the off-lock fence boundary of a logical queue. -use super::{Backend, DeferredBatch}; +use super::{Backend, DeferredBatch, PerChannel, Uninstalled}; use crate::g17::{ completion::Deferred, job::{self, Engine, Packet}, + queue::compute::Binding, }; use core::sync::atomic::Ordering; use kernel::{dma_fence::{Fence, RawDmaFence}, drm::sched, prelude::*, sync::Arc}; @@ -35,47 +36,20 @@ impl Backend { // fresh epoch through alias destruction so recovery can join this work. loop { let lease = self.shared.preparations.enter(false)?; - let mut retired = KVec::new(); - let mut bindings = KVec::new(); + let mut retired: PerChannel = Default::default(); + let mut bindings: PerChannel = Default::default(); let mut state = self.shared.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; if !lease.is_current() { drop(state); drop(lease); continue; } - // Roll back sibling channels before the primary channel for deterministic teardown. - for primary_pass in [false, true] { - for index in 0..firmware.queues.compute.len() { - let matches = firmware.queues.compute[index] - .as_ref() - .and_then(|entry| entry.queue.as_deref()) - .is_some_and(|queue| { - queue.owner() == Some(self.owner) && queue.is_primary() == primary_pass - }); - if !matches { - continue; - } - let entry = firmware.queues.compute[index].as_mut().ok_or(EIO)?; - let (cancel, replaced) = entry - .queue - .as_deref_mut() - .ok_or(EIO)? - .rollback_unpublished(self.owner, &self.context)?; - if let Some(replaced) = replaced { - let _ = bindings.push(replaced, GFP_KERNEL); - } - if cancel { - if let Some(queue) = entry.queue.take() { - let _ = retired.push((entry.reservation, queue), GFP_KERNEL); - } - } - } - } + let result = firmware.queues.rollback_unpublished_compute( + self.owner, &self.context, &mut retired, &mut bindings); drop(state); + // Off-lock, and after a failure too: no cancelled queue's reservation stays behind. drop(bindings); - for item in retired { - self.finish_uninstalled_compute(Some(item))?; - } + let finished = self.finish_retired_compute(&mut retired); self.shared.channels.notify(); self.shared.queue_events(); - return Ok(()); + return result.and(finished); } } diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index d79d784b7578f..7ed4ca5c95277 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -32,7 +32,11 @@ def fixture(): admission = ('#[derive(Clone,Copy,Debug,PartialEq)]\n' + item(prep, 'pub(super) enum AdmissionWait').replace('pub(super) ', '') + '\n' + next(line for line in prep.splitlines() if 'const ADMISSION_WAITS:' in line).replace('pub(super) ', '') + '\n' + admission) - methods = '\n'.join(item(runtime, sig) for sig in [' fn grow_compute(', ' fn finish_uninstalled_compute(']) + methods = '\n'.join(item(runtime, sig) for sig in [' fn grow_compute(', ' fn finish_uninstalled_compute(', + ' fn finish_retired_compute(']) + # The per-channel places growth hands drained siblings over in. + aliases = '\n'.join(next(line for line in runtime.splitlines() if line.startswith(prefix)) + for prefix in ('type Uninstalled =', 'type PerChannel =')).replace('super::pairs::', '') methods = (methods.replace('super::object::Allocator', 'Allocator').replace('super::freelist::Pages', 'Pages') .replace('super::freelist::ComputeCapacity', 'ComputeCapacity')) return r''' @@ -75,6 +79,8 @@ def fixture(): impl Drop for Pages{fn drop(&mut self){PAGES.store(false,Ordering::SeqCst);}} impl Drop for Alias{fn drop(&mut self){ALIAS.store(false,Ordering::SeqCst);}} mod compute{pub(crate) use crate::Queue;} +const COMPUTE_CHANNELS_MAX:usize=3; +''' + aliases + r''' struct Queue{fresh:bool} impl Queue{ fn owner(&self)->Option{Some(1)} @@ -92,7 +98,7 @@ def fixture(): fn compute(&self,_:u64)->Option<&Queue>{self.compute[0].as_ref().unwrap().queue.as_deref()} fn compute_mut(&mut self,_:u64)->Option<&mut Queue>{self.compute[0].as_mut().unwrap().queue.as_deref_mut()} fn compute_primary(&mut self,owner:u64)->Option<&mut Queue>{self.compute_mut(owner)} - fn drain_compute_siblings(&mut self,_:u64)->Result)>>{Ok(Vec::new())} + fn drain_compute_siblings(&mut self,_:u64,_:&mut PerChannel)->Result{Ok(())} fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} } struct Primary;impl Primary{fn notify(&self,_:u32)->Result{Ok(())}} diff --git a/tools/asahi/g17-compute-retired-tests.py b/tools/asahi/g17-compute-retired-tests.py new file mode 100755 index 0000000000000..900fdee4c47b4 --- /dev/null +++ b/tools/asahi/g17-compute-retired-tests.py @@ -0,0 +1,471 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: compute channels given up under the device mutex never leak a reservation. + +A logical compute queue holds up to `COMPUTE_CHANNELS_MAX` channels. When an +unpublished compute packet fails, `Backend::rollback_unpublished_compute()` +rolls back every channel of the owner, and before primary pool growth +`Registry::drain_compute_siblings()` releases every idle sibling. Both take +queues out of the registry under the device mutex. Each taken queue keeps an +empty registry entry, and so its QID, until it is dropped off-lock and its +reservation is cancelled (`finish_uninstalled_compute()`). An entry left empty +for good locks its owner out: `reserve_compute_channel()` refuses that owner +with `EINVAL`. + +This test compiles, against host stubs, the production code from +drivers/gpu/drm/asahi/g17/runtime.rs (`Registry::drain_compute_siblings()`, +`Registry::rollback_unpublished_compute()`, `Registry::reserve_compute_channel()`, +`Registry::reserved()`, `Registry::cancel_compute()`, +`Backend::finish_uninstalled_compute()`, `Backend::finish_retired_compute()`) +and from runtime/backend.rs (`Backend::rollback_unpublished_compute()`). It +checks, for an owner with all `COMPUTE_CHANNELS_MAX` channels, that: + +- nothing a channel gives up (queue or displaced binding) is dropped while the + device mutex is held; +- every cancelled or drained queue has its reservation cancelled, so the owner + can reserve channels again; +- this also holds when a later channel fails its rollback or is still busy in + the drain (`EAGAIN`), and when finishing one queue fails; +- an owner with more channels than places is refused before any extra channel + changes. + +Each mutation drops one part of that and must fail an assertion. +""" +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 line(source, prefix): + found = [text for text in source.splitlines() if text.startswith(prefix)] + assert len(found) == 1, prefix + return found[0] + + +def replace_once(text, old, new): + assert text.count(old) == 1, old + return text.replace(old, new) + + +def build_harness(mutation=None): + runtime = (G17 / 'runtime.rs').read_text() + backend = (G17 / 'runtime/backend.rs').read_text() + max_line = line((G17 / 'pairs.rs').read_text(), 'pub(crate) const COMPUTE_CHANNELS_MAX: usize') + + aliases = '\n'.join([ + line(runtime, 'type Uninstalled ='), + line(runtime, 'type PerChannel ='), + ]).replace('super::pairs::', '') + drain = item(runtime, ' fn drain_compute_siblings(') + rollback = item(runtime, ' fn rollback_unpublished_compute(\n') + reserve = item(runtime, ' pub(super) fn reserve_compute_channel(') + reserved = item(runtime, ' fn reserved(&mut self, reservation: ComputeReservation)') + cancel = item(runtime, ' pub(super) fn cancel_compute(') + finish_one = item(runtime, ' fn finish_uninstalled_compute(') + finish_all = item(runtime, ' fn finish_retired_compute(') + backend_rollback = item(backend, ' fn rollback_unpublished_compute(&self)') + + if mutation == 'queue-under-lock': + # A cancelled queue is dropped where it is taken, as when a push into an empty KVec failed. + rollback = replace_once(rollback, + '*place = entry.queue.take().map(|queue| (entry.reservation, queue));', + 'drop(entry.queue.take());') + elif mutation == 'binding-under-lock': + rollback = replace_once(rollback, '*binding = replaced;', 'drop(replaced);') + elif mutation == 'drain-under-lock': + drain = replace_once(drain, + '*place = entry.queue.take().map(|queue| (entry.reservation, queue));', + 'drop(entry.queue.take());') + elif mutation == 'drain-local-on-eagain': + # The old shape: collect locally and hand the queues over only on success. + drain = replace_once(drain, 'retired: &mut PerChannel,', 'outer: &mut PerChannel,') + drain = replace_once(drain, ' let mut channel = 0;\n', + ' let mut local: PerChannel = Default::default();\n' + ' let retired = &mut local;\n' + ' let mut channel = 0;\n') + drain = drain[:drain.rindex('Ok(())')] + 'core::mem::swap(outer, retired);\n Ok(())\n }' + elif mutation == 'finish-stops-at-error': + finish_all = ( + ' fn finish_retired_compute(&self, retired: &mut PerChannel) -> Result {\n' + ' for item in retired.iter_mut() {\n' + ' self.finish_uninstalled_compute(item.take())?;\n' + ' }\n' + ' Ok(())\n' + ' }') + elif mutation == 'early-return-skips-finish': + backend_rollback = replace_once(backend_rollback, 'let result = firmware.queues', 'let result: Result = Ok(()); firmware.queues') + backend_rollback = replace_once(backend_rollback, '&mut retired, &mut bindings);', '&mut retired, &mut bindings)?;') + elif mutation == 'overwrite-full': + rollback = replace_once(rollback, 'bindings.get_mut(channel)', 'bindings.get_mut(channel % COMPUTE_CHANNELS_MAX)') + rollback = replace_once(rollback, 'retired.get_mut(channel).filter(|place| place.is_none())', + 'retired.get_mut(channel % COMPUTE_CHANNELS_MAX)') + + reserve = reserve.replace('crate::g17::capacity::', 'capacity::') + reserve, cancel = (text.replace('pub(super) ', '') for text in (reserve, cancel)) + + return r''' +#![allow(dead_code)] +use std::cell::{Cell, RefCell, RefMut}; +use std::ops::{Deref, DerefMut}; +use std::sync::Arc; + +type Error = i32; +type Result = core::result::Result; +type KBox = Box; +type KVec = Vec; +const EIO: Error = -5; +const ENODEV: Error = -19; +const EINVAL: Error = -22; +const EAGAIN: Error = -11; +const ENOSPC: Error = -28; +const FIRST_COMPUTE_QID: u8 = 8; +''' + max_line.replace('pub(crate) ', '') + r''' + +thread_local! { + static LOCKED: Cell = const { Cell::new(false) }; + static LOG: RefCell> = const { RefCell::new(Vec::new()) }; +} +fn locked() -> bool { LOCKED.with(Cell::get) } +fn log(text: String) { LOG.with(|log| log.borrow_mut().push(text)); } +fn take_log() -> Vec { LOG.with(|log| core::mem::take(&mut *log.borrow_mut())) } + +mod capacity { + pub(super) enum Site { ComputeSlots } + pub(super) fn refused(_: Site) -> i32 { super::ENOSPC } +} + +#[derive(Clone, Copy, PartialEq, Debug)] +struct Id { qid: u8, generation: u32 } +impl Id { fn qid(&self) -> u8 { self.qid } } +#[derive(Clone, Copy)] +enum DataMaster { Compute } + +struct Context; + +/// A displaced binding: its aliases must be torn down off the device mutex. +struct Binding(u8); +impl Drop for Binding { + fn drop(&mut self) { + assert!(!locked(), "binding of qid {} dropped under the device mutex", self.0); + log(format!("binding {}", self.0)); + } +} +mod compute { pub(super) use super::{Binding, Queue}; } + +#[derive(Clone, Copy, PartialEq)] +enum Rollback { Cancel, Displace, Keep, Fail } + +struct Queue { + qid: u8, + owner: Option, + primary: bool, + active: u32, + rollback: Rollback, + unpublished: bool, +} +impl Queue { + fn owner(&self) -> Option { self.owner } + fn is_primary(&self) -> bool { self.primary } + fn active_len(&self) -> u32 { self.active } + fn has_replays(&self) -> bool { false } + fn configuring(&self) -> bool { false } + fn release_owner(&mut self) -> Result { + self.owner = None; + Ok(self.unpublished) + } + fn rollback_unpublished(&mut self, owner: u64, _: &Arc) -> Result<(bool, Option)> { + assert_eq!(self.owner, Some(owner)); + log(format!("rollback {}", self.qid)); + match self.rollback { + Rollback::Cancel => { self.owner = None; Ok((true, None)) } + Rollback::Displace => Ok((false, Some(Binding(self.qid)))), + Rollback::Keep => Ok((false, None)), + Rollback::Fail => Err(EIO), + } + } +} +impl Drop for Queue { + fn drop(&mut self) { + assert!(!locked(), "queue {} dropped under the device mutex", self.qid); + log(format!("drop {}", self.qid)); + } +} + +/// Stands in for the cell-locked slot: a guard for the installed queue, or none. +struct ComputeSlot(RefCell>>); +impl ComputeSlot { + fn new() -> Result { Ok(Self(RefCell::new(None))) } + fn with(queue: Queue) -> Self { Self(RefCell::new(Some(Box::new(queue)))) } + fn as_deref(&self) -> Option> { + RefMut::filter_map(self.0.borrow_mut(), |queue| queue.as_deref_mut()).ok() + } + fn as_deref_mut(&mut self) -> Option> { self.as_deref() } + fn is_some(&self) -> bool { self.0.borrow().is_some() } + fn is_none(&self) -> bool { !self.is_some() } + fn take(&mut self) -> Option> { self.0.borrow_mut().take() } +} + +#[derive(Clone, Copy)] +struct ComputeReservation { slot: usize, id: Id, owner: u64 } +struct ComputeEntry { reservation: ComputeReservation, queue: ComputeSlot } +''' + aliases + r''' + +struct Identities(u64); +impl Identities { + fn reserve(&mut self, count: u64) -> Result> { + let start = self.0; + self.0 += count; + Ok(start..self.0) + } +} +struct Qids { next: u8, cancelled: Vec, refuse: Option } +impl Qids { + fn reserve_for(&mut self, _: u64, _: DataMaster, _: Option, _: usize) -> Result { + self.next += 1; + Ok(Id { qid: self.next, generation: 1 }) + } + fn render_pair_fits(&self) -> bool { true } + fn render_pair_capacity(&self) -> usize { 4 } + fn cancel_unpublished(&mut self, id: Id) -> Result { + if self.refuse == Some(id.qid) { return Err(EIO); } + self.cancelled.push(id.qid); + Ok(()) + } +} +struct Admission; +impl Admission { + fn reserve_compute_with_budget( + &self, _: u64, _: u64, reserve: impl FnOnce(usize) -> Result<(T, bool, usize)>, + ) -> Result { + reserve(0).map(|(id, _, _)| id) + } +} + +struct Registry { + compute: KVec>, + identities: Identities, + qids: Qids, + admission: Admission, +} +impl Registry { + fn reclaimable_render_slots(&self) -> Result<(u64, u64)> { Ok((0, 0)) } + fn compute_admission_error(&self, error: Error) -> Error { + if error == ENOSPC { EAGAIN } else { error } + } + fn note_build_room(&mut self) {} +''' + '\n'.join([drain, rollback, reserve, reserved, cancel]) + r''' +} + +struct Firmware { queues: Registry } +struct Guard<'a>(RefMut<'a, Option>>); +impl Deref for Guard<'_> { + type Target = Option>; + fn deref(&self) -> &Self::Target { &self.0 } +} +impl DerefMut for Guard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } +} +impl Drop for Guard<'_> { + fn drop(&mut self) { LOCKED.with(|locked| locked.set(false)); } +} +struct State(RefCell>>); +impl State { + fn lock(&self) -> Guard<'_> { + assert!(!locked(), "device mutex taken twice"); + LOCKED.with(|locked| locked.set(true)); + Guard(self.0.borrow_mut()) + } +} +struct Lease; +impl Lease { fn is_current(&self) -> bool { true } } +struct Preparations; +impl Preparations { fn enter(&self, _: bool) -> Result { Ok(Lease) } } +struct Channels(Cell); +impl Channels { fn notify(&self) { self.0.set(self.0.get() + 1); } } +struct Shared { preparations: Preparations, state: State, channels: Channels } +impl Shared { fn queue_events(&self) {} } +struct Backend { owner: u64, context: Arc, shared: Shared } +impl Backend { +''' + '\n'.join([finish_one, finish_all, backend_rollback]) + r''' +} + +const OWNER: u64 = 1; + +/// The owner's channels in slots 0..: primary first, then siblings; slot `free` stays empty. +fn backend(channels: &[(Rollback, u32, bool)]) -> Backend { + let mut compute: KVec> = Vec::new(); + for (slot, &(rollback, active, unpublished)) in channels.iter().enumerate() { + let qid = 10 + slot as u8; + compute.push(Some(ComputeEntry { + reservation: ComputeReservation { slot, id: Id { qid, generation: 1 }, owner: OWNER }, + queue: ComputeSlot::with(Queue { + qid, owner: Some(OWNER), primary: slot == 0, active, rollback, unpublished, + }), + })); + } + for _ in 0..4 { + compute.push(None); + } + let queues = Registry { + compute, + identities: Identities(100), + qids: Qids { next: 40, cancelled: Vec::new(), refuse: None }, + admission: Admission, + }; + Backend { + owner: OWNER, + context: Arc::new(Context), + shared: Shared { + preparations: Preparations, + state: State(RefCell::new(Some(Box::new(Firmware { queues })))), + channels: Channels(Cell::new(0)), + }, + } +} + +fn installed(b: &Backend) -> Vec { + let state = b.shared.state.0.borrow(); + let queues = &state.as_ref().unwrap().queues; + queues.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref().map(|queue| queue.qid)).collect() +} + +fn empty_entries(b: &Backend) -> usize { + let state = b.shared.state.0.borrow(); + state.as_ref().unwrap().queues.compute.iter().flatten().filter(|entry| entry.queue.is_none()).count() +} + +fn cancelled(b: &Backend) -> Vec { + b.shared.state.0.borrow().as_ref().unwrap().queues.qids.cancelled.clone() +} + +/// The owner is not locked out: the production reservation grants it a channel again. +fn reserves_again(b: &Backend) { + let mut state = b.shared.state.0.borrow_mut(); + let queues = &mut state.as_mut().unwrap().queues; + let reservation = queues.reserve_compute_channel(OWNER, COMPUTE_CHANNELS_MAX as u8); + assert!(reservation.is_ok(), "owner locked out of reserve_compute_channel: {:?}", reservation.err()); + queues.cancel_compute(reservation.unwrap()).unwrap(); +} + +fn drain(b: &Backend) -> Result { + let mut retired: PerChannel = Default::default(); + let result = { + let mut state = b.shared.state.lock(); + let firmware = state.as_deref_mut().unwrap(); + firmware.queues.drain_compute_siblings(OWNER, &mut retired) + }; + let finished = b.finish_retired_compute(&mut retired); + assert!(retired.iter().all(Option::is_none), "drained queue left unfinished"); + result.and(finished) +} + +fn main() { + use Rollback::*; + assert_eq!(COMPUTE_CHANNELS_MAX, 3, "this test models three channels per owner"); + + // 1. Rollback cancels all three channels: siblings first, every reservation cancelled. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + b.rollback_unpublished_compute().unwrap(); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "drop 11", "drop 12", "drop 10"]); + assert_eq!(cancelled(&b), [11, 12, 10]); + assert!(installed(&b).is_empty() && empty_entries(&b) == 0, "rolled-back channel left in the registry"); + reserves_again(&b); + + // 2. Displaced bindings on all three channels are dropped off-lock; the queues stay. + let b = backend(&[(Displace, 0, false), (Displace, 0, false), (Displace, 0, false)]); + b.rollback_unpublished_compute().unwrap(); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "binding 11", "binding 12", "binding 10"]); + assert_eq!(installed(&b), [10, 11, 12]); + assert!(cancelled(&b).is_empty()); + + // 3. A later channel fails its rollback: the channels taken before it are still finished. + let b = backend(&[(Keep, 0, false), (Cancel, 0, false), (Fail, 0, false)]); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "drop 11"]); + assert_eq!(cancelled(&b), [11]); + assert_eq!(installed(&b), [10, 12]); + assert_eq!(empty_entries(&b), 0, "a failed rollback left an empty entry holding its QID"); + + // 4. The drain releases both idle siblings and finishes both; the primary stays. + let b = backend(&[(Keep, 0, true), (Keep, 0, true), (Keep, 0, true)]); + drain(&b).unwrap(); + assert_eq!(take_log(), ["drop 11", "drop 12"]); + assert_eq!(cancelled(&b), [11, 12]); + assert_eq!(installed(&b), [10]); + assert_eq!(empty_entries(&b), 0); + reserves_again(&b); + + // 5. A busy later sibling stops the drain (EAGAIN), and the sibling taken before it is + // still finished, so the owner is not locked out. + let b = backend(&[(Keep, 0, true), (Keep, 0, true), (Keep, 1, true)]); + assert_eq!(drain(&b), Err(EAGAIN)); + assert_eq!(take_log(), ["drop 11"]); + assert_eq!(cancelled(&b), [11]); + assert_eq!(installed(&b), [10, 12]); + assert_eq!(empty_entries(&b), 0, "EAGAIN left a drained sibling's entry empty"); + reserves_again(&b); + + // 6. Finishing goes on past a failed cancellation: the others' reservations still go. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + b.shared.state.0.borrow_mut().as_mut().unwrap().queues.qids.refuse = Some(11); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 10", "drop 11", "drop 12", "drop 10"]); + assert_eq!(cancelled(&b), [12, 10], "a failed cancellation stopped the others"); + + // 7. More channels than places (beyond the per-owner bound): refused before the extra + // channel changes; the three taken are finished and the extra one stays installed. + let b = backend(&[(Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false), (Cancel, 0, false)]); + assert_eq!(b.rollback_unpublished_compute(), Err(EIO)); + assert_eq!(take_log(), ["rollback 11", "rollback 12", "rollback 13", "drop 11", "drop 12", "drop 13"]); + assert_eq!(cancelled(&b), [11, 12, 13]); + assert_eq!(installed(&b), [10]); + assert_eq!(empty_entries(&b), 0); + + println!("PASS g17-compute-retired: no reservation leaks across rollback and sibling drain"); +} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=[ + 'queue-under-lock', 'binding-under-lock', 'drain-under-lock', 'drain-local-on-eagain', + 'finish-stops-at-error', 'early-return-skips-finish', 'overwrite-full', + ]) + args = parser.parse_args() + source = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-retired-') as tmp: + rs = Path(tmp) / 'test.rs' + exe = Path(tmp) / 'test' + rs.write_text(source) + build = subprocess.run([rustc, '--edition=2021', '-O', str(rs), '-o', str(exe)], + capture_output=True, text=True) + if build.returncode != 0: + sys.stderr.write(build.stderr) + return build.returncode + run = subprocess.run([str(exe)], capture_output=True, text=True) + sys.stdout.write(run.stdout) + sys.stderr.write(run.stderr) + return run.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py index 894d87bffca89..84f2ce51675aa 100755 --- a/tools/asahi/g17-m5-sibling-compute-tests.py +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -92,7 +92,8 @@ def build_harness(mutation=None): release_fn = item(runtime_src, 'pub(super) fn release_compute(') ack_exit_fn = item(exit_src, 'pub(super) fn acknowledge_compute_exit(') pub_exit_fn = item(exit_src, 'fn publish_compute_exit(') - rollback_fn = item(backend_src, 'fn rollback_unpublished_compute(') + rollback_fn = item(runtime_src, 'fn rollback_unpublished_compute(\n') + backend_rollback_fn = item(backend_src, 'fn rollback_unpublished_compute(&self)') grow_fn = item(runtime_src, 'fn grow_compute(') drain_sib_fn = item(runtime_src, 'fn drain_compute_siblings(') direct_fn = item(runtime_src, 'fn compute_direct(') @@ -203,7 +204,12 @@ def build_harness(mutation=None): rollback_fn, 'for primary_pass in [false, true]', 'queue.is_primary() == primary_pass', - '.rollback_unpublished(self.owner, &self.context)?', + '.rollback_unpublished(owner, context)?', + ) and ordered_ok( + backend_rollback_fn, + 'firmware.queues.rollback_unpublished_compute(', + 'drop(state);', + 'self.finish_retired_compute(&mut retired)', ) grow_releases_siblings_ok = ( ordered_ok( @@ -216,10 +222,9 @@ def build_harness(mutation=None): ) and ordered_ok( grow_fn, - 'retired_siblings = firmware.queues.drain_compute_siblings(self.owner)?;', + 'firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?;', 'firmware.queues.compute_primary(self.owner)', - 'for item in retired_siblings {', - 'self.finish_uninstalled_compute(Some(item))?;', + 'self.finish_retired_compute(&mut retired_siblings)?;', ) ) exit_propagates_ok = ordered_ok( diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 055db828b15f1..e9d4592d9ed7b 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -271,6 +271,10 @@ def mutations(flag, names, base, expect=KILL): 'count-owed-twice'), []), 'g17-compute-deadline-tests.py': [([], PASS)], 'g17-compute-growth-deadline-tests.py': [([], PASS)], + 'g17-compute-retired-tests.py': [([], PASS)] + + mutations('--mutation', ('queue-under-lock', 'binding-under-lock', 'drain-under-lock', + 'drain-local-on-eagain', 'finish-stops-at-error', + 'early-return-skips-finish', 'overwrite-full'), []), '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'), []),