From 10f3766eb5044ae80b630a18ab987fa99aa67d9c Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 07:06:29 -0500 Subject: [PATCH 1/3] drm/asahi: g17: lockless fence status, published-source coalescing, and G17P direct compute sources Cut kernel CPU and device-mutex overhead on cross-queue GPU fence handoffs across G17P and M5: 1. Lockless fence status (asahi_g17_fence_status): query dma_fence_is_signaled() followed by smp_rmb() and READ_ONCE(fence->error) instead of taking fence->lock with IRQs disabled via dma_fence_get_status() on every input fence, scope node, and collected leaf. Also check sources.contains_input() before re-querying fence_status() in Queue::enqueue(), and back collect_coalesced() with a 4-leaf inline stack buffer to avoid per-submit heap allocations on the common path. 2. Published-source coalescing: ExportFence intentionally keeps an independent dma_fence context so out-of-order early failures cannot violate core dma_fence monotonicity. Record the packed (qid, published_seq) atomically on Submission alongside published_epoch and coalesce healthy unsignalled published ExportFences sharing (epoch, qid) in both collect_leaf() and Backend::input_sources() to the latest publication ordinal, leaving failed, unpublished, cross-epoch, and cross-QID leaves intact. 3. G17P direct compute submission with input sources: record immutable stamp_va and monotonic exec_share identity on PublishedSource so resolve_direct_sources(), compute_direct(), and compute_readiness() handle same-VM compute sources without taking the device mutex on G17P as well as M5 (using kick barriers for same-execution-context G17P sources and NativeWait records via publish_with_native_waits() for cross-context sources, while skipping duplicate self-QID barriers). Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/context.rs | 4 + drivers/gpu/drm/asahi/g17/exec_share.rs | 15 ++ drivers/gpu/drm/asahi/g17/fence.rs | 177 +++++++++++++++++++ drivers/gpu/drm/asahi/g17/job.rs | 3 +- drivers/gpu/drm/asahi/g17/queue/compute.rs | 2 + drivers/gpu/drm/asahi/g17/queue/mod.rs | 12 +- drivers/gpu/drm/asahi/g17/runtime.rs | 97 +++++++--- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 24 ++- drivers/gpu/drm/asahi/g17/sync_input.c | 46 ++++- drivers/gpu/drm/asahi/g17/sync_input.h | 2 + drivers/gpu/drm/asahi/g17/sync_input.rs | 70 +++++++- tools/asahi/g17-m5-cross-qid-direct-tests.py | 177 ++++++++++++++++--- tools/asahi/g17-m5-sibling-gate-tests.py | 8 +- 13 files changed, 559 insertions(+), 78 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index d5b2e15224741..1d409d2879645 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -494,6 +494,10 @@ impl Context { None => self.execution.release(), } } + /// Non-zero identity shared by contexts in the same `exec_share`, or `0` when unshared. + pub(crate) fn execution_share_id(&self) -> u64 { + self.share.as_ref().map_or(0, |share| share.id()) + } /// `other` runs in this context's shared execution context. pub(crate) fn shares_execution(&self, other: &Context) -> bool { self.share.is_some() && core::ptr::eq(&*self.execution, &*other.execution) diff --git a/drivers/gpu/drm/asahi/g17/exec_share.rs b/drivers/gpu/drm/asahi/g17/exec_share.rs index 68b858e0ff18b..8a1a8bea6323a 100644 --- a/drivers/gpu/drm/asahi/g17/exec_share.rs +++ b/drivers/gpu/drm/asahi/g17/exec_share.rs @@ -18,12 +18,15 @@ use core::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use kernel::{prelude::*, sync::Arc}; struct Entry { + id: u64, vm: u64, execution: Arc, claims: Arc, users: u32, } +static NEXT_SHARE_ID: AtomicU64 = AtomicU64::new(1); + kernel::sync::global_lock! { // SAFETY: Module initialization initializes this lock before registering adapters. unsafe(uninit) static SHARES: Mutex> = KVec::new(); @@ -39,6 +42,7 @@ pub(crate) unsafe fn init() { /// One logical queue's use of a shared execution context. pub(crate) struct Use { + id: u64, vm: u64, execution: Arc, claims: Arc, @@ -46,6 +50,10 @@ pub(crate) struct Use { } impl Use { + /// Non-zero identity shared by every logical queue in this execution context. + pub(crate) fn id(&self) -> u64 { + self.id + } /// The work-state index claims of the sharers. pub(crate) fn claims(&self) -> &Arc { &self.claims @@ -93,6 +101,7 @@ pub(crate) fn join(vm: &Vm) -> Option<(Arc, Use)> { Some(( entry.execution.clone(), Use { + id: entry.id, vm: entry.vm, execution: entry.execution.clone(), claims: entry.claims.clone(), @@ -104,9 +113,14 @@ pub(crate) fn join(vm: &Vm) -> Option<(Arc, Use)> { /// Offers a new context of `vm` for sharing. pub(crate) fn offer(vm: &Vm, execution: &Arc) -> Result { let claims = Arc::new(AtomicU64::new(0), GFP_KERNEL)?; + let id = NEXT_SHARE_ID.fetch_add(1, Ordering::Relaxed); + if id == 0 { + return Err(EOVERFLOW); + } let mut shares = SHARES.lock(); shares.push( Entry { + id, vm: vm.id(), execution: execution.clone(), claims: claims.clone(), @@ -115,6 +129,7 @@ pub(crate) fn offer(vm: &Vm, execution: &Arc) -> Result { GFP_KERNEL, )?; Ok(Use { + id, vm: vm.id(), execution: execution.clone(), claims, diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index d47b4f2f88fd8..be97e351f086f 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -222,6 +222,47 @@ pub(super) unsafe fn exported_source_raw(raw: *mut bindings::dma_fence) -> Optio .cloned() } +/// Lock-free coalescing key for an unsignalled, currently published compute `ExportFence`. +/// +/// Two healthy published compute submissions on the same `(epoch, physical QID)` execute and +/// retire in strict FIFO order on that QID, so waiting on the later publication ordinal in +/// firmware subsumes the earlier one without sharing a `dma_fence` context across submits that +/// could fail out of order before publication. +/// +/// # Safety +/// +/// `raw` must point to a live `dma_fence`, and `key` and `seq` must be valid writable pointers. +#[no_mangle] +pub(super) unsafe extern "C" fn asahi_g17_export_coalesce_key( + raw: *mut bindings::dma_fence, + key: *mut u64, + seq: *mut u64, +) -> bool { + let expected = EXPORT_OPS.load(Ordering::Acquire); + if expected == 0 || raw.is_null() { + return false; + } + // SAFETY: Caller holds a live fence reference; vtable check precedes cast to FenceObject. + let object = unsafe { + if (*raw).ops as usize != expected { + return false; + } + &*(raw as *const FenceObject) + }; + let Some(source) = object.source.as_ref() else { + return false; + }; + let Some((pub_key, pub_seq)) = source.published_order_key() else { + return false; + }; + // SAFETY: Caller supplies valid writable output pointers. + unsafe { + *key = pub_key; + *seq = pub_seq; + } + true +} + /// 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)] @@ -229,6 +270,8 @@ pub(crate) struct PublishedSource { pub(crate) epoch: u64, pub(crate) published: u64, pub(crate) dependency: super::fw::kick::KickDependency, + pub(crate) stamp_va: u64, + pub(crate) execution_share: u64, pub(crate) readers: Arc, } @@ -261,15 +304,26 @@ pub(crate) struct Submission { /// Non-zero encoded recovery epoch (`epoch.wrapping_add(1)`) while `state.published` holds a /// live `PublishedSource` snapshot, or `0` when unpublished. published_epoch: AtomicU64, + /// Packed `(qid << 56) | published_seq` written before `published_epoch` (Release), so + /// lock-free coalescing in `sync_input` can collapse same-QID leaves without locking `state`. + published_order: 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 { + const PUBLISHED_SEQ_MASK: u64 = (1u64 << 56) - 1; + fn encode_epoch(epoch: u64) -> u64 { epoch.wrapping_add(1) } + fn encode_order(qid: u8, published: u64) -> u64 { + if published == 0 || published > Self::PUBLISHED_SEQ_MASK { + return 0; + } + (u64::from(qid) << 56) | published + } fn new(context: Arc, firmware_source: bool) -> Result> { let work = Arc::new(WorkStateLease::deferred(context)?, GFP_KERNEL)?; Self::with_work(Some(work), firmware_source) @@ -289,6 +343,7 @@ impl Submission { firmware_source, retired: AtomicBool::new(false), published_epoch: AtomicU64::new(0), + published_order: AtomicU64::new(0), firmware_consumer: AtomicBool::new(false), }), GFP_KERNEL, @@ -316,12 +371,14 @@ impl Submission { return; } let tag = Self::encode_epoch(source.epoch); + let order = Self::encode_order(source.dependency.qid(), source.published); 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_order.store(order, Ordering::Relaxed); self.published_epoch.store(tag, Ordering::Release); } } @@ -347,6 +404,39 @@ impl Submission { let tag = Self::encode_epoch(epoch); self.firmware_source && tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag } + /// Lock-free `(coalesce_key, published_seq)` for a healthy, currently published compute source. + /// Returns `None` when unpublished, retired, errored, or out of packing range. + pub(super) fn published_order_key(&self) -> Option<(u64, u64)> { + if !self.firmware_source { + return None; + } + let epoch_tag = self.published_epoch.load(Ordering::Acquire); + if epoch_tag == 0 || epoch_tag > Self::PUBLISHED_SEQ_MASK { + return None; + } + if self.error.load(Ordering::Acquire) != 0 || self.retired.load(Ordering::Acquire) { + return None; + } + let order = self.published_order.load(Ordering::Relaxed); + core::sync::atomic::fence(Ordering::Acquire); + if self.published_epoch.load(Ordering::Relaxed) != epoch_tag { + return None; + } + let seq = order & Self::PUBLISHED_SEQ_MASK; + if seq == 0 { + return None; + } + let qid = order >> 56; + Some(((epoch_tag << 8) | qid, seq)) + } + pub(super) fn published_order_key_for(&self, epoch: u64) -> Option<(u64, u64)> { + let tag = Self::encode_epoch(epoch); + if tag == 0 || tag > Self::PUBLISHED_SEQ_MASK { + return None; + } + let (key, seq) = self.published_order_key()?; + ((key >> 8) == tag).then_some((key, seq)) + } pub(super) fn note_firmware_consumer(&self) { self.firmware_consumer.store(true, Ordering::Release); } @@ -587,6 +677,93 @@ mod tests { } assert_eq!(source.owners.load(Ordering::Acquire), 0); } + + #[test] + fn published_export_coalesce_key_tracks_epoch_qid_and_invalidation() { + use crate::g17::fw::kick::{KickDependency, KickTimestamp}; + + let contexts = contexts(); + let a = aggregate(&contexts); + let b = aggregate(&contexts); + let c = aggregate(&contexts); + let readers = Arc::new(AtomicU32::new(0), GFP_KERNEL).unwrap(); + let dep_q5_1 = KickDependency::new(5, KickTimestamp::new(10).unwrap()).unwrap(); + let dep_q5_2 = KickDependency::new(5, KickTimestamp::new(11).unwrap()).unwrap(); + let dep_q6_1 = KickDependency::new(6, KickTimestamp::new(12).unwrap()).unwrap(); + + // Unpublished submissions expose no coalesce key. + let (mut k, mut s) = (0u64, 0u64); + assert!(!unsafe { asahi_g17_export_coalesce_key(a.0.raw(), &mut k, &mut s) }); + + // Simulate published snapshots (set_published requires state.work.is_some() in production; + // test the atomic publication contract directly here without a GPU Context). + let publish_direct = |sub: &Submission, epoch: u64, seq: u64, dep: KickDependency| { + let tag = Submission::encode_epoch(epoch); + let order = Submission::encode_order(dep.qid(), seq); + sub.state.lock().published = Some(PublishedSource { + epoch, + published: seq, + dependency: dep, + stamp_va: 0x1000, + execution_share: 1, + readers: readers.clone(), + }); + sub.published_order.store(order, Ordering::Relaxed); + sub.published_epoch.store(tag, Ordering::Release); + }; + + publish_direct(a.source(), 7, 100, dep_q5_1); + publish_direct(b.source(), 7, 101, dep_q5_2); + publish_direct(c.source(), 7, 102, dep_q6_1); + + let (mut ka, mut sa) = (0u64, 0u64); + let (mut kb, mut sb) = (0u64, 0u64); + let (mut kc, mut sc) = (0u64, 0u64); + assert!(unsafe { asahi_g17_export_coalesce_key(a.0.raw(), &mut ka, &mut sa) }); + assert!(unsafe { asahi_g17_export_coalesce_key(b.0.raw(), &mut kb, &mut sb) }); + assert!(unsafe { asahi_g17_export_coalesce_key(c.0.raw(), &mut kc, &mut sc) }); + assert_eq!(ka, kb); + assert!(sb > sa); + assert_ne!(ka, kc); + assert_eq!(a.source().published_order_key_for(7), Some((ka, sa))); + assert_eq!(a.source().published_order_key_for(8), None); + + // Coalescing two same-(epoch, qid) exports collapses to the newer publication ordinal, + // while keeping distinct QIDs separate. + let merged = super::super::sync_input::merge(&[a.fence(), b.fence(), c.fence()]).unwrap(); + let leaves = super::super::sync_input::collect_coalesced(&merged).unwrap(); + assert_eq!(leaves.len(), 2); + assert!(leaves.iter().any(|l| l.fence == b.0.raw())); + assert!(leaves.iter().any(|l| l.fence == c.0.raw())); + assert!(!leaves.iter().any(|l| l.fence == a.0.raw())); + + // Error or retirement clears/suppresses coalescing so errors are never dropped. + a.source().note_error(EIO); + assert!(!unsafe { asahi_g17_export_coalesce_key(a.0.raw(), &mut ka, &mut sa) }); + b.source().clear_published(); + assert!(!unsafe { asahi_g17_export_coalesce_key(b.0.raw(), &mut kb, &mut sb) }); + + a.finish_enqueue(Err(EIO)); + b.finish_enqueue(Ok(())); + c.finish_enqueue(Ok(())); + } + + #[test] + fn lockless_fence_status_tracks_unsignaled_success_and_error() { + let contexts = contexts(); + let ok_fence = independent(&contexts).unwrap(); + let ok_handle = Fence::from_fence(&ok_fence); + assert_eq!(super::super::job::fence_status(&ok_handle), 0); + ok_fence.signal(); + assert_eq!(super::super::job::fence_status(&ok_handle), 1); + + let err_fence = independent(&contexts).unwrap(); + let err_handle = Fence::from_fence(&err_fence); + assert_eq!(super::super::job::fence_status(&err_handle), 0); + err_fence.set_error(EIO); + err_fence.signal(); + assert_eq!(super::super::job::fence_status(&err_handle), EIO.to_errno()); + } } impl Drop for Member { fn drop(&mut self) { diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 2d6e2dd3b2bf3..d30c77aa3b27c 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -301,8 +301,7 @@ impl Packet { } pub(crate) fn fence_status(fence: &Fence) -> i32 { - // SAFETY: The owned fence keeps the raw DMA fence alive for this read. - unsafe { bindings::dma_fence_get_status(fence.raw()) } + super::sync_input::fence_status(fence) } fn check_status(fence: &Fence) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 67c78957fb364..2bbd3e562a1d2 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -3353,6 +3353,8 @@ impl Queue { epoch, published, dependency, + stamp_va: self.graph.support.gpu_va() + STAMP as u64, + execution_share: packet.context.execution_share_id(), readers: self.source_readers.clone(), }, ); diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index f480b7cda3dec..a33c3338b0e5e 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -365,6 +365,12 @@ impl Queue { // either order and must each consume an input's error status before running. for sync in inputs { if let Some(fence) = &sync.fence { + if sources + .as_ref() + .is_some_and(|sources| sources.contains_input(fence)) + { + continue; + } // An input that already signalled without error orders nothing and has no status // left to consume (like a completed frontier producer above). Keeping it would // send the render through the scheduler thread instead of inline publication: @@ -372,12 +378,6 @@ impl Queue { if job::fence_status(fence) > 0 { continue; } - if sources - .as_ref() - .is_some_and(|sources| sources.contains_input(fence)) - { - continue; - } dependencies.push(fence.clone(), GFP_KERNEL)?; checked_inputs.push(fence.clone(), GFP_KERNEL)?; } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index e64a10eb7d945..21fa123b4b270 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2662,7 +2662,7 @@ impl super::Firmware { let Some((sequence, dependency, stamp_va, event_slot, hold, same_execution)) = found else { return Err(EAGAIN); }; - if m5 && dependency.qid() == target_qid { + if 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. @@ -3117,23 +3117,33 @@ 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, + /// Resolves same-VM 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. On M5 and for G17P sources sharing this queue's execution + /// context, cross-QID sources resolve to kick dependencies in `frontier`; G17P cross-context + /// sources resolve to completion-wait records in `native`. 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, + m5: bool, sources: &super::sync_input::Sources, - ) -> Option<(super::dependency::Frontier, KVec, u64)> { + ) -> Option<( + super::dependency::Frontier, + KVec, + KVec, + u64, + )> { sources.check().ok()?; let mut frontier = super::dependency::Frontier::new(); + let mut native: KVec = KVec::new(); let mut holds = KVec::new(); let mut cross_qid_mask = 0u64; + let consumer_share = self.context.execution_share_id(); for (idx, source) in sources.sources.iter().enumerate() { if source.submission.source_status().ok()? { continue; @@ -3163,13 +3173,34 @@ impl Backend { if !source.submission.has_published_epoch(generation) { return None; } - frontier - .insert(published.published, published.dependency) - .ok()?; + let same_execution = + consumer_share != 0 && consumer_share == published.execution_share; + if m5 || same_execution { + frontier + .insert(published.published, published.dependency) + .ok()?; + } else { + let wait = super::sync_input::NativeWait { + sequence: published.published, + dependency: published.dependency, + stamp_va: published.stamp_va, + event_slot: u32::from(published.dependency.qid()), + }; + if let Some(old) = native + .iter_mut() + .find(|old| old.dependency.qid() == wait.dependency.qid()) + { + if wait.sequence > old.sequence { + *old = wait; + } + } else { + native.push(wait, GFP_KERNEL).ok()?; + } + } holds.push(hold, GFP_KERNEL).ok()?; cross_qid_mask |= 1u64 << idx; } - Some((frontier, holds, cross_qid_mask)) + Some((frontier, native, holds, cross_qid_mask)) } /// Whether `packet` may run on, or bring up, a sibling compute channel of this owner: only an @@ -3191,11 +3222,11 @@ impl Backend { /// 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. + /// device-wide is scanned. Same-VM compute sources whose producers have published their kick + /// metadata also resolve directly (kick barriers on M5 and shared-context G17P, completion-wait + /// records on cross-context G17P), 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. + /// installation, cross-channel barriers, render prefixes, replay and recovery. fn compute_direct( &self, packet: &Arc, @@ -3205,8 +3236,7 @@ impl Backend { 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() + if self.context.render_seen() || bound_count == 0 || bound_count > super::pairs::COMPUTE_CHANNELS_MAX || (bound_count > 1 && packet.order.wait_through[1].is_some()) @@ -3228,11 +3258,11 @@ impl Backend { return None; } let generation = port.generation(); - let (direct_frontier, direct_holds, cross_qid_mask) = + let (direct_frontier, direct_native, direct_holds, cross_qid_mask) = if let Some(sources) = packet.completion.sources() { - self.resolve_direct_sources(port, generation, target_qid, sources)? + self.resolve_direct_sources(port, generation, target_qid, m5, sources)? } else { - (super::dependency::Frontier::new(), KVec::new(), 0) + (super::dependency::Frontier::new(), KVec::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 @@ -3350,12 +3380,22 @@ impl Backend { m5, generation, }; - Some(queue.publish( - packet.clone(), - direct_frontier.as_slice(), - &mut host, - &mut |event| deferred.push(event), - )) + Some(if direct_native.is_empty() { + queue.publish( + packet.clone(), + direct_frontier.as_slice(), + &mut host, + &mut |event| deferred.push(event), + ) + } else { + queue.publish_with_native_waits( + packet.clone(), + direct_frontier.as_slice(), + direct_native.as_slice(), + &mut host, + &mut |event| deferred.push(event), + ) + }) })(); if packet.is_published() { if let Some(sources) = packet.completion.sources() { @@ -3370,7 +3410,7 @@ impl Backend { drop(direct_holds); } super::sync_input::note_published(); - super::sync_input::note_native(0); + super::sync_input::note_native(direct_native.len()); } } else { drop(direct_holds); @@ -3559,8 +3599,7 @@ impl Backend { }; // 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 + if bound_count != 0 && bound_count <= super::pairs::COMPUTE_CHANNELS_MAX { let cells = self.direct.lock().clone(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 89cbd0b7fcf74..ed7fe135d935a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -146,6 +146,7 @@ impl job::Backend for Backend { use crate::g17::{fence, sync_input}; let mut heads = KVec::new(); let mut sources: KVec = KVec::new(); + let mut source_keys: KVec> = KVec::new(); let mut publication_waits = KVec::new(); let mut unchecked: KVec = KVec::new(); let lease = self.shared.preparations.try_enter().ok(); @@ -161,7 +162,7 @@ impl job::Backend for Backend { if status > 0 { continue; } if status < 0 { return None; } let leaves = sync_input::collect_coalesced(input)?; - for leaf in &leaves { + for leaf in &*leaves { if leaf.status > 0 { continue; } if leaf.status < 0 { return None; } // SAFETY: Collection owns each leaf until this lookup finishes. @@ -171,11 +172,28 @@ impl job::Backend for Backend { if sources.iter().any(|known| Arc::ptr_eq(&known.submission, &submission)) { continue; } + let pub_key = + port_epoch.and_then(|epoch| submission.published_order_key_for(epoch)); + if let Some((key, seq)) = pub_key { + if let Some(pos) = source_keys + .iter() + .position(|existing| existing.is_some_and(|(k, _)| k == key)) + { + if let Some((_, existing_seq)) = source_keys[pos] { + if seq > existing_seq { + sources[pos] = sync_input::Source { submission }; + source_keys[pos] = Some((key, seq)); + } + } + continue; + } + } if sources.len() == crate::g17::fw::kick::KICK_BARRIERS_MAX { return None; } - let published_fast = - port_epoch.is_some_and(|epoch| submission.has_published_epoch(epoch)); + let published_fast = pub_key.is_some() + || port_epoch.is_some_and(|epoch| submission.has_published_epoch(epoch)); let idx = sources.len(); sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; + source_keys.push(pub_key, GFP_KERNEL).ok()?; if !published_fast { unchecked.push(idx, GFP_KERNEL).ok()?; } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 1b68be583ad4c..68496a6779936 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -6,17 +6,40 @@ #include "sync_input.h" #include "sync_scope.h" +/* + * Lock-free fence status query: avoids taking fence->lock and disabling IRQs + * on the common unsignaled and already-signaled paths. Once SIGNALED_BIT is + * observed, fence->error is immutable (dma_fence_set_error() must precede + * signaling, and test_and_set_bit(SIGNALED_BIT) is a full barrier). + */ +int asahi_g17_fence_status(struct dma_fence *fence) +{ + int error; + + if (!dma_fence_is_signaled(fence)) + return 0; + /* Pair with test_and_set_bit(SIGNALED_BIT) before reading fence->error. */ + smp_rmb(); + error = READ_ONCE(fence->error); + return error ?: 1; +} + static int collect_leaf(struct dma_fence *leaf, struct asahi_g17_fence_leaf *out, size_t capacity, size_t *count, bool coalesce_contexts) { - int status = dma_fence_get_status(leaf); + int status = asahi_g17_fence_status(leaf); + u64 pub_key = 0, pub_seq = 0; + bool has_pub = false; size_t i; /* Already-signalled non-error leaves need no further wait or barrier. */ if (status > 0) return 0; + if (coalesce_contexts && status == 0) + has_pub = asahi_g17_export_coalesce_key(leaf, &pub_key, &pub_seq); + for (i = 0; i < *count; ++i) { if (out[i].fence == leaf) { if (status < 0 && out[i].status >= 0) @@ -37,6 +60,25 @@ static int collect_leaf(struct dma_fence *leaf, } return 0; } + /* + * Coalesce healthy unsignaled exported compute sources already + * published on the same (epoch, physical QID), keeping only the + * latest publication ordinal. Each ExportFence retains its own + * dma_fence context so out-of-order early errors cannot violate + * core dma_fence monotonicity. + */ + if (has_pub && out[i].status == 0) { + u64 out_key = 0, out_seq = 0; + + if (asahi_g17_export_coalesce_key(out[i].fence, &out_key, &out_seq) && + out_key == pub_key) { + if (pub_seq > out_seq) { + dma_fence_put(out[i].fence); + out[i].fence = dma_fence_get(leaf); + } + return 0; + } + } } if (*count == capacity) @@ -65,7 +107,7 @@ static int collect_fences(struct dma_fence *head, if (asahi_g17_is_scope(node)) { struct dma_fence *children[2]; unsigned int n, i; - int status = dma_fence_get_status(node); + int status = asahi_g17_fence_status(node); if (status > 0) { dma_fence_put(node); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.h b/drivers/gpu/drm/asahi/g17/sync_input.h index 9bd90b289de2c..640a428463516 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.h +++ b/drivers/gpu/drm/asahi/g17/sync_input.h @@ -11,6 +11,8 @@ struct asahi_g17_fence_leaf { int status; }; +int asahi_g17_fence_status(struct dma_fence *fence); +bool asahi_g17_export_coalesce_key(struct dma_fence *fence, u64 *key, u64 *seq); int asahi_g17_collect_fences(struct dma_fence *head, struct asahi_g17_fence_leaf *out, size_t capacity); int asahi_g17_collect_fences_coalesced(struct dma_fence *head, diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 987d890069728..af5a761d193c6 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -3,6 +3,7 @@ //! Bounded input-fence components. Collection happens before the device mutex, //! because polling a container's status can signal it and run callbacks. +use core::mem::MaybeUninit; use kernel::{bindings, dma_fence::{Fence, RawDmaFence}, prelude::*}; #[repr(C)] @@ -12,6 +13,7 @@ pub(crate) struct Leaf { } unsafe extern "C" { + fn asahi_g17_fence_status(fence: *mut bindings::dma_fence) -> i32; fn asahi_g17_collect_fences_coalesced(head: *mut bindings::dma_fence, out: *mut Leaf, capacity: usize) -> i32; fn asahi_g17_put_fence(fence: *mut bindings::dma_fence); @@ -20,6 +22,11 @@ unsafe extern "C" { -> *mut bindings::dma_fence; } +pub(crate) fn fence_status(fence: &Fence) -> i32 { + // SAFETY: The owned fence keeps the raw DMA fence alive for this read. + unsafe { asahi_g17_fence_status(fence.raw()) } +} + impl super::dependency::FenceOrder for Fence { fn order(&self, earlier: &Self) -> super::dependency::FenceOrdering { // SAFETY: Both fences are live references; the helper only reads them. @@ -54,11 +61,61 @@ impl Drop for Leaf { } } +const INLINE_LEAVES: usize = 4; + +/// Owned collected leaves: stack-backed for the common <= 4-leaf case (zero heap allocation), +/// spilling to a `KVec` only when an input holds more distinct leaves. +pub(crate) enum Leaves { + Inline { + len: usize, + items: [MaybeUninit; INLINE_LEAVES], + }, + Heap(KVec), +} + +impl core::ops::Deref for Leaves { + type Target = [Leaf]; + + fn deref(&self) -> &[Leaf] { + match self { + Self::Inline { len, items } => { + // SAFETY: `items[..*len]` were initialized by the C collector. + unsafe { core::slice::from_raw_parts(items.as_ptr().cast(), *len) } + } + Self::Heap(vec) => vec.as_slice(), + } + } +} + +impl Drop for Leaves { + fn drop(&mut self) { + if let Self::Inline { len, items } = self { + for slot in &mut items[..*len] { + // SAFETY: Each slot in `0..*len` is initialized and dropped once here. + unsafe { slot.assume_init_drop() }; + } + } + } +} + fn collect_with( input: &Fence, collector: unsafe extern "C" fn(*mut bindings::dma_fence, *mut Leaf, usize) -> i32, -) -> Option> { - let mut capacity = 4; +) -> Option { + let mut capacity = INLINE_LEAVES; + let mut inline = [const { MaybeUninit::::uninit() }; INLINE_LEAVES]; + // SAFETY: `input` owns its fence; the C helper initializes `count` leaves or releases all on error. + let count = unsafe { collector(input.raw(), inline.as_mut_ptr().cast(), capacity) }; + if count >= 0 { + return Some(Leaves::Inline { + len: count as usize, + items: inline, + }); + } + if count != ENOSPC.to_errno() { + return None; + } + capacity = 16; loop { let mut leaves = KVec::with_capacity(capacity, GFP_KERNEL).ok()?; // SAFETY: The input owns its fence. The C helper writes at most capacity @@ -73,14 +130,15 @@ fn collect_with( } // SAFETY: The helper returned this many initialized, owned records. unsafe { leaves.set_len(count as usize) }; - return Some(leaves); + return Some(Leaves::Heap(leaves)); } } /// The leaves of `input`, coalescing unsignalled non-error leaves sharing a `dma_fence` context -/// to their latest sequence number so deep timeline chains stay bounded by distinct contexts. -/// Allocation, unsupported containers, or a large prefix retain normal waits. -pub(crate) fn collect_coalesced(input: &Fence) -> Option> { +/// or a published compute queue `(epoch, qid)` to their latest sequence number so deep timeline +/// chains stay bounded by distinct producers. Allocation, unsupported containers, or a large +/// prefix retain normal waits. +pub(crate) fn collect_coalesced(input: &Fence) -> Option { collect_with(input, asahi_g17_collect_fences_coalesced) } diff --git a/tools/asahi/g17-m5-cross-qid-direct-tests.py b/tools/asahi/g17-m5-cross-qid-direct-tests.py index 9f4d4d37c0739..360d1076b20a4 100755 --- a/tools/asahi/g17-m5-cross-qid-direct-tests.py +++ b/tools/asahi/g17-m5-cross-qid-direct-tests.py @@ -78,11 +78,15 @@ def build_c_harness(mutation=None): #include #include +typedef uint64_t u64; + struct dma_fence {{ uint64_t context; uint64_t seqno; int status; int refs; + uint64_t pub_key; + uint64_t pub_seq; }}; struct asahi_g17_fence_leaf {{ @@ -102,11 +106,20 @@ def build_c_harness(mutation=None): f->refs--; }} -static int dma_fence_get_status(struct dma_fence *f) +static int asahi_g17_fence_status(struct dma_fence *f) {{ return f->status; }} +static bool asahi_g17_export_coalesce_key(struct dma_fence *f, u64 *key, u64 *seq) +{{ + if (!f->pub_key) + return false; + *key = f->pub_key; + *seq = f->pub_seq; + return true; +}} + static bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) {{ assert(f1->context == f2->context); @@ -131,6 +144,8 @@ def build_c_harness(mutation=None): chain[i].seqno = order[i]; chain[i].status = 0; chain[i].refs = 1; + chain[i].pub_key = 0; + chain[i].pub_seq = 0; }} struct asahi_g17_fence_leaf out[16]; size_t count = 0; @@ -185,6 +200,34 @@ def build_c_harness(mutation=None): assert(collect_leaf(&z1, out, 16, &count, true) == 0); assert(count == 2); release_all(out, count); + + /* 5. Distinct-context ExportFences published on the same (epoch, qid) coalesce to newest. */ + struct dma_fence exp[4] = {{ + {{ .context = 101, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 12 }}, + {{ .context = 102, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 19 }}, + {{ .context = 103, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 15 }}, + {{ .context = 104, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 6, .pub_seq = 20 }}, + }}; + count = 0; + for (int i = 0; i < 4; ++i) + assert(collect_leaf(&exp[i], out, 16, &count, true) == 0); + assert(count == 2); + assert(out[0].fence == &exp[1]); + assert(out[1].fence == &exp[3]); + release_all(out, count); + for (int i = 0; i < 4; ++i) + assert(exp[i].refs == 1); + + /* 6. Failed or unpublished ExportFence on same QID is never dropped. */ + struct dma_fence exp_fail = {{ .context = 105, .seqno = 0, .status = -EIO, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 10 }}; + struct dma_fence exp_unpub = {{ .context = 106, .seqno = 0, .status = 0, .refs = 1, .pub_key = 0, .pub_seq = 0 }}; + count = 0; + assert(collect_leaf(&exp_fail, out, 16, &count, true) == 0); + assert(collect_leaf(&exp[1], out, 16, &count, true) == 0); + assert(collect_leaf(&exp_unpub, out, 16, &count, true) == 0); + assert(count == 3); + release_all(out, count); + assert(exp_fail.refs == 1 && exp[1].refs == 1 && exp_unpub.refs == 1); return 0; }} ''' @@ -272,8 +315,8 @@ def build_rust_harness(mutation=None): ) # 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 {') + collect_cap_ok = 'const INLINE_LEAVES: usize = 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 = ( @@ -287,14 +330,16 @@ def build_rust_harness(mutation=None): ) ) direct_sources_ok = ( - '(has_sources && !m5)' in compute_direct_fn + '(has_sources && !m5)' not in compute_direct_fn and ordered_ok( compute_direct_fn, 'let target_qid = cells[0].as_ref()?.qid()?;', - 'self.resolve_direct_sources(port, generation, target_qid, sources)?', + 'self.resolve_direct_sources(port, generation, target_qid, m5, sources)?', 'queue.qid() != target_qid', 'queue.publish(', 'direct_frontier.as_slice(),', + 'queue.publish_with_native_waits(', + 'direct_native.as_slice(),', 'source.submission.note_firmware_consumer();', 'sources.set_holds(direct_holds);', 'drop(direct_holds);', @@ -338,10 +383,13 @@ def build_rust_harness(mutation=None): 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::NativeWait', 'NativeWait') host_resolve = host_resolve.replace('super::sync_input::Hold', 'Hold') + host_resolve = host_resolve.replace('KVec', 'Vec') 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);') + host_resolve = host_resolve.replace('native.push(wait, GFP_KERNEL).ok()?;', 'native.push(wait);') return f''' use std::sync::{{Arc, Mutex, atomic::{{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}}}}; @@ -368,14 +416,31 @@ def build_rust_harness(mutation=None): fn qid(self) -> u8 {{ self.qid }} }} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct NativeWait {{ + sequence: u64, + dependency: KickDependency, + stamp_va: u64, + event_slot: u32, +}} + #[derive(Clone)] struct PublishedSource {{ epoch: u64, published: u64, dependency: KickDependency, + stamp_va: u64, + execution_share: u64, readers: Arc, }} +struct Context {{ + share_id: u64, +}} +impl Context {{ + fn execution_share_id(&self) -> u64 {{ self.share_id }} +}} + struct Frontier {{ items: Vec<(u64, KickDependency)>, }} @@ -479,21 +544,23 @@ def build_rust_harness(mutation=None): }} }} -struct Backend; +struct Backend {{ + context: Context, +}} impl Backend {{ {host_resolve} }} fn main() {{ - assert!({str(collect_cap_ok).lower()}, "sync_input::collect must start with capacity 4"); + assert!({str(collect_cap_ok).lower()}, "sync_input::collect must start with inline 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(direct_sources_ok).lower()}, "compute_direct must resolve M5 and G17P 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 backend = Backend {{ context: Context {{ share_id: 42 }} }}; let port = Port {{ gen: AtomicU64::new(7), rec: AtomicU32::new(0), @@ -502,7 +569,7 @@ def build_rust_harness(mutation=None): 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, + // 1. Happy path (M5): 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. @@ -512,6 +579,8 @@ def build_rust_harness(mutation=None): epoch: 7, published: 42, dependency: KickDependency {{ qid: 5, kick: 100 }}, + stamp_va: 0xfeed_0000, + execution_share: 42, readers: readers.clone(), }}); let locks_before = sub.state_locks.load(Ordering::Relaxed); @@ -519,8 +588,9 @@ def build_rust_harness(mutation=None): 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(); + let (frontier, native, holds, mask) = backend.resolve_direct_sources(&port, 7, 9, true, &sources).unwrap(); assert_eq!(frontier.items, vec![(42, KickDependency {{ qid: 5, kick: 100 }})]); + assert!(native.is_empty()); assert_eq!(holds.len(), 1); assert_eq!(mask, 1); assert_eq!(readers.load(Ordering::Acquire), 1); @@ -533,43 +603,91 @@ def build_rust_harness(mutation=None): 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. + // 1a. G17P shared execution context (same share_id 42): resolves to Frontier kick barrier, no NativeWait! + let (f_g17p_same, n_g17p_same, h_g17p_same, m_g17p_same) = + backend.resolve_direct_sources(&port, 7, 9, false, &sources).unwrap(); + assert_eq!(f_g17p_same.items, vec![(42, KickDependency {{ qid: 5, kick: 100 }})]); + assert!(n_g17p_same.is_empty()); + assert_eq!(h_g17p_same.len(), 1); + assert_eq!(m_g17p_same, 1); + drop(h_g17p_same); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 1a2. G17P cross-execution-context (different share_id): resolves to NativeWait (deduped by QID), empty Frontier! + let other_ctx_backend = Backend {{ context: Context {{ share_id: 99 }} }}; + let sub_later = Submission::new(); + sub_later.set_published(PublishedSource {{ + epoch: 7, + published: 45, + dependency: KickDependency {{ qid: 5, kick: 103 }}, + stamp_va: 0xfeed_0000, + execution_share: 42, + readers: readers.clone(), + }}); + let two_same_qid = Sources {{ + sources: vec![Source {{ submission: sub.clone() }}, Source {{ submission: sub_later.clone() }}], + }}; + let (f_g17p_xctx, n_g17p_xctx, h_g17p_xctx, m_g17p_xctx) = + other_ctx_backend.resolve_direct_sources(&port, 7, 9, false, &two_same_qid).unwrap(); + assert!(f_g17p_xctx.items.is_empty()); + assert_eq!(n_g17p_xctx.len(), 1); + assert_eq!(n_g17p_xctx[0].sequence, 45); + assert_eq!(n_g17p_xctx[0].stamp_va, 0xfeed_0000); + assert_eq!(n_g17p_xctx[0].event_slot, 5); + assert_eq!(h_g17p_xctx.len(), 2); + assert_eq!(m_g17p_xctx, 0b11); + drop(h_g17p_xctx); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // 1b. Same-QID source (qid 5 -> target_qid 5): skipped cleanly on both M5 and G17P. let same_sub = Submission::new(); same_sub.set_published(PublishedSource {{ epoch: 7, published: 43, dependency: KickDependency {{ qid: 5, kick: 101 }}, + stamp_va: 0xfeed_0000, + execution_share: 42, 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)); + for m5 in [true, false] {{ + let (f_same, n_same, h_same, m_same) = + backend.resolve_direct_sources(&port, 7, 5, m5, &same_sources).unwrap(); + assert!(f_same.items.is_empty(), "same-QID source must not emit a duplicate explicit barrier"); + assert!(n_same.is_empty(), "same-QID source must not emit a NativeWait"); + 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!(backend.resolve_direct_sources(&port, 7, 5, true, &same_sources).is_none()); + assert!(backend.resolve_direct_sources(&port, 7, 5, false, &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()); + assert!(backend.resolve_direct_sources(&port, 7, 9, true, &s_unpub).is_none()); + assert!(backend.resolve_direct_sources(&port, 7, 9, false, &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!(backend.resolve_direct_sources(&port, 8, 9, true, &sources).is_none()); + assert!(backend.resolve_direct_sources(&port, 8, 9, false, &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!(backend.resolve_direct_sources(&port, 7, 9, true, &sources).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + port.rec.store(0, Ordering::Release); + port.flip_rec_on_query.store(true, Ordering::Release); + assert!(backend.resolve_direct_sources(&port, 7, 9, false, &sources).is_none()); assert_eq!(readers.load(Ordering::Acquire), 0); port.rec.store(0, Ordering::Release); @@ -579,11 +697,14 @@ def build_rust_harness(mutation=None): epoch: 7, published: 44, dependency: KickDependency {{ qid: 5, kick: 102 }}, + stamp_va: 0xfeed_0000, + execution_share: 42, 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()); + assert!(backend.resolve_direct_sources(&port, 7, 9, true, &s_can).is_none()); + assert!(backend.resolve_direct_sources(&port, 7, 9, false, &s_can).is_none()); // 6. Failed producer -> clean None fallback (so slow path propagates PRODUCER_FAILED). let failed = Submission::new(); @@ -591,19 +712,23 @@ def build_rust_harness(mutation=None): epoch: 7, published: 45, dependency: KickDependency {{ qid: 5, kick: 103 }}, + stamp_va: 0xfeed_0000, + execution_share: 42, 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!(backend.resolve_direct_sources(&port, 7, 9, true, &s_fail).is_none()); + assert!(backend.resolve_direct_sources(&port, 7, 9, false, &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(); + let (f_ret, n_ret, h_ret, m_ret) = backend.resolve_direct_sources(&port, 7, 9, false, &s_ret).unwrap(); assert!(f_ret.items.is_empty()); + assert!(n_ret.is_empty()); assert!(h_ret.is_empty()); assert_eq!(m_ret, 0); diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py index 3068c820beb54..50e35a1401801 100755 --- a/tools/asahi/g17-m5-sibling-gate-tests.py +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -169,13 +169,13 @@ def build(mutation=None): # (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)?', + direct, 'let generation = port.generation();', + 'self.resolve_direct_sources(port, generation, target_qid, m5, 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())', + 'readiness claims the primary for sources': ordered_ok( + readiness, 'let sources_checked =', 'if bound_count != 0', '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, From 100b51f792b742f0ed238347f2b81727eea2816a Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 10:41:13 -0500 Subject: [PATCH 2/3] selftests/asahi-m4: update sync_input C shim for lockless fence status drivers/gpu/drm/asahi/g17/sync_input.c now queries fence status locklessly via asahi_g17_fence_status() (using dma_fence_is_signaled(), smp_rmb(), and READ_ONCE(fence->error)) and coalesces published ExportFences via asahi_g17_export_coalesce_key(). Update the standalone C host-test shim in test-fence-signalling.py that includes sync_input.c directly so it models signaled + error fields on struct dma_fence, provides dma_fence_is_signaled(), smp_rmb(), READ_ONCE(), and asahi_g17_export_coalesce_key(), and covers lockless fence status and published-source coalescing. Signed-off-by: DjDeveloperr --- .../gpu/asahi-m4/test-fence-signalling.py | 75 ++++++++++++++++--- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index ffc523fa9f5e3..962983e9604e3 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -552,14 +552,22 @@ def extract_function(text, name): #define ASAHI_G17_SYNC_SCOPE_H 1 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #define GFP_KERNEL 0 +#define READ_ONCE(x) (x) + +static inline void smp_rmb(void) +{ +} struct dma_fence { uint64_t context; uint64_t seqno; - int status; + bool signaled; + int error; int refcount; bool is_chain; bool is_container; + uint64_t pub_key; + uint64_t pub_seq; struct dma_fence *chain_next; struct dma_fence *chain_fence; }; @@ -585,9 +593,9 @@ def extract_function(text, name): } } -static inline int dma_fence_get_status(struct dma_fence *f) +static inline bool dma_fence_is_signaled(struct dma_fence *f) { - return f ? f->status : 1; + return f && f->signaled; } static inline bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) @@ -671,6 +679,16 @@ def extract_function(text, name): } #include "sync_input.h" + +bool asahi_g17_export_coalesce_key(struct dma_fence *fence, u64 *key, u64 *seq) +{ + if (!fence || !fence->pub_key) + return false; + *key = fence->pub_key; + *seq = fence->pub_seq; + return true; +} + #include "sync_input.c" int main(void) @@ -687,7 +705,8 @@ def extract_function(text, name): for (i = 0; i < HOPS; ++i) { leaves[i].context = (i % 2 == 0) ? 10 : 20; leaves[i].seqno = (uint64_t)(i / 2 + 1); - leaves[i].status = 0; + leaves[i].signaled = false; + leaves[i].error = 0; leaves[i].refcount = 1; chains[i].is_chain = true; @@ -696,6 +715,11 @@ def extract_function(text, name): chains[i].chain_next = (i > 0) ? &chains[i - 1] : NULL; } + /* Unsignalled fence ignores pre-populated error until signaled. */ + leaves[0].error = -5; + assert(asahi_g17_fence_status(&leaves[0]) == 0); + leaves[0].error = 0; + /* Coalesced collector fits a 256-hop 2-queue timeline chain into capacity=4 with 2 leaves. */ n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); assert(n == 2); @@ -711,17 +735,22 @@ def extract_function(text, name): assert(n == -ENOSPC); /* Already-signalled leaves (status > 0) are skipped by both collectors. */ - for (i = 0; i < HOPS; ++i) - leaves[i].status = 1; + for (i = 0; i < HOPS; ++i) { + leaves[i].signaled = true; + leaves[i].error = 0; + } + assert(asahi_g17_fence_status(&leaves[0]) == 1); n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); assert(n == 0); n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); assert(n == 0); /* Error leaf (status < 0) is preserved even when a later same-context leaf is unsignalled. */ - leaves[5].status = -5; - leaves[HOPS - 1].status = 0; - leaves[HOPS - 2].status = 0; + leaves[5].signaled = true; + leaves[5].error = -5; + assert(asahi_g17_fence_status(&leaves[5]) == -5); + leaves[HOPS - 1].signaled = false; + leaves[HOPS - 2].signaled = false; n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); assert(n == 3); { @@ -738,6 +767,34 @@ def extract_function(text, name): assert(saw_err && saw_ctx10 && saw_ctx20); } + /* Published ExportFences on distinct contexts sharing (epoch, qid) coalesce to latest seq. */ + { + struct dma_fence pub_leaves[3]; + struct dma_fence pub_chains[3]; + + memset(pub_leaves, 0, sizeof(pub_leaves)); + memset(pub_chains, 0, sizeof(pub_chains)); + for (i = 0; i < 3; ++i) { + pub_leaves[i].context = (uint64_t)(100 + i); + pub_leaves[i].refcount = 1; + pub_leaves[i].pub_key = (7ULL << 8) | 3; + pub_leaves[i].pub_seq = (uint64_t)(i == 1 ? 30 : (i == 0 ? 10 : 20)); + + pub_chains[i].is_chain = true; + pub_chains[i].refcount = 1; + pub_chains[i].chain_fence = &pub_leaves[i]; + pub_chains[i].chain_next = (i > 0) ? &pub_chains[i - 1] : NULL; + } + n = asahi_g17_collect_fences_coalesced(&pub_chains[2], out, 4); + assert(n == 1); + assert(out[0].fence == &pub_leaves[1] && out[0].status == 0); + asahi_g17_put_fence(out[0].fence); + for (i = 0; i < 3; ++i) { + assert(pub_leaves[i].refcount == 1); + assert(pub_chains[i].refcount == 1); + } + } + /* Every refcount returns cleanly to 1 (no leaks or double puts). */ for (i = 0; i < HOPS; ++i) { assert(leaves[i].refcount == 1); From 871fe9798f34008da22802e2548a5dc4f3bd59ad Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 12:26:15 -0500 Subject: [PATCH 3/3] drm/asahi: g17: retain error dependencies for coalesced published sources Coalescing healthy unsignalled published compute ExportFences on the same (epoch, physical QID) in sync_input.c discarded the earlier ExportFence reference before Backend::input_sources() could record it. Because an earlier submission on the same QID can still fail independently after collection (for example via its own producer error, cancellation, or recovery interrupt) while a later publication on that QID completes cleanly, dropping the earlier reference could hide a late failure from a consumer waiting on the coalesced set. Remove cross-context ExportFence coalescing from sync_input.c so collect_coalesced() returns all distinct-context ExportFence leaves, and perform same-(epoch, QID) firmware-wait coalescing in sync_input::coalesce_source() / Backend::input_sources() while retaining every superseded earlier Submission in Sources::coalesced_errors. Sources::check() checks both wait sources and coalesced_errors lock-free (before publication, at retirement, in DeferredBatch::finish(), and before signalling the consumer fence), so firmware still emits at most one barrier/NativeWait per QID while any late error on an earlier coalesced source fails the consumer with PRODUCER_FAILED. Add KUnit and host mutation tests (drop-coalesced-error and skip-coalesced-error-check) asserting the consumer outcome when an earlier initially healthy coalesced export fails after collection while the retained later export completes cleanly. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/fence.rs | 161 ++++++++------ drivers/gpu/drm/asahi/g17/runtime.rs | 1 + drivers/gpu/drm/asahi/g17/runtime/backend.rs | 41 ++-- drivers/gpu/drm/asahi/g17/sync_input.c | 24 --- drivers/gpu/drm/asahi/g17/sync_input.h | 1 - drivers/gpu/drm/asahi/g17/sync_input.rs | 74 ++++++- tools/asahi/g17-m5-cross-qid-direct-tests.py | 201 ++++++++++++++---- tools/asahi/run-host-tests.py | 4 +- .../gpu/asahi-m4/test-fence-signalling.py | 25 +-- 9 files changed, 351 insertions(+), 181 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index be97e351f086f..cf17d26acc944 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -222,47 +222,6 @@ pub(super) unsafe fn exported_source_raw(raw: *mut bindings::dma_fence) -> Optio .cloned() } -/// Lock-free coalescing key for an unsignalled, currently published compute `ExportFence`. -/// -/// Two healthy published compute submissions on the same `(epoch, physical QID)` execute and -/// retire in strict FIFO order on that QID, so waiting on the later publication ordinal in -/// firmware subsumes the earlier one without sharing a `dma_fence` context across submits that -/// could fail out of order before publication. -/// -/// # Safety -/// -/// `raw` must point to a live `dma_fence`, and `key` and `seq` must be valid writable pointers. -#[no_mangle] -pub(super) unsafe extern "C" fn asahi_g17_export_coalesce_key( - raw: *mut bindings::dma_fence, - key: *mut u64, - seq: *mut u64, -) -> bool { - let expected = EXPORT_OPS.load(Ordering::Acquire); - if expected == 0 || raw.is_null() { - return false; - } - // SAFETY: Caller holds a live fence reference; vtable check precedes cast to FenceObject. - let object = unsafe { - if (*raw).ops as usize != expected { - return false; - } - &*(raw as *const FenceObject) - }; - let Some(source) = object.source.as_ref() else { - return false; - }; - let Some((pub_key, pub_seq)) = source.published_order_key() else { - return false; - }; - // SAFETY: Caller supplies valid writable output pointers. - unsafe { - *key = pub_key; - *seq = pub_seq; - } - true -} - /// 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)] @@ -305,7 +264,8 @@ pub(crate) struct Submission { /// live `PublishedSource` snapshot, or `0` when unpublished. published_epoch: AtomicU64, /// Packed `(qid << 56) | published_seq` written before `published_epoch` (Release), so - /// lock-free coalescing in `sync_input` can collapse same-QID leaves without locking `state`. + /// `Backend::input_sources()` can collapse same-QID firmware wait barriers without locking + /// `state` while retaining earlier submissions for error checking in `Sources::check()`. published_order: AtomicU64, /// Set atomically when a firmware kick depends on this source so replay/retirement /// observes consumers without scanning producer queues under the device mutex. @@ -681,6 +641,7 @@ mod tests { #[test] fn published_export_coalesce_key_tracks_epoch_qid_and_invalidation() { use crate::g17::fw::kick::{KickDependency, KickTimestamp}; + use crate::g17::sync_input::{coalesce_source, Coalesce, Source, Sources}; let contexts = contexts(); let a = aggregate(&contexts); @@ -692,8 +653,7 @@ mod tests { let dep_q6_1 = KickDependency::new(6, KickTimestamp::new(12).unwrap()).unwrap(); // Unpublished submissions expose no coalesce key. - let (mut k, mut s) = (0u64, 0u64); - assert!(!unsafe { asahi_g17_export_coalesce_key(a.0.raw(), &mut k, &mut s) }); + assert_eq!(a.source().published_order_key(), None); // Simulate published snapshots (set_published requires state.work.is_some() in production; // test the atomic publication contract directly here without a GPU Context). @@ -716,36 +676,111 @@ mod tests { publish_direct(b.source(), 7, 101, dep_q5_2); publish_direct(c.source(), 7, 102, dep_q6_1); - let (mut ka, mut sa) = (0u64, 0u64); - let (mut kb, mut sb) = (0u64, 0u64); - let (mut kc, mut sc) = (0u64, 0u64); - assert!(unsafe { asahi_g17_export_coalesce_key(a.0.raw(), &mut ka, &mut sa) }); - assert!(unsafe { asahi_g17_export_coalesce_key(b.0.raw(), &mut kb, &mut sb) }); - assert!(unsafe { asahi_g17_export_coalesce_key(c.0.raw(), &mut kc, &mut sc) }); + let (ka, sa) = a.source().published_order_key().unwrap(); + let (kb, sb) = b.source().published_order_key().unwrap(); + let (kc, sc) = c.source().published_order_key().unwrap(); assert_eq!(ka, kb); assert!(sb > sa); assert_ne!(ka, kc); assert_eq!(a.source().published_order_key_for(7), Some((ka, sa))); assert_eq!(a.source().published_order_key_for(8), None); - // Coalescing two same-(epoch, qid) exports collapses to the newer publication ordinal, - // while keeping distinct QIDs separate. + // Distinct-context ExportFences are all preserved by collect_coalesced() so + // Backend::input_sources() retains error dependencies for every earlier export. let merged = super::super::sync_input::merge(&[a.fence(), b.fence(), c.fence()]).unwrap(); let leaves = super::super::sync_input::collect_coalesced(&merged).unwrap(); - assert_eq!(leaves.len(), 2); - assert!(leaves.iter().any(|l| l.fence == b.0.raw())); - assert!(leaves.iter().any(|l| l.fence == c.0.raw())); - assert!(!leaves.iter().any(|l| l.fence == a.0.raw())); - - // Error or retirement clears/suppresses coalescing so errors are never dropped. - a.source().note_error(EIO); - assert!(!unsafe { asahi_g17_export_coalesce_key(a.0.raw(), &mut ka, &mut sa) }); - b.source().clear_published(); - assert!(!unsafe { asahi_g17_export_coalesce_key(b.0.raw(), &mut kb, &mut sb) }); + assert_eq!(leaves.len(), 3); + + // Coalescing two same-(epoch, qid) exports keeps only the newest wait source while + // retaining the earlier submission in coalesced_errors (both arrival orders). + let build_sources = |order: [&Aggregate; 3]| -> Arc { + let mut wait_sources: KVec = KVec::new(); + let mut keys: KVec> = KVec::new(); + let mut coalesced_errors: KVec> = KVec::new(); + for agg in order { + let sub = agg.source().clone(); + let key = sub.published_order_key_for(7); + let _ = coalesce_source( + &mut wait_sources, + &mut keys, + &mut coalesced_errors, + sub, + key, + ) + .unwrap(); + } + assert_eq!(wait_sources.len(), 2); + assert!(wait_sources.iter().any(|s| Arc::ptr_eq(&s.submission, b.source()))); + assert!(wait_sources.iter().any(|s| Arc::ptr_eq(&s.submission, c.source()))); + assert_eq!(coalesced_errors.len(), 1); + assert!(Arc::ptr_eq(&coalesced_errors[0], a.source())); + Sources::new(KVec::new(), wait_sources, coalesced_errors, KVec::new()).unwrap() + }; + let consumer_fwd = build_sources([&a, &b, &c]); + let consumer_rev = build_sources([&b, &a, &c]); + assert!(consumer_fwd.check().is_ok()); + assert!(consumer_rev.check().is_ok()); - a.finish_enqueue(Err(EIO)); + // Duplicate leaf after coalescing is recognized cleanly without duplicating error entries. + { + let mut wait_sources: KVec = KVec::new(); + let mut keys: KVec> = KVec::new(); + let mut coalesced_errors: KVec> = KVec::new(); + assert!(matches!( + coalesce_source( + &mut wait_sources, + &mut keys, + &mut coalesced_errors, + b.source().clone(), + Some((kb, sb)), + ), + Ok(Coalesce::Insert) + )); + assert!(matches!( + coalesce_source( + &mut wait_sources, + &mut keys, + &mut coalesced_errors, + a.source().clone(), + Some((ka, sa)), + ), + Ok(Coalesce::Coalesced) + )); + assert!(matches!( + coalesce_source( + &mut wait_sources, + &mut keys, + &mut coalesced_errors, + a.source().clone(), + Some((ka, sa)), + ), + Ok(Coalesce::Duplicate) + )); + assert_eq!(coalesced_errors.len(), 1); + } + + // Late error after collection: retained later export `b` (and `c`) complete cleanly, + // while earlier coalesced export `a` fails later. Consumer check MUST observe the error. b.finish_enqueue(Ok(())); c.finish_enqueue(Ok(())); + assert_eq!(b.source().source_status(), Ok(true)); + assert_eq!(c.source().source_status(), Ok(true)); + assert!(consumer_fwd.check().is_ok()); + assert!(consumer_rev.check().is_ok()); + + a.finish_enqueue(Err(EIO)); + assert_eq!(a.source().published_order_key(), None); + assert_eq!( + consumer_fwd.check(), + Err(crate::g17::dependency::PRODUCER_FAILED) + ); + assert_eq!( + consumer_rev.check(), + Err(crate::g17::dependency::PRODUCER_FAILED) + ); + + b.source().clear_published(); + assert_eq!(b.source().published_order_key(), None); } #[test] diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 21fa123b4b270..eab8de0335a3a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -3200,6 +3200,7 @@ impl Backend { holds.push(hold, GFP_KERNEL).ok()?; cross_qid_mask |= 1u64 << idx; } + sources.check().ok()?; Some((frontier, native, holds, cross_qid_mask)) } diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index ed7fe135d935a..a0b9aba00ed2f 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -147,6 +147,7 @@ impl job::Backend for Backend { let mut heads = KVec::new(); let mut sources: KVec = KVec::new(); let mut source_keys: KVec> = KVec::new(); + let mut coalesced_errors: KVec> = KVec::new(); let mut publication_waits = KVec::new(); let mut unchecked: KVec = KVec::new(); let lease = self.shared.preparations.try_enter().ok(); @@ -169,33 +170,25 @@ impl job::Backend for Backend { let submission = unsafe { fence::exported_source_raw(leaf.fence) }?; if submission.source_status().ok()? { continue; } if !submission.same_vm(self.context.status()) { return None; } - if sources.iter().any(|known| Arc::ptr_eq(&known.submission, &submission)) { - continue; - } let pub_key = port_epoch.and_then(|epoch| submission.published_order_key_for(epoch)); - if let Some((key, seq)) = pub_key { - if let Some(pos) = source_keys - .iter() - .position(|existing| existing.is_some_and(|(k, _)| k == key)) - { - if let Some((_, existing_seq)) = source_keys[pos] { - if seq > existing_seq { - sources[pos] = sync_input::Source { submission }; - source_keys[pos] = Some((key, seq)); - } - } - continue; - } - } - if sources.len() == crate::g17::fw::kick::KICK_BARRIERS_MAX { return None; } let published_fast = pub_key.is_some() || port_epoch.is_some_and(|epoch| submission.has_published_epoch(epoch)); - let idx = sources.len(); - sources.push(sync_input::Source { submission }, GFP_KERNEL).ok()?; - source_keys.push(pub_key, GFP_KERNEL).ok()?; - if !published_fast { - unchecked.push(idx, GFP_KERNEL).ok()?; + match sync_input::coalesce_source( + &mut sources, + &mut source_keys, + &mut coalesced_errors, + submission, + pub_key, + ) + .ok()? + { + sync_input::Coalesce::Duplicate | sync_input::Coalesce::Coalesced => continue, + sync_input::Coalesce::Insert => { + if !published_fast { + unchecked.push(sources.len() - 1, GFP_KERNEL).ok()?; + } + } } } heads.push(input.clone(), GFP_KERNEL).ok()?; @@ -236,7 +229,7 @@ impl job::Backend for Backend { } } } - sync_input::Sources::new(heads, sources, publication_waits).ok() + sync_input::Sources::new(heads, sources, coalesced_errors, publication_waits).ok() } fn feed(&self) -> Option> { diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 68496a6779936..4adbe490a5e00 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -29,17 +29,12 @@ static int collect_leaf(struct dma_fence *leaf, size_t *count, bool coalesce_contexts) { int status = asahi_g17_fence_status(leaf); - u64 pub_key = 0, pub_seq = 0; - bool has_pub = false; size_t i; /* Already-signalled non-error leaves need no further wait or barrier. */ if (status > 0) return 0; - if (coalesce_contexts && status == 0) - has_pub = asahi_g17_export_coalesce_key(leaf, &pub_key, &pub_seq); - for (i = 0; i < *count; ++i) { if (out[i].fence == leaf) { if (status < 0 && out[i].status >= 0) @@ -60,25 +55,6 @@ static int collect_leaf(struct dma_fence *leaf, } return 0; } - /* - * Coalesce healthy unsignaled exported compute sources already - * published on the same (epoch, physical QID), keeping only the - * latest publication ordinal. Each ExportFence retains its own - * dma_fence context so out-of-order early errors cannot violate - * core dma_fence monotonicity. - */ - if (has_pub && out[i].status == 0) { - u64 out_key = 0, out_seq = 0; - - if (asahi_g17_export_coalesce_key(out[i].fence, &out_key, &out_seq) && - out_key == pub_key) { - if (pub_seq > out_seq) { - dma_fence_put(out[i].fence); - out[i].fence = dma_fence_get(leaf); - } - return 0; - } - } } if (*count == capacity) diff --git a/drivers/gpu/drm/asahi/g17/sync_input.h b/drivers/gpu/drm/asahi/g17/sync_input.h index 640a428463516..78ff2903b2938 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.h +++ b/drivers/gpu/drm/asahi/g17/sync_input.h @@ -12,7 +12,6 @@ struct asahi_g17_fence_leaf { }; int asahi_g17_fence_status(struct dma_fence *fence); -bool asahi_g17_export_coalesce_key(struct dma_fence *fence, u64 *key, u64 *seq); int asahi_g17_collect_fences(struct dma_fence *head, struct asahi_g17_fence_leaf *out, size_t capacity); int asahi_g17_collect_fences_coalesced(struct dma_fence *head, diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index af5a761d193c6..ae69d2fcf9ac8 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -135,9 +135,10 @@ fn collect_with( } /// The leaves of `input`, coalescing unsignalled non-error leaves sharing a `dma_fence` context -/// or a published compute queue `(epoch, qid)` to their latest sequence number so deep timeline -/// chains stay bounded by distinct producers. Allocation, unsupported containers, or a large -/// prefix retain normal waits. +/// to their latest sequence number so deep timeline chains stay bounded by distinct contexts. +/// Distinct-context `ExportFence`s are all returned so `Backend::input_sources()` can coalesce +/// same-`(epoch, QID)` firmware waits while retaining earlier error dependencies separately. +/// Allocation, unsupported containers, or a large prefix retain normal waits. pub(crate) fn collect_coalesced(input: &Fence) -> Option { collect_with(input, asahi_g17_collect_fences_coalesced) } @@ -151,6 +152,61 @@ pub(super) struct Source { pub(super) submission: Arc, } +pub(super) enum Coalesce { + Duplicate, + Coalesced, + Insert, +} + +/// Deduplicates and coalesces `submission` into `(sources, source_keys, coalesced_errors)`. +/// +/// Two healthy unsignalled published compute submissions on the same `(epoch, QID)` execute in +/// FIFO order on that QID, so firmware only needs a barrier on the latest publication ordinal. +/// Because an earlier submission can still fail independently after collection (for example via +/// its own producer failure, cancellation, or recovery interrupt) while the retained later +/// submission completes cleanly, every superseded earlier submission is retained in +/// `coalesced_errors` so [`Sources::check`] propagates its error to the consumer. +pub(super) fn coalesce_source( + sources: &mut KVec, + source_keys: &mut KVec>, + coalesced_errors: &mut KVec>, + submission: Arc, + pub_key: Option<(u64, u64)>, +) -> Result { + if sources + .iter() + .any(|known| Arc::ptr_eq(&known.submission, &submission)) + || coalesced_errors + .iter() + .any(|known| Arc::ptr_eq(known, &submission)) + { + return Ok(Coalesce::Duplicate); + } + if let Some((key, seq)) = pub_key { + if let Some(pos) = source_keys + .iter() + .position(|existing| existing.is_some_and(|(k, _)| k == key)) + { + if let Some((_, existing_seq)) = source_keys[pos] { + let earlier = if seq > existing_seq { + source_keys[pos] = Some((key, seq)); + core::mem::replace(&mut sources[pos].submission, submission) + } else { + submission + }; + coalesced_errors.push(earlier, GFP_KERNEL)?; + return Ok(Coalesce::Coalesced); + } + } + } + if sources.len() == super::fw::kick::KICK_BARRIERS_MAX { + return Err(ENOSPC); + } + sources.push(Source { submission }, GFP_KERNEL)?; + source_keys.push(pub_key, GFP_KERNEL)?; + Ok(Coalesce::Insert) +} + /// The counter is independent of a physical queue's allocation and survives /// processor stop until the last consumer releases its binding loan. pub(super) struct Hold(Arc); @@ -195,16 +251,21 @@ pub(super) struct Sources { inputs: KVec, publication_waits: KVec, pub(super) sources: KVec, + coalesced_errors: KVec>, #[pin] holds: Mutex>, } impl Sources { - pub(super) fn new(inputs: KVec, sources: KVec, - publication_waits: KVec) -> Result> { + pub(super) fn new( + inputs: KVec, + sources: KVec, + coalesced_errors: KVec>, + publication_waits: KVec, + ) -> Result> { CONVERTED.fetch_add(1, Ordering::Relaxed); if !publication_waits.is_empty() { PENDING.fetch_add(1, Ordering::Relaxed); } Arc::pin_init(pin_init!(Self { - inputs, sources, publication_waits, + inputs, sources, coalesced_errors, publication_waits, holds <- new_mutex!(KVec::new(), "G17 source binding loans"), }), GFP_KERNEL) } @@ -214,6 +275,7 @@ impl Sources { pub(super) fn publication_waits(&self) -> &[Fence] { &self.publication_waits } pub(super) fn check(&self) -> Result { for source in &self.sources { source.submission.source_status()?; } + for submission in &self.coalesced_errors { submission.source_status()?; } Ok(()) } pub(super) fn set_holds(&self, holds: KVec) { diff --git a/tools/asahi/g17-m5-cross-qid-direct-tests.py b/tools/asahi/g17-m5-cross-qid-direct-tests.py index 360d1076b20a4..317b96fda988e 100755 --- a/tools/asahi/g17-m5-cross-qid-direct-tests.py +++ b/tools/asahi/g17-m5-cross-qid-direct-tests.py @@ -85,8 +85,6 @@ def build_c_harness(mutation=None): uint64_t seqno; int status; int refs; - uint64_t pub_key; - uint64_t pub_seq; }}; struct asahi_g17_fence_leaf {{ @@ -111,15 +109,6 @@ def build_c_harness(mutation=None): return f->status; }} -static bool asahi_g17_export_coalesce_key(struct dma_fence *f, u64 *key, u64 *seq) -{{ - if (!f->pub_key) - return false; - *key = f->pub_key; - *seq = f->pub_seq; - return true; -}} - static bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) {{ assert(f1->context == f2->context); @@ -144,8 +133,6 @@ def build_c_harness(mutation=None): chain[i].seqno = order[i]; chain[i].status = 0; chain[i].refs = 1; - chain[i].pub_key = 0; - chain[i].pub_seq = 0; }} struct asahi_g17_fence_leaf out[16]; size_t count = 0; @@ -201,39 +188,28 @@ def build_c_harness(mutation=None): assert(count == 2); release_all(out, count); - /* 5. Distinct-context ExportFences published on the same (epoch, qid) coalesce to newest. */ + /* 5. Distinct-context ExportFences are all preserved so Backend::input_sources() retains + * earlier error dependencies separately from firmware wait barriers. */ struct dma_fence exp[4] = {{ - {{ .context = 101, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 12 }}, - {{ .context = 102, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 19 }}, - {{ .context = 103, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 15 }}, - {{ .context = 104, .seqno = 0, .status = 0, .refs = 1, .pub_key = (8ULL << 8) | 6, .pub_seq = 20 }}, + {{ .context = 101, .seqno = 0, .status = 0, .refs = 1 }}, + {{ .context = 102, .seqno = 0, .status = 0, .refs = 1 }}, + {{ .context = 103, .seqno = 0, .status = 0, .refs = 1 }}, + {{ .context = 104, .seqno = 0, .status = 0, .refs = 1 }}, }}; count = 0; for (int i = 0; i < 4; ++i) assert(collect_leaf(&exp[i], out, 16, &count, true) == 0); - assert(count == 2); - assert(out[0].fence == &exp[1]); - assert(out[1].fence == &exp[3]); + assert(count == 4); release_all(out, count); for (int i = 0; i < 4; ++i) assert(exp[i].refs == 1); - - /* 6. Failed or unpublished ExportFence on same QID is never dropped. */ - struct dma_fence exp_fail = {{ .context = 105, .seqno = 0, .status = -EIO, .refs = 1, .pub_key = (8ULL << 8) | 5, .pub_seq = 10 }}; - struct dma_fence exp_unpub = {{ .context = 106, .seqno = 0, .status = 0, .refs = 1, .pub_key = 0, .pub_seq = 0 }}; - count = 0; - assert(collect_leaf(&exp_fail, out, 16, &count, true) == 0); - assert(collect_leaf(&exp[1], out, 16, &count, true) == 0); - assert(collect_leaf(&exp_unpub, out, 16, &count, true) == 0); - assert(count == 3); - release_all(out, count); - assert(exp_fail.refs == 1 && exp[1].refs == 1 && exp_unpub.refs == 1); return 0; }} ''' def build_rust_harness(mutation=None): + sync_c = (G17 / 'sync_input.c').read_text() sync_rs = (G17 / 'sync_input.rs').read_text() backend_rs = (G17 / 'runtime/backend.rs').read_text() runtime_rs = (G17 / 'runtime.rs').read_text() @@ -247,12 +223,18 @@ def build_rust_harness(mutation=None): 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 ') + coalesce_enum = item(sync_rs, 'pub(super) enum Coalesce').replace('pub(super) ', 'pub ') + coalesce_fn = item(sync_rs, 'pub(super) fn coalesce_source(').replace('pub(super) ', 'pub ') + sources_impl = item(sync_rs, 'impl Sources') + sources_check_fn = item(sources_impl, 'pub(super) fn check(').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(') + complete_fn = item(completion_rs, 'fn complete_with_compute(') + deferred_finish_fn = item(runtime_rs, 'pub(super) fn finish(&mut self)') 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(') @@ -313,6 +295,18 @@ def build_rust_harness(mutation=None): 'self.state.lock().work', 1, ) + elif mutation == 'drop-coalesced-error': + coalesce_fn = coalesce_fn.replace( + 'coalesced_errors.push(earlier, GFP_KERNEL)?;', + 'let _ = earlier;', + 1, + ) + elif mutation == 'skip-coalesced-error-check': + sources_check_fn = sources_check_fn.replace( + 'for submission in &self.coalesced_errors { submission.source_status()?; }', + '', + 1, + ) # Structural checks on production sources. collect_cap_ok = 'const INLINE_LEAVES: usize = 4;' in sync_rs @@ -321,13 +315,18 @@ def build_rust_harness(mutation=None): leaf_loop = input_sources_fn[leaf_loop_start:unchecked_block_start] input_sources_ok = ( 'self.shared.state.lock()' not in leaf_loop + and 'asahi_g17_export_coalesce_key' not in sync_c and ordered_ok( input_sources_fn, 'submission.has_published_epoch(epoch)', + 'sync_input::coalesce_source(', 'if !unchecked.is_empty() {', 'let state = self.shared.state.lock();', 'for idx in unchecked {', + 'sync_input::Sources::new(heads, sources, coalesced_errors, publication_waits)', ) + and 'self.check_source_inputs()' in complete_fn + and 'completion.check_source_inputs()' in deferred_finish_fn ) direct_sources_ok = ( '(has_sources && !m5)' not in compute_direct_fn @@ -378,7 +377,14 @@ def build_rust_harness(mutation=None): and 'self.completion.clear_source_published();' in cancel_fn ) - # Adapt resolve_direct_sources() for host compilation. + # Adapt coalesce_source() and resolve_direct_sources() for host compilation. + host_coalesce = coalesce_fn + host_coalesce = host_coalesce.replace('KVec<', 'Vec<') + host_coalesce = host_coalesce.replace('super::fw::kick::KICK_BARRIERS_MAX', 'KICK_BARRIERS_MAX') + host_coalesce = host_coalesce.replace('coalesced_errors.push(earlier, GFP_KERNEL)?;', 'coalesced_errors.push(earlier);') + host_coalesce = host_coalesce.replace('sources.push(Source { submission }, GFP_KERNEL)?;', 'sources.push(Source { submission });') + host_coalesce = host_coalesce.replace('source_keys.push(pub_key, GFP_KERNEL)?;', 'source_keys.push(pub_key);') + host_resolve = resolve_fn host_resolve = host_resolve.replace('super::port::Port', 'Port') host_resolve = host_resolve.replace('super::sync_input::Sources', 'Sources') @@ -396,8 +402,10 @@ def build_rust_harness(mutation=None): const EBUSY: i32 = -16; const EIO: i32 = -5; +const ENOSPC: i32 = -28; const EOVERFLOW: i32 = -75; const PRODUCER_FAILED: i32 = -5; +const KICK_BARRIERS_MAX: usize = 31; type Result = std::result::Result; {hold_struct} @@ -407,6 +415,10 @@ def build_rust_harness(mutation=None): {hint_struct} {hint_impl} +#[derive(Debug, PartialEq, Eq)] +{coalesce_enum} +{host_coalesce} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct KickDependency {{ qid: u8, @@ -521,12 +533,21 @@ def build_rust_harness(mutation=None): }} struct Source {{ submission: Arc }} -struct Sources {{ sources: Vec }} +struct Sources {{ + sources: Vec, + coalesced_errors: Vec>, +}} impl Sources {{ - fn check(&self) -> Result {{ - for s in &self.sources {{ s.submission.source_status()?; }} - Ok(()) + {sources_check_fn} +}} + +fn complete_consumer(sources: &Sources, mut result: Result) -> Result {{ + if result.is_ok() {{ + if let Err(error) = sources.check() {{ + result = Err(error); + }} }} + result }} struct Port {{ @@ -587,7 +608,7 @@ def build_rust_harness(mutation=None): 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 sources = Sources {{ sources: vec![Source {{ submission: sub.clone() }}], coalesced_errors: Vec::new() }}; let (frontier, native, holds, mask) = backend.resolve_direct_sources(&port, 7, 9, true, &sources).unwrap(); assert_eq!(frontier.items, vec![(42, KickDependency {{ qid: 5, kick: 100 }})]); assert!(native.is_empty()); @@ -626,6 +647,7 @@ def build_rust_harness(mutation=None): }}); let two_same_qid = Sources {{ sources: vec![Source {{ submission: sub.clone() }}, Source {{ submission: sub_later.clone() }}], + coalesced_errors: Vec::new(), }}; let (f_g17p_xctx, n_g17p_xctx, h_g17p_xctx, m_g17p_xctx) = other_ctx_backend.resolve_direct_sources(&port, 7, 9, false, &two_same_qid).unwrap(); @@ -649,7 +671,7 @@ def build_rust_harness(mutation=None): execution_share: 42, readers: readers.clone(), }}); - let same_sources = Sources {{ sources: vec![Source {{ submission: same_sub.clone() }}] }}; + let same_sources = Sources {{ sources: vec![Source {{ submission: same_sub.clone() }}], coalesced_errors: Vec::new() }}; for m5 in [true, false] {{ let (f_same, n_same, h_same, m_same) = backend.resolve_direct_sources(&port, 7, 5, m5, &same_sources).unwrap(); @@ -669,7 +691,7 @@ def build_rust_harness(mutation=None): // 2. Unpublished source -> clean None fallback. let unpub = Submission::new(); - let s_unpub = Sources {{ sources: vec![Source {{ submission: unpub }}] }}; + let s_unpub = Sources {{ sources: vec![Source {{ submission: unpub }}], coalesced_errors: Vec::new() }}; assert!(backend.resolve_direct_sources(&port, 7, 9, true, &s_unpub).is_none()); assert!(backend.resolve_direct_sources(&port, 7, 9, false, &s_unpub).is_none()); @@ -702,7 +724,7 @@ def build_rust_harness(mutation=None): readers: readers.clone(), }}); cancelled.clear_published(); - let s_can = Sources {{ sources: vec![Source {{ submission: cancelled }}] }}; + let s_can = Sources {{ sources: vec![Source {{ submission: cancelled }}], coalesced_errors: Vec::new() }}; assert!(backend.resolve_direct_sources(&port, 7, 9, true, &s_can).is_none()); assert!(backend.resolve_direct_sources(&port, 7, 9, false, &s_can).is_none()); @@ -717,7 +739,7 @@ def build_rust_harness(mutation=None): readers: readers.clone(), }}); failed.error.store(EIO, Ordering::Release); - let s_fail = Sources {{ sources: vec![Source {{ submission: failed }}] }}; + let s_fail = Sources {{ sources: vec![Source {{ submission: failed }}], coalesced_errors: Vec::new() }}; assert!(backend.resolve_direct_sources(&port, 7, 9, true, &s_fail).is_none()); assert!(backend.resolve_direct_sources(&port, 7, 9, false, &s_fail).is_none()); assert_eq!(readers.load(Ordering::Acquire), 0); @@ -725,13 +747,102 @@ def build_rust_harness(mutation=None): // 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 s_ret = Sources {{ sources: vec![Source {{ submission: retired }}], coalesced_errors: Vec::new() }}; let (f_ret, n_ret, h_ret, m_ret) = backend.resolve_direct_sources(&port, 7, 9, false, &s_ret).unwrap(); assert!(f_ret.items.is_empty()); assert!(n_ret.is_empty()); assert!(h_ret.is_empty()); assert_eq!(m_ret, 0); + // 8. Coalesced same-(epoch, QID) exports retain earlier error dependencies: + // when an earlier initially healthy export fails AFTER collection while the retained + // later export completes cleanly, the consumer outcome MUST fail with PRODUCER_FAILED. + for reverse_order in [false, true] {{ + let early = Submission::new(); + let late = Submission::new(); + let other = Submission::new(); + early.set_published(PublishedSource {{ + epoch: 7, + published: 100, + dependency: KickDependency {{ qid: 5, kick: 200 }}, + stamp_va: 0xfeed_0000, + execution_share: 42, + readers: readers.clone(), + }}); + late.set_published(PublishedSource {{ + epoch: 7, + published: 105, + dependency: KickDependency {{ qid: 5, kick: 205 }}, + stamp_va: 0xfeed_0000, + execution_share: 42, + readers: readers.clone(), + }}); + other.set_published(PublishedSource {{ + epoch: 7, + published: 102, + dependency: KickDependency {{ qid: 6, kick: 202 }}, + stamp_va: 0xfeed_1000, + execution_share: 42, + readers: readers.clone(), + }}); + let key_q5 = (8u64 << 8) | 5; + let key_q6 = (8u64 << 8) | 6; + let mut wait_sources = Vec::new(); + let mut keys = Vec::new(); + let mut coalesced_errors = Vec::new(); + let items: Vec<(Arc, Option<(u64, u64)>)> = if reverse_order {{ + vec![ + (late.clone(), Some((key_q5, 105))), + (early.clone(), Some((key_q5, 100))), + (other.clone(), Some((key_q6, 102))), + ] + }} else {{ + vec![ + (early.clone(), Some((key_q5, 100))), + (late.clone(), Some((key_q5, 105))), + (other.clone(), Some((key_q6, 102))), + ] + }}; + for (s, k) in items {{ + coalesce_source(&mut wait_sources, &mut keys, &mut coalesced_errors, s, k).unwrap(); + }} + // Duplicate of already-coalesced early submission is suppressed without growing error list. + assert_eq!( + coalesce_source(&mut wait_sources, &mut keys, &mut coalesced_errors, early.clone(), Some((key_q5, 100))), + Ok(Coalesce::Duplicate) + ); + // Firmware wait list collapsed to 2 (latest on QID 5 + QID 6); earlier QID 5 kept for error checks. + assert_eq!(wait_sources.len(), 2); + assert!(Arc::ptr_eq(&wait_sources[0].submission, &late)); + assert!(Arc::ptr_eq(&wait_sources[1].submission, &other)); + assert_eq!(coalesced_errors.len(), 1); + assert!(Arc::ptr_eq(&coalesced_errors[0], &early)); + + let coalesced = Sources {{ sources: wait_sources, coalesced_errors }}; + // Initially healthy: direct resolution emits only 2 barriers/holds (not 3). + let (f_c, n_c, h_c, m_c) = backend.resolve_direct_sources(&port, 7, 9, true, &coalesced).unwrap(); + assert_eq!(f_c.items.len(), 2); + assert!(n_c.is_empty()); + assert_eq!(h_c.len(), 2); + assert_eq!(m_c, 0b11); + drop(h_c); + assert_eq!(readers.load(Ordering::Acquire), 0); + + // Late error after collection: retained later export and other QID succeed cleanly, + // while earlier coalesced export fails independently. + late.retired.store(true, Ordering::Release); + other.retired.store(true, Ordering::Release); + assert_eq!(complete_consumer(&coalesced, Ok(())), Ok(())); + + early.error.store(EIO, Ordering::Release); + assert_eq!(late.source_status(), Ok(true)); + assert_eq!(coalesced.check(), Err(PRODUCER_FAILED)); + assert_eq!(complete_consumer(&coalesced, Ok(())), Err(PRODUCER_FAILED)); + assert!(backend.resolve_direct_sources(&port, 7, 9, true, &coalesced).is_none()); + assert!(backend.resolve_direct_sources(&port, 7, 9, false, &coalesced).is_none()); + assert_eq!(readers.load(Ordering::Acquire), 0); + }} + println!("PASS g17-m5-cross-qid-direct-tests"); }} ''' @@ -748,7 +859,9 @@ def main(): 'hold-m5-outer-compute-host', 'same-qid-emits-barrier', 'lock-has-published-epoch', - 'lock-same-vm']) + 'lock-same-vm', + 'drop-coalesced-error', + 'skip-coalesced-error-check']) args = parser.parse_args() cc = os.environ.get('HOSTCC', 'cc') rustc = os.environ.get('HOSTRUSTC', 'rustc') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a20d283737988..690833697a695 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -326,7 +326,9 @@ def mutations(flag, names, base, expect=KILL): 'hold-m5-outer-compute-host', 'same-qid-emits-barrier', 'lock-has-published-epoch', - 'lock-same-vm'), []), + 'lock-same-vm', + 'drop-coalesced-error', + 'skip-coalesced-error-check'), []), 'g17-m5-sibling-compute-tests.py': [([], PASS)] + mutations('--mutation', ('fixed-object-ids', 'primary-before-sibling', 'exit-ack-stops-first', 'direct-allows-multi-barrier', diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index 962983e9604e3..2690159730526 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -566,8 +566,6 @@ def extract_function(text, name): int refcount; bool is_chain; bool is_container; - uint64_t pub_key; - uint64_t pub_seq; struct dma_fence *chain_next; struct dma_fence *chain_fence; }; @@ -679,16 +677,6 @@ def extract_function(text, name): } #include "sync_input.h" - -bool asahi_g17_export_coalesce_key(struct dma_fence *fence, u64 *key, u64 *seq) -{ - if (!fence || !fence->pub_key) - return false; - *key = fence->pub_key; - *seq = fence->pub_seq; - return true; -} - #include "sync_input.c" int main(void) @@ -767,7 +755,8 @@ def extract_function(text, name): assert(saw_err && saw_ctx10 && saw_ctx20); } - /* Published ExportFences on distinct contexts sharing (epoch, qid) coalesce to latest seq. */ + /* Distinct-context unsignalled leaves (such as independent ExportFences) are all + * preserved by the C collector so Backend::input_sources() retains error dependencies. */ { struct dma_fence pub_leaves[3]; struct dma_fence pub_chains[3]; @@ -777,8 +766,6 @@ def extract_function(text, name): for (i = 0; i < 3; ++i) { pub_leaves[i].context = (uint64_t)(100 + i); pub_leaves[i].refcount = 1; - pub_leaves[i].pub_key = (7ULL << 8) | 3; - pub_leaves[i].pub_seq = (uint64_t)(i == 1 ? 30 : (i == 0 ? 10 : 20)); pub_chains[i].is_chain = true; pub_chains[i].refcount = 1; @@ -786,9 +773,11 @@ def extract_function(text, name): pub_chains[i].chain_next = (i > 0) ? &pub_chains[i - 1] : NULL; } n = asahi_g17_collect_fences_coalesced(&pub_chains[2], out, 4); - assert(n == 1); - assert(out[0].fence == &pub_leaves[1] && out[0].status == 0); - asahi_g17_put_fence(out[0].fence); + assert(n == 3); + for (i = 0; i < n; ++i) { + assert(out[i].status == 0); + asahi_g17_put_fence(out[i].fence); + } for (i = 0; i < 3; ++i) { assert(pub_leaves[i].refcount == 1); assert(pub_chains[i].refcount == 1);