diff --git a/drivers/gpu/drm/asahi/g17/completion.rs b/drivers/gpu/drm/asahi/g17/completion.rs index dde20605a5f91..b3a10f2c0add2 100644 --- a/drivers/gpu/drm/asahi/g17/completion.rs +++ b/drivers/gpu/drm/asahi/g17/completion.rs @@ -585,6 +585,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); } @@ -682,6 +688,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. @@ -700,6 +707,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 04df5e4aa9fd6..d47b4f2f88fd8 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -222,9 +222,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 @@ -236,6 +247,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. @@ -245,22 +258,38 @@ 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, ) @@ -275,15 +304,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; @@ -294,14 +363,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); } @@ -406,8 +477,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 bb7ae4571b47a..317b86c72f102 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 68470deed93bd..3d83f034ebaa1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -3154,6 +3154,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 b201c3f84f75f..d0ba7aac2cd84 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); } } @@ -1628,6 +1644,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, @@ -1682,7 +1699,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); } } @@ -1824,6 +1848,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; } @@ -1837,6 +1862,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)?; @@ -1903,7 +1935,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(); @@ -1921,6 +1953,7 @@ impl super::Firmware { regs: &self.bridge.regs, port: &self.port, outer, + m5_outer, outer_cursors, effort: &mut self.effort, qids: &mut queues.qids, @@ -2262,17 +2295,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 @@ -2281,11 +2373,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; @@ -2297,7 +2397,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 @@ -2326,6 +2425,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() { @@ -2342,10 +2442,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() => { @@ -2510,8 +2633,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() @@ -2537,10 +2669,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, @@ -2713,6 +2847,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..0f70bc5af053e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -144,11 +144,20 @@ 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; } if status < 0 { return None; } - let leaves = sync_input::collect(input)?; + let leaves = sync_input::collect_coalesced(input)?; for leaf in &leaves { if leaf.status > 0 { continue; } if leaf.status < 0 { return None; } @@ -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 6c68414b49fd4..94034a518a910 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -23,8 +23,14 @@ static int collect_leaf(struct dma_fence *leaf, out[i].status = status; return 0; } - if (coalesce_contexts && status == 0 && out[i].status == 0 && - out[i].fence->context == leaf->context) { + /* + * Coalesce healthy unsignaled leaves sharing a fence context (such + * as multiple points of one timeline chain), keeping only the + * latest seqno. Failed leaves are never coalesced, so errors are + * preserved, and neither is context 0, which names no timeline. + */ + if (coalesce_contexts && status == 0 && leaf->context != 0 && + out[i].status == 0 && out[i].fence->context == leaf->context) { if (dma_fence_is_later(leaf, out[i].fence)) { dma_fence_put(out[i].fence); out[i].fence = dma_fence_get(leaf); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 4d7629a8ffe77..12346580fdb8b 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -12,8 +12,6 @@ pub(crate) struct Leaf { } unsafe extern "C" { - fn asahi_g17_collect_fences(head: *mut bindings::dma_fence, - out: *mut Leaf, capacity: usize) -> 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); @@ -67,13 +65,9 @@ fn collect_with( } } +/// 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(input: &Fence) -> Option> { - collect_with(input, asahi_g17_collect_fences) -} - -/// Like [`collect`], coalescing unsignalled non-error leaves sharing a `dma_fence` context to -/// their latest sequence number so deep timeline chains stay bounded by distinct contexts. pub(crate) fn collect_coalesced(input: &Fence) -> Option> { collect_with(input, asahi_g17_collect_fences_coalesced) } @@ -91,7 +85,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())) @@ -101,9 +95,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, @@ -118,7 +111,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..335144ff23e2b --- /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 (coalesce_contexts && status == 0 && leaf->context != 0 &&', + 'if (coalesce_contexts && 0 &&', + 1, + ) + elif mutation == 'coalesce-failed-leaf': + collect_leaf = collect_leaf.replace( + 'status == 0 && leaf->context != 0 &&\n\t\t out[i].status == 0 && ', + 'leaf->context != 0 &&\n\t\t ', + 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, true) == 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, true) == 0); + assert(collect_leaf(&healthy, out, 16, &count, true) == 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, true) == 0); + for (int i = 0; i < 2; ++i) + assert(collect_leaf(&q1[i], out, 16, &count, true) == 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, true) == 0); + assert(collect_leaf(&z1, out, 16, &count, true) == 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 d3cc87328d502..cecd4fd485e5c 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -296,6 +296,17 @@ def mutations(flag, names, base, expect=KILL): 'skip-epoch-check', 'unconditional-changed-notify', 'skip-generation-bump'), []), + '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-m5-effort-tests.py': [([], PASS)] + mutations('--mutation', ('m5-ignores-bound',), []), 'g17-firmware-selection-tests.py': [([], PASS)],