From 8442bb05b0479036d5f6956d0bc622b9e1d54401 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 14:54:36 -0500 Subject: [PATCH 1/6] drm/asahi: g17: link publications directly to timestamp writers and attach lazily Avoid O(N^2) Publication link cliques and multi-millisecond event-worker stalls when deep timestamp-free chains queue behind pending timestamp writers: 1. Direct timestamp-writer linking (queue/mod.rs, job.rs): track inherited pending timestamp-writer publications in Fences::timestamp_publications and collect only actual timestamp writers (has_outputs()) or failed entries (status < 0) in EnqueueOrdering::build(), collapsing ~18,000 clique links per deeply pipelined frame to O(N). 2. Lazy successor attachment (completion/publication.rs): retain pre-allocated predecessor links on each successor with Link::target = None until finish() runs (preventing Arc self-cycles on unfinished teardown), fast-pathing cleanly settled predecessors via an Acquire load on settled_clean without locking them or draining eager successor lists on the event worker. Signed-off-by: DjDeveloperr --- .../drm/asahi/g17/completion/publication.rs | 209 ++++++- drivers/gpu/drm/asahi/g17/job.rs | 13 +- drivers/gpu/drm/asahi/g17/queue/mod.rs | 146 ++++- .../g17-publication-direct-lazy-tests.py | 556 ++++++++++++++++++ tools/asahi/run-host-tests.py | 4 + 5 files changed, 884 insertions(+), 44 deletions(-) create mode 100755 tools/asahi/g17-publication-direct-lazy-tests.py diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index f1170ee9a4cdf..2e90ce83167da 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -15,7 +15,9 @@ use kernel::{new_mutex, prelude::*, sync::{Arc, Mutex}}; type Links = Option>; struct Link { - target: Arc, + // Populated only when attached to a predecessor's successor list so + // `deferred_links` held on the target itself never forms a self-Arc cycle. + target: Option>, result: Result, next: Links, // Reuse an already-consumed link as a traversal frame instead of recursing @@ -24,6 +26,10 @@ struct Link { } struct State { + // Pre-allocated predecessor links kept on the successor until `finish()` + // runs (or `is_pending()` observes all predecessors settled cleanly). + // Always drained before attaching to any predecessor so no Arc cycle forms. + deferred_links: KVec<(Arc, KBox)>, remaining: usize, result: Option>, predecessor_error: Option, @@ -58,6 +64,10 @@ pub(crate) struct Publication { // deferred predecessor error. Cleared only once no host write or error // remains, and never set again. pending: AtomicBool, + // True once this publication published Ok (timestamps written and fence + // signalled) or settled cleanly without outputs and has not since failed. + // Lets in-order successors bypass locking the predecessor in `finish()`. + settled_clean: AtomicBool, #[pin] state: Mutex, } @@ -74,8 +84,10 @@ impl Publication { status, has_outputs, pending: AtomicBool::new(true), + settled_clean: AtomicBool::new(false), state <- new_mutex!(State { - // Acceptance installs all links before releasing this sentinel. + deferred_links: KVec::new(), + // Acceptance installs deferred links before releasing this sentinel. remaining: 1, result: None, predecessor_error: None, @@ -93,25 +105,100 @@ impl Publication { &self.output } + /// Whether this command itself writes host timestamps. + pub(crate) fn has_outputs(&self) -> bool { + self.has_outputs + } + /// Whether this publication still has an unpublished host timestamp write /// or an unresolved or failed predecessor chain. pub(crate) fn is_pending(&self) -> bool { - self.pending.load(Ordering::Acquire) + if !self.pending.load(Ordering::Acquire) { + return false; + } + if self.has_outputs { + return true; + } + loop { + let (probe, dropped) = { + let mut state = self.state.lock(); + if !self.pending.load(Ordering::Acquire) { + return false; + } + if state.published.is_some() + || state.claimed + || state.deferred_links.is_empty() + { + return self.pending.load(Ordering::Acquire); + } + let unsettled = state + .deferred_links + .iter() + .find(|(pred, _)| !pred.settled_clean.load(Ordering::Acquire)) + .map(|(pred, _)| pred.clone()); + match unsettled { + None => { + let old = core::mem::take(&mut state.deferred_links); + state.upstream_released = true; + self.settled_clean.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + (None, old) + } + Some(pred) if !pred.has_outputs => (Some(pred), KVec::new()), + Some(_) => return true, + } + }; + drop(dropped); + match probe { + Some(pred) => { + if pred.is_pending() { + return true; + } + } + None => return false, + } + } } /// One terminal result, offered separately from its physical-retirement proof. - pub(crate) fn finish(&self, result: Result<[u64; 4]>) { - let ready = { + pub(crate) fn finish(self: &Arc, result: Result<[u64; 4]>) { + let (ready, to_attach) = { let mut state = self.state.lock(); if state.claimed || state.result.is_some() { return; } state.result = Some(result); - state.claim() + let deferred = core::mem::take(&mut state.deferred_links); + if deferred.is_empty() { + (state.claim(), deferred) + } else { + // Hold a sentinel (+1) while checking/attaching predecessors + // off-lock so `remaining` cannot reach 0 prematurely. + state.remaining += 1 + deferred.len(); + (None, deferred) + } }; if let Some(result) = ready { Self::drain(self.publish(result)); + return; } + if !to_attach.is_empty() { + self.attach_deferred(to_attach); + } + } + + fn attach_deferred(self: &Arc, deferred: KVec<(Arc, KBox)>) { + let mut fast_ok = 0usize; + for (predecessor, mut link) in deferred { + if predecessor.settled_clean.load(Ordering::Acquire) { + fast_ok += 1; + drop(link); + } else { + link.target = Some(self.clone()); + predecessor.add_successor(link); + } + } + Self::drain(self.predecessors_done_ok(1 + fast_ok)); } fn publish(&self, result: Result<[u64; 4]>) -> Links { @@ -130,7 +217,10 @@ impl Publication { // fence and aggregate membership have all been published off this lock. state.published = Some(result); if result.is_ok() { + self.settled_clean.store(true, Ordering::Release); self.pending.store(false, Ordering::Release); + } else { + self.settled_clean.store(false, Ordering::Release); } state.successors.take() }; @@ -142,14 +232,11 @@ impl Publication { links } - fn predecessor_done(&self, result: Result) -> Links { + fn predecessors_done_ok(&self, count: usize) -> Links { let (ready, settled) = { let mut state = self.state.lock(); - debug_assert!(state.remaining != 0); - if result.is_err() && state.predecessor_error.is_none() { - state.predecessor_error = Some(PRODUCER_FAILED); - } - state.remaining -= 1; + debug_assert!(state.remaining >= count); + state.remaining -= count; if let Some(ready) = state.claim() { (Some(ready), None) } else if state.remaining == 0 @@ -161,6 +248,7 @@ impl Publication { // no host timestamps, so downstream commands need not wait on // or chain behind its GPU execution. state.upstream_released = true; + self.settled_clean.store(true, Ordering::Release); self.pending.store(false, Ordering::Release); (None, state.successors.take()) } else { @@ -179,6 +267,25 @@ impl Publication { links } + fn predecessor_done(&self, result: Result) -> Links { + if result.is_ok() { + return self.predecessors_done_ok(1); + } + let ready = { + let mut state = self.state.lock(); + debug_assert!(state.remaining != 0); + if state.predecessor_error.is_none() { + state.predecessor_error = Some(PRODUCER_FAILED); + } + state.remaining -= 1; + state.claim() + }; + if let Some(result) = ready { + return self.publish(result); + } + None + } + fn add_successor(&self, mut link: KBox) { let immediate = { let mut state = self.state.lock(); @@ -192,7 +299,9 @@ impl Publication { return; } }; - Self::drain(link.target.predecessor_done(immediate)); + if let Some(target) = link.target.take() { + Self::drain(target.predecessor_done(immediate)); + } } /// Iterative depth-first notification, O(nodes + links), with no stack growth. @@ -201,7 +310,10 @@ impl Publication { loop { if let Some(mut link) = pending.take() { pending = link.next.take(); - let children = link.target.predecessor_done(link.result); + let children = link + .target + .take() + .map_or(None, |target| target.predecessor_done(link.result)); if children.is_some() { link.resume = pending.take(); link.next = frames.take(); @@ -218,8 +330,10 @@ impl Publication { } } -/// Temporary backwards references exist only during fallible setup. Installed -/// links retain the successor only, so closing a queue cannot form an Arc cycle. +/// Pre-allocated predecessor links held until acceptance. While deferred on the +/// successor, each link keeps `target: None` so no Arc cycle can form; once +/// attached to a predecessor on out-of-order completion, the predecessor owns +/// the link and the successor has already dropped its predecessor references. pub(crate) struct Prepared { target: Arc, links: KVec<(Arc, KBox)>, @@ -233,7 +347,7 @@ impl Prepared { let mut links = KVec::with_capacity(predecessors.clone().count(), GFP_KERNEL)?; for predecessor in predecessors { let link = KBox::new(Link { - target: target.clone(), + target: None, result: Ok(()), next: None, resume: None, @@ -245,16 +359,35 @@ impl Prepared { /// Called after all fallible scheduler setup and before any GPU publication. pub(crate) fn activate(self) { - { + let attach_now = { let mut state = self.target.state.lock(); debug_assert!(state.remaining == 1 && !state.claimed); - // The fully allocated link vector bounds this count below usize::MAX. - state.remaining += self.links.len(); - } - for (predecessor, link) in self.links { - predecessor.add_successor(link); + state.remaining -= 1; + if state.result.is_some() { + if self.links.is_empty() { + let ready = state.claim(); + drop(state); + if let Some(result) = ready { + Publication::drain(self.target.publish(result)); + } + return; + } + state.remaining += 1 + self.links.len(); + Some(self.links) + } else { + if self.links.is_empty() && !self.target.has_outputs { + state.upstream_released = true; + self.target.settled_clean.store(true, Ordering::Release); + self.target.pending.store(false, Ordering::Release); + } else { + state.deferred_links = self.links; + } + None + } + }; + if let Some(links) = attach_now { + self.target.attach_deferred(links); } - Publication::drain(self.target.predecessor_done(Ok(()))); } } @@ -398,4 +531,32 @@ mod tests { late.finish(Ok([5, 6, 0, 0])); assert_eq!(fence_status(&late_fence), PRODUCER_FAILED.to_errno()); } + + #[test] + fn in_order_writer_finish_drains_zero_deferred_links() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_lazy"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (producer, prod_fence) = make_pub(&contexts, &status, true); + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + + let mut consumers = KVec::with_capacity(16, GFP_KERNEL).unwrap(); + for _ in 0..16 { + let (cons, fence) = make_pub(&contexts, &status, false); + Prepared::new(cons.clone(), core::iter::once(&producer)) + .unwrap() + .activate(); + consumers.push((cons, fence), GFP_KERNEL).unwrap(); + } + // Deferred links stay on each successor; producer has zero eager successors. + assert!(producer.state.lock().successors.is_none()); + + producer.finish(Ok([1, 2, 0, 0])); + assert!(fence_status(&prod_fence) > 0); + assert!(producer.settled_clean.load(Ordering::Acquire)); + + for (cons, fence) in consumers { + cons.finish(Ok([3, 4, 0, 0])); + assert!(fence_status(&fence) > 0); + } + } } diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 4d6f8678719e6..446480c96bf2a 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -549,6 +549,10 @@ pub(crate) struct Fences { pub(crate) scheduled: Fence, pub(crate) completed: Fence, pub(crate) publication: Option>, + /// Pending host-timestamp writer publications inherited through + /// timestamp-free publication chaining. `None` for commands that write + /// their own timestamps or have no pending timestamp ancestors. + pub(crate) timestamp_publications: Option>>>, pub(crate) owner: Arc, } @@ -680,7 +684,14 @@ impl Scheduler { self.backend.count_backlog(&packet); } job.push(); - Ok(Fences { ready, scheduled, completed, publication: host_publication, owner: packet.completion.clone() }) + Ok(Fences { + ready, + scheduled, + completed, + publication: host_publication, + timestamp_publications: None, + owner: packet.completion.clone(), + }) } } diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 2bb536c65a68a..1cb3329a13286 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -289,7 +289,13 @@ impl Queue { // since the prune above without a publication is not among them, so prune again: any // failure now visible makes it a full scan, and the failure record below has it. self.prune_frontier(index); - let (completion, publication, ordering_host_waits, ordering_firmware_waits) = { + let ( + completion, + publication, + ordering_host_waits, + ordering_firmware_waits, + inherited_publications, + ) = { let ordering = EnqueueOrdering::build( &self.publishers[index], &self.frontiers[other], @@ -313,13 +319,20 @@ impl Queue { )?; let publication = completion .publication() - .map(|target| PreparedPublication::new(target, ordering.predecessors.iter().copied())) + .map(|target| PreparedPublication::new(target, ordering.predecessors.iter())) .transpose()?; + let inherited_publications = + if has_outputs || ordering.predecessors.is_empty() { + None + } else { + Some(Arc::new(ordering.predecessors, GFP_KERNEL)?) + }; ( completion, publication, ordering.host_waits, ordering.firmware_waits, + inherited_publications, ) }; let mut failures: [Option; 2] = [None, None]; @@ -405,11 +418,12 @@ impl Queue { Engine::Render => &mut self.render, Engine::Compute => &mut self.compute, }; - let fences = + let mut fences = scheduler .as_mut() .ok_or(ENODEV)? .enqueue(packet, dependencies, early, publication)?; + fences.timestamp_publications = inherited_publications; self.sequence[index] = order.sequence; if fences.publishes() { self.publishers[index].push_within_capacity(order.sequence, fences.clone())?; @@ -698,6 +712,9 @@ trait FrontierEntry: outstanding::Status { fn pending_publication(&self) -> Option<&Arc> { self.publication().filter(|publication| publication.is_pending()) } + fn timestamp_publications(&self) -> &[Arc] { + &[] + } fn completed(&self) -> &Fence; fn scheduled(&self) -> &Fence; } @@ -711,6 +728,12 @@ impl FrontierEntry for Fences { self.publication.as_ref() } + fn timestamp_publications(&self) -> &[Arc] { + self.timestamp_publications + .as_deref() + .map_or(&[], |v| v.as_slice()) + } + fn completed(&self) -> &Fence { &self.completed } @@ -720,18 +743,56 @@ impl FrontierEntry for Fences { } } -struct EnqueueOrdering<'a> { - predecessors: KVec<&'a Arc>, +fn push_unique_publication( + out: &mut KVec>, + publication: &Arc, +) -> Result { + if !out.iter().any(|existing| Arc::ptr_eq(existing, publication)) { + out.push(publication.clone(), GFP_KERNEL)?; + } + Ok(()) +} + +/// Collect the actual pending host-timestamp writer publications represented by +/// `entry` (deduplicated) rather than linking to every intermediate +/// timestamp-free pass-through node, avoiding an O(N^2) clique of links across +/// deeply pipelined frames. +fn collect_publication_predecessors( + entry: &E, + out: &mut KVec>, +) -> Result { + let Some(pub_ref) = entry.pending_publication() else { + return Ok(()); + }; + if pub_ref.has_outputs() || entry.status() < 0 { + push_unique_publication(out, pub_ref)?; + return Ok(()); + } + let inherited = entry.timestamp_publications(); + if inherited.is_empty() { + push_unique_publication(out, pub_ref)?; + } else { + for ancestor in inherited { + if ancestor.is_pending() { + push_unique_publication(out, ancestor)?; + } + } + } + Ok(()) +} + +struct EnqueueOrdering { + predecessors: KVec>, host_waits: KVec, firmware_waits: KVec<(Fence, Fence)>, } -impl<'a> EnqueueOrdering<'a> { +impl EnqueueOrdering { /// `same_publishers`: the publishers of this command's engine. Only those can be same-engine /// predecessors or host waits, and the rest of that engine's frontier can be deep. fn build( - same_publishers: &'a Outstanding, - other_frontier: &'a Outstanding, + same_publishers: &Outstanding, + other_frontier: &Outstanding, order: Order, engine: Engine, host_waits: bool, @@ -758,8 +819,8 @@ impl<'a> EnqueueOrdering<'a> { for (_, entry) in same_covered.clone() { let status = entry.status(); if status <= 0 { - if let Some(publication) = entry.pending_publication() { - predecessors.push(publication, GFP_KERNEL)?; + if entry.pending_publication().is_some() { + collect_publication_predecessors(entry, &mut predecessors)?; } else if status < 0 { // Failed after `prune_frontier()` without an active // publication: keep its already-signalled error fence. @@ -770,10 +831,8 @@ impl<'a> EnqueueOrdering<'a> { } if cross_chain { for (_, entry) in other_covered.clone() { - if entry.status() <= 0 { - if let Some(publication) = entry.pending_publication() { - predecessors.push(publication, GFP_KERNEL)?; - } + if entry.status() <= 0 && entry.pending_publication().is_some() { + collect_publication_predecessors(entry, &mut predecessors)?; } } } @@ -833,6 +892,7 @@ mod tests { scheduled: Fence, completed: Fence, publication: Option>, + timestamp_publications: KVec>, } impl outstanding::Status for TestEntry { @@ -850,6 +910,10 @@ mod tests { self.publication.as_ref() } + fn timestamp_publications(&self) -> &[Arc] { + self.timestamp_publications.as_slice() + } + fn completed(&self) -> &Fence { &self.completed } @@ -884,6 +948,7 @@ mod tests { scheduled, completed, publication: Some(publication.clone()), + timestamp_publications: KVec::new(), }, Some(publication), ) @@ -895,6 +960,7 @@ mod tests { scheduled, completed, publication: None, + timestamp_publications: KVec::new(), }, None, ) @@ -937,7 +1003,7 @@ mod tests { let (rend_b, pub_b) = test_entry(&contexts, &status, Some(false)); let pub_b = pub_b.unwrap(); - PreparedPublication::new(pub_b.clone(), plan_b.predecessors.iter().copied()) + PreparedPublication::new(pub_b.clone(), plan_b.predecessors.iter()) .unwrap() .activate(); let render_frontier = frontier([(1, rend_b)]); @@ -965,7 +1031,7 @@ mod tests { assert_eq!(plan_c.predecessors.len(), 1); let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, true).unwrap(); - PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter().copied()) + PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter()) .unwrap() .activate(); @@ -1023,7 +1089,7 @@ mod tests { assert_eq!(plan_c.predecessors.len(), 1); let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, false).unwrap(); - PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter().copied()) + PreparedPublication::new(pub_c.clone(), plan_c.predecessors.iter()) .unwrap() .activate(); pub_c.finish(Ok([3, 4, 0, 0])); @@ -1277,7 +1343,7 @@ mod tests { let publication = host_output .publication() .expect("compute with outputs uses ordered publication"); - PreparedPublication::new(publication, plan.predecessors.iter().copied()) + PreparedPublication::new(publication, plan.predecessors.iter()) .unwrap() .activate(); @@ -1336,7 +1402,7 @@ mod tests { let pub_b = host_output_b .publication() .expect("compute consumer behind publication uses ordered publication"); - PreparedPublication::new(pub_b, plan_b.predecessors.iter().copied()) + PreparedPublication::new(pub_b, plan_b.predecessors.iter()) .unwrap() .activate(); @@ -1347,4 +1413,46 @@ mod tests { pub_a.finish(Ok([1, 2, 0, 0])); assert!(fence_status(&comp_b_completed) > 0); } + + #[test] + fn deep_timestamp_free_chain_links_directly_to_writer_not_clique() { + let none = frontier([]); + let contexts = FenceContexts::new(1, c_str!("asahi_q_noclq"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (comp_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + let compute_frontier = frontier([(1, comp_a)]); + + let mut render_publishers: Outstanding = Outstanding::new(0); + render_publishers.reserve(32).unwrap(); + for seq in 1..=32u64 { + let plan = EnqueueOrdering::build( + &render_publishers, + &compute_frontier, + Order { + sequence: seq, + wait_through: [(seq > 1).then_some(seq - 1), Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + assert_eq!(plan.predecessors.len(), 1); + assert!(Arc::ptr_eq(&plan.predecessors[0], &pub_a)); + let (mut entry, pub_r) = test_entry(&contexts, &status, Some(false)); + let pub_r = pub_r.unwrap(); + PreparedPublication::new(pub_r, plan.predecessors.iter()) + .unwrap() + .activate(); + entry.timestamp_publications = plan.predecessors; + render_publishers.push_within_capacity(seq, entry).unwrap(); + } + pub_a.finish(Ok([1, 2, 0, 0])); + } } diff --git a/tools/asahi/g17-publication-direct-lazy-tests.py b/tools/asahi/g17-publication-direct-lazy-tests.py new file mode 100755 index 0000000000000..f0215b7713e03 --- /dev/null +++ b/tools/asahi/g17-publication-direct-lazy-tests.py @@ -0,0 +1,556 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for direct timestamp-writer linking and lazy Publication attachment. + +Verifies: +1. `collect_publication_predecessors()` in `queue/mod.rs` links directly to + pending timestamp writers (`has_outputs()`) and failed entries (`status() < 0`) + via `timestamp_publications`, preventing an O(N^2) clique of intermediate + timestamp-free pass-through links. +2. `Publication` in `completion/publication.rs` defers predecessor attachment + until `finish()` with `target: None` in `deferred_links` (no Arc self-cycle + when dropped unfinished), skips locking cleanly settled predecessors on the + in-order path, and preserves exact out-of-order / failed predecessor + propagation and settlement semantics. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G17 = ROOT / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature): + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def build_harness(mutation=None): + pub_src = (G17 / 'completion/publication.rs').read_text() + q_src = (G17 / 'queue/mod.rs').read_text() + job_src = (G17 / 'job.rs').read_text() + + collect_fn = item(q_src, 'fn collect_publication_predecessors<') + build_fn = item(q_src, 'fn build(') + activate_fn = item(pub_src, 'pub(crate) fn activate(self)') + new_prep_fn = item(pub_src, 'pub(crate) fn new<\'a>(') + finish_fn = item(pub_src, 'pub(crate) fn finish(self: &Arc,') + attach_fn = item(pub_src, 'fn attach_deferred(self: &Arc,') + publish_fn = item(pub_src, 'fn publish(&self, result: Result<[u64; 4]>) -> Links') + is_pending_fn = item(pub_src, 'pub(crate) fn is_pending(&self) -> bool') + + if mutation == 'clique-chain': + collect_fn = collect_fn.replace( + 'if pub_ref.has_outputs() || entry.status() < 0 {', + 'if true {', + 1, + ) + elif mutation == 'skip-failed-status-direct': + collect_fn = collect_fn.replace( + 'if pub_ref.has_outputs() || entry.status() < 0 {', + 'if pub_ref.has_outputs() {', + 1, + ) + elif mutation == 'eager-activate': + activate_fn = activate_fn.replace( + 'state.deferred_links = self.links;', + 'for (p, l) in self.links { p.add_successor(l); }', + 1, + ) + elif mutation == 'cycle-target-some': + new_prep_fn = new_prep_fn.replace( + 'target: None,', + 'target: Some(target.clone()),', + 1, + ) + elif mutation == 'skip-error-clear-settled': + publish_fn = publish_fn.replace( + 'self.settled_clean.store(false, Ordering::Release);', + '', + 1, + ) + elif mutation == 'skip-fast-check': + attach_fn = attach_fn.replace( + 'if predecessor.settled_clean.load(Ordering::Acquire) {', + 'if false {', + 1, + ) + + src_checks = { + 'fences_field': 'pub(crate) timestamp_publications: Option>>>,' in job_src, + 'build_uses_collect': 'collect_publication_predecessors(entry, &mut predecessors)?;' in build_fn, + 'collect_direct_writer': 'if pub_ref.has_outputs() || entry.status() < 0 {' in collect_fn + and 'entry.timestamp_publications()' in collect_fn, + 'lazy_activate': 'state.deferred_links = self.links;' in activate_fn + and 'predecessor.add_successor' not in activate_fn, + 'no_cycle_prep': 'target: None,' in new_prep_fn, + 'fast_settled_check': 'if predecessor.settled_clean.load(Ordering::Acquire) {' in attach_fn, + 'clear_settled_on_err': 'self.settled_clean.store(false, Ordering::Release);' in publish_fn, + 'finish_takes_deferred': 'core::mem::take(&mut state.deferred_links)' in finish_fn, + 'is_pending_settles': 'state.upstream_released = true;' in is_pending_fn, + } + + # Behavioral Rust model mirroring the exact lazy Publication + direct-writer rules. + use_clique = mutation == 'clique-chain' + skip_failed_direct = mutation == 'skip-failed-status-direct' + eager_activate = mutation == 'eager-activate' + cycle_target_some = mutation == 'cycle-target-some' + skip_err_clear = mutation == 'skip-error-clear-settled' + skip_fast = mutation == 'skip-fast-check' + + return f''' +use std::sync::{{Arc, Mutex, Weak, atomic::{{AtomicBool, AtomicI32, AtomicUsize, Ordering}}}}; + +const PRODUCER_FAILED: i32 = -5; +const EIO: i32 = -5; + +type Links = Option>; + +struct Link {{ + target: Option>, + result: Result<(), i32>, + next: Links, + resume: Links, +}} + +struct State {{ + deferred_links: Vec<(Arc, Box)>, + remaining: usize, + result: Option>, + predecessor_error: Option, + claimed: bool, + published: Option>, + upstream_released: bool, + successors: Links, +}} + +impl State {{ + fn claim(&mut self) -> Option> {{ + if self.remaining != 0 || self.claimed {{ + return None; + }} + let result = self.result.take()?; + self.claimed = true; + Some(match (result, self.predecessor_error) {{ + (Ok(()), Some(err)) => Err(err), + (res, _) => res, + }}) + }} +}} + +struct Publication {{ + has_outputs: bool, + pending: AtomicBool, + settled_clean: AtomicBool, + fence_status: AtomicI32, + add_succ_calls: AtomicUsize, + state: Mutex, +}} + +impl Publication {{ + fn new(has_outputs: bool) -> Arc {{ + Arc::new(Self {{ + has_outputs, + pending: AtomicBool::new(true), + settled_clean: AtomicBool::new(false), + fence_status: AtomicI32::new(0), + add_succ_calls: AtomicUsize::new(0), + state: Mutex::new(State {{ + deferred_links: Vec::new(), + remaining: 1, + result: None, + predecessor_error: None, + claimed: false, + published: None, + upstream_released: false, + successors: None, + }}), + }}) + }} + + fn has_outputs(&self) -> bool {{ self.has_outputs }} + + fn is_pending(&self) -> bool {{ + if !self.pending.load(Ordering::Acquire) {{ + return false; + }} + if self.has_outputs {{ + return true; + }} + loop {{ + let (probe, dropped) = {{ + let mut state = self.state.lock().unwrap(); + if !self.pending.load(Ordering::Acquire) {{ + return false; + }} + if state.published.is_some() || state.claimed || state.deferred_links.is_empty() {{ + return self.pending.load(Ordering::Acquire); + }} + let unsettled = state + .deferred_links + .iter() + .find(|(p, _)| !p.settled_clean.load(Ordering::Acquire)) + .map(|(p, _)| p.clone()); + match unsettled {{ + None => {{ + let old = std::mem::take(&mut state.deferred_links); + state.upstream_released = true; + self.settled_clean.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + (None, old) + }} + Some(p) if !p.has_outputs => (Some(p), Vec::new()), + Some(_) => return true, + }} + }}; + drop(dropped); + match probe {{ + Some(p) => {{ + if p.is_pending() {{ + return true; + }} + }} + None => return false, + }} + }} + }} + + fn finish(self: &Arc, result: Result<(), i32>) {{ + let (ready, to_attach) = {{ + let mut state = self.state.lock().unwrap(); + if state.claimed || state.result.is_some() {{ + return; + }} + state.result = Some(result); + let deferred = std::mem::take(&mut state.deferred_links); + if deferred.is_empty() {{ + (state.claim(), deferred) + }} else {{ + state.remaining += 1 + deferred.len(); + (None, deferred) + }} + }}; + if let Some(res) = ready {{ + Self::drain(self.publish(res)); + return; + }} + if !to_attach.is_empty() {{ + self.attach_deferred(to_attach); + }} + }} + + fn attach_deferred(self: &Arc, deferred: Vec<(Arc, Box)>) {{ + let mut fast_ok = 0usize; + for (pred, mut link) in deferred {{ + if !{str(skip_fast).lower()} && pred.settled_clean.load(Ordering::Acquire) {{ + fast_ok += 1; + drop(link); + }} else {{ + link.target = Some(self.clone()); + pred.add_successor(link); + }} + }} + Self::drain(self.predecessors_done_ok(1 + fast_ok)); + }} + + fn publish(&self, result: Result<(), i32>) -> Links {{ + self.fence_status.store(match result {{ Ok(()) => 1, Err(e) => e }}, Ordering::Release); + let mut links = {{ + let mut state = self.state.lock().unwrap(); + state.published = Some(result); + if result.is_ok() {{ + self.settled_clean.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + }} else if !{str(skip_err_clear).lower()} {{ + self.settled_clean.store(false, Ordering::Release); + }} + state.successors.take() + }}; + let mut next = links.as_mut(); + while let Some(link) = next {{ + link.result = result; + next = link.next.as_mut(); + }} + links + }} + + fn predecessors_done_ok(&self, count: usize) -> Links {{ + let (ready, settled) = {{ + let mut state = self.state.lock().unwrap(); + state.remaining -= count; + if let Some(ready) = state.claim() {{ + (Some(ready), None) + }} else if state.remaining == 0 + && !self.has_outputs + && state.predecessor_error.is_none() + && !state.upstream_released + {{ + state.upstream_released = true; + self.settled_clean.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + (None, state.successors.take()) + }} else {{ + (None, None) + }} + }}; + if let Some(res) = ready {{ + return self.publish(res); + }} + let mut links = settled; + let mut next = links.as_mut(); + while let Some(link) = next {{ + link.result = Ok(()); + next = link.next.as_mut(); + }} + links + }} + + fn predecessor_done(&self, result: Result<(), i32>) -> Links {{ + if result.is_ok() {{ + return self.predecessors_done_ok(1); + }} + let ready = {{ + let mut state = self.state.lock().unwrap(); + if state.predecessor_error.is_none() {{ + state.predecessor_error = Some(PRODUCER_FAILED); + }} + state.remaining -= 1; + state.claim() + }}; + if let Some(res) = ready {{ + return self.publish(res); + }} + None + }} + + fn add_successor(&self, mut link: Box) {{ + self.add_succ_calls.fetch_add(1, Ordering::Relaxed); + let immediate = {{ + let mut state = self.state.lock().unwrap(); + if let Some(res) = state.published {{ + res + }} else if state.upstream_released {{ + Ok(()) + }} else {{ + link.next = state.successors.take(); + state.successors = Some(link); + return; + }} + }}; + if let Some(target) = link.target.take() {{ + Self::drain(target.predecessor_done(immediate)); + }} + }} + + fn drain(mut pending: Links) {{ + let mut frames: Links = None; + loop {{ + if let Some(mut link) = pending.take() {{ + pending = link.next.take(); + let children = link + .target + .take() + .and_then(|t| t.predecessor_done(link.result)); + if children.is_some() {{ + link.resume = pending.take(); + link.next = frames.take(); + frames = Some(link); + pending = children; + }} + }} else if let Some(mut frame) = frames.take() {{ + frames = frame.next.take(); + pending = frame.resume.take(); + }} else {{ + break; + }} + }} + }} +}} + +fn activate(target: &Arc, preds: &[Arc]) {{ + let mut links = Vec::with_capacity(preds.len()); + for p in preds {{ + links.push((p.clone(), Box::new(Link {{ + target: if {str(cycle_target_some).lower()} {{ Some(target.clone()) }} else {{ None }}, + result: Ok(()), + next: None, + resume: None, + }}))); + }} + if {str(eager_activate).lower()} {{ + target.state.lock().unwrap().remaining += links.len(); + for (p, mut l) in links {{ + l.target = Some(target.clone()); + p.add_successor(l); + }} + Publication::drain(target.predecessors_done_ok(1)); + return; + }} + let mut state = target.state.lock().unwrap(); + state.remaining -= 1; + if links.is_empty() && !target.has_outputs {{ + state.upstream_released = true; + target.settled_clean.store(true, Ordering::Release); + target.pending.store(false, Ordering::Release); + }} else {{ + state.deferred_links = links; + }} +}} + +struct Entry {{ + pub_node: Arc, + inherited: Vec>, +}} + +fn collect(entry: &Entry, out: &mut Vec>) {{ + if !entry.pub_node.is_pending() {{ + return; + }} + let status = entry.pub_node.fence_status.load(Ordering::Acquire); + let direct = if {str(use_clique).lower()} {{ + true + }} else if {str(skip_failed_direct).lower()} {{ + entry.pub_node.has_outputs() + }} else {{ + entry.pub_node.has_outputs() || status < 0 + }}; + if direct || entry.inherited.is_empty() {{ + if !out.iter().any(|e| Arc::ptr_eq(e, &entry.pub_node)) {{ + out.push(entry.pub_node.clone()); + }} + }} else {{ + for anc in &entry.inherited {{ + if anc.is_pending() && !out.iter().any(|e| Arc::ptr_eq(e, anc)) {{ + out.push(anc.clone()); + }} + }} + }} +}} + +fn main() {{ + // Static contract checks on actual kernel sources. + assert!({str(src_checks['fences_field']).lower()}, "Fences must store timestamp_publications"); + assert!({str(src_checks['build_uses_collect']).lower()}, "EnqueueOrdering::build must use collect_publication_predecessors"); + assert!({str(src_checks['collect_direct_writer']).lower()}, "collect_publication_predecessors must link directly to writers/failed entries"); + assert!({str(src_checks['lazy_activate']).lower()}, "Prepared::activate must defer links instead of eager add_successor"); + assert!({str(src_checks['no_cycle_prep']).lower()}, "Prepared::new must set link.target = None"); + assert!({str(src_checks['fast_settled_check']).lower()}, "attach_deferred must fast-path settled_clean predecessors"); + assert!({str(src_checks['clear_settled_on_err']).lower()}, "publish(Err) must clear settled_clean"); + assert!({str(src_checks['finish_takes_deferred']).lower()}, "finish() must take deferred_links before attaching"); + assert!({str(src_checks['is_pending_settles']).lower()}, "is_pending() must settle clean deferred chains"); + + // 1. 64-deep timestamp-free chain behind 1 writer must stay O(1) links per node (NOT O(N^2) clique). + let writer = Publication::new(true); + activate(&writer, &[]); + let mut entries = vec![Entry {{ pub_node: writer.clone(), inherited: vec![] }}]; + let mut total_links = 0usize; + for _ in 0..64 {{ + let mut preds = Vec::new(); + for e in &entries {{ + collect(e, &mut preds); + }} + assert_eq!(preds.len(), 1, "must link only to direct timestamp writer, got {{}}", preds.len()); + assert!(Arc::ptr_eq(&preds[0], &writer)); + total_links += preds.len(); + let node = Publication::new(false); + activate(&node, &preds); + entries.push(Entry {{ pub_node: node, inherited: preds }}); + }} + assert_eq!(total_links, 64); + assert_eq!(writer.add_succ_calls.load(Ordering::Relaxed), 0, "lazy activate must not lock predecessor"); + + // 2. In-order writer finish drains 0 links and successors skip add_successor completely. + writer.finish(Ok(())); + assert_eq!(writer.fence_status.load(Ordering::Acquire), 1); + for e in &entries[1..] {{ + e.pub_node.finish(Ok(())); + assert_eq!(e.pub_node.fence_status.load(Ordering::Acquire), 1); + }} + assert_eq!(writer.add_succ_calls.load(Ordering::Relaxed), 0, "in-order finish must skip predecessor lock"); + + // 3. Out-of-order consumer finishing before producer fails when producer fails. + let p2 = Publication::new(true); + activate(&p2, &[]); + let c2 = Publication::new(false); + activate(&c2, &[p2.clone()]); + c2.finish(Ok(())); + assert_eq!(c2.fence_status.load(Ordering::Acquire), 0); + p2.finish(Err(EIO)); + assert_eq!(c2.fence_status.load(Ordering::Acquire), PRODUCER_FAILED); + + // 4. Failed timestamp-free entry (status < 0) is linked directly even if inherited writer settled. + let w3 = Publication::new(true); + activate(&w3, &[]); + let mid = Publication::new(false); + activate(&mid, &[w3.clone()]); + let mid_entry = Entry {{ pub_node: mid.clone(), inherited: vec![w3.clone()] }}; + w3.finish(Ok(())); + mid.finish(Err(EIO)); + let mut preds3 = Vec::new(); + collect(&mid_entry, &mut preds3); + assert_eq!(preds3.len(), 1, "failed entry must be linked directly"); + assert!(Arc::ptr_eq(&preds3[0], &mid)); + + // 5. Settled consumer failing later still delivers error to late successor. + let w4 = Publication::new(true); + activate(&w4, &[]); + let cons4 = Publication::new(false); + activate(&cons4, &[w4.clone()]); + w4.finish(Ok(())); + assert!(!cons4.is_pending()); + cons4.finish(Err(EIO)); + let late4 = Publication::new(false); + activate(&late4, &[cons4.clone()]); + late4.finish(Ok(())); + assert_eq!(late4.fence_status.load(Ordering::Acquire), PRODUCER_FAILED); + + // 6. Activated-then-dropped publication without finish() has ZERO Arc cycle! + let w5 = Publication::new(true); + activate(&w5, &[]); + let weak_c5: Weak; + {{ + let c5 = Publication::new(false); + activate(&c5, &[w5.clone()]); + weak_c5 = Arc::downgrade(&c5); + }} + assert!(weak_c5.upgrade().is_none(), "unfinished deferred publication leaked via Arc self-cycle!"); + + println!("PASS g17-publication-direct-lazy-tests"); +}} +''' + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=[ + 'clique-chain', + 'skip-failed-status-direct', + 'eager-activate', + 'cycle-target-some', + 'skip-error-clear-settled', + 'skip-fast-check', + ]) + args = parser.parse_args() + src = build_harness(args.mutation) + rustc = os.environ.get('HOSTRUSTC', 'rustc') + with tempfile.TemporaryDirectory(prefix='g17-pub-lazy-') as td: + rs = Path(td) / 'test.rs' + exe = Path(td) / 'test' + rs.write_text(src) + subprocess.run([rustc, '-O', '-o', str(exe), str(rs)], check=True) + res = subprocess.run([str(exe)]) + sys.exit(res.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 170f2ee9abc4d..6a5f1d13f32f5 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -298,6 +298,10 @@ def mutations(flag, names, base, expect=KILL): 'g17-m5-direct-compute-tests.py': [([], PASS)] + mutations('--mutation', ('no-pre-recovery-drain', 'direct-debits-published', 'scope-allows-reserve'), []), + 'g17-publication-direct-lazy-tests.py': [([], PASS)] + + mutations('--mutation', ('clique-chain', 'skip-failed-status-direct', + 'eager-activate', 'cycle-target-some', + 'skip-error-clear-settled', 'skip-fast-check'), []), 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', From 59ae0e4a4979db5c9050b92701a3a67703565168 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 20:17:31 -0500 Subject: [PATCH 2/6] drm/asahi: g17: keep failed timestamp-free entries in the publication chain Linking a command straight to the timestamp writers of the pending timestamp-free entries it covers dropped those entries from the chain. Such an entry can fail while its writer is still pending (its fence then still reads 0, so it is not linked as failed), or fail after the covering command was enqueued. Either way the covering command signalled success when the writer did, instead of inheriting the failure. Link the newest pending timestamp-free entry of each covered prefix that no newer linked entry covers. Each command records the prefix of its own engine it covers, and a linked entry reaches the entries it covers through its own links, so in-order submission adds one link per engine and no clique. These chain links are kept apart from the inherited writers, so later commands still flatten only to writers. Linked entries that have not retired keep their predecessors deferred, so bound how deep Publication::is_pending() follows them; a probe that stops early reports pending, which only links more. License the publication host test GPL-2.0-only, and test both failure orders and a chain-dropping mutation in KUnit and on the host. Signed-off-by: DjDeveloperr --- .../drm/asahi/g17/completion/publication.rs | 12 +- drivers/gpu/drm/asahi/g17/job.rs | 4 + drivers/gpu/drm/asahi/g17/queue/mod.rs | 191 +++++++++++++++++- .../g17-publication-direct-lazy-tests.py | 119 +++++++++-- tools/asahi/run-host-tests.py | 3 +- 5 files changed, 300 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 2e90ce83167da..c055d63623a35 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -14,6 +14,12 @@ use kernel::{new_mutex, prelude::*, sync::{Arc, Mutex}}; type Links = Option>; +/// How many unsettled timestamp-free predecessors deep `Publication::is_pending()` follows +/// before it answers pending. Commands link the newest pending entry of their prefixes, so an +/// unretired pipeline is a chain of such links; the bound keeps the probe off the stack, and a +/// probe that stops early only leaves the settlement to `finish()`. +const PENDING_PROBE_DEPTH: usize = 4; + struct Link { // Populated only when attached to a predecessor's successor list so // `deferred_links` held on the target itself never forms a self-Arc cycle. @@ -113,6 +119,10 @@ impl Publication { /// Whether this publication still has an unpublished host timestamp write /// or an unresolved or failed predecessor chain. pub(crate) fn is_pending(&self) -> bool { + self.pending_within(PENDING_PROBE_DEPTH) + } + + fn pending_within(&self, depth: usize) -> bool { if !self.pending.load(Ordering::Acquire) { return false; } @@ -151,7 +161,7 @@ impl Publication { drop(dropped); match probe { Some(pred) => { - if pred.is_pending() { + if depth == 0 || pred.pending_within(depth - 1) { return true; } } diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 446480c96bf2a..b0c469c1b10b5 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -553,6 +553,9 @@ pub(crate) struct Fences { /// timestamp-free publication chaining. `None` for commands that write /// their own timestamps or have no pending timestamp ancestors. pub(crate) timestamp_publications: Option>>>, + /// The prefix of its own engine this command covers (`Order::wait_through`). A later + /// command that links this command's publication reaches that prefix through it. + pub(crate) covers: Option, pub(crate) owner: Arc, } @@ -690,6 +693,7 @@ impl Scheduler { completed, publication: host_publication, timestamp_publications: None, + covers: None, owner: packet.completion.clone(), }) } diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 1cb3329a13286..ece0bbb673fd3 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -312,14 +312,19 @@ impl Queue { guard, destinations, engine == Engine::Compute, - !ordering.predecessors.is_empty(), + !ordering.predecessors.is_empty() || !ordering.chain.is_empty(), self.backend.feed(), sources.clone(), self.usage.clone(), )?; let publication = completion .publication() - .map(|target| PreparedPublication::new(target, ordering.predecessors.iter())) + .map(|target| { + PreparedPublication::new( + target, + ordering.predecessors.iter().chain(ordering.chain.iter()), + ) + }) .transpose()?; let inherited_publications = if has_outputs || ordering.predecessors.is_empty() { @@ -424,6 +429,7 @@ impl Queue { .ok_or(ENODEV)? .enqueue(packet, dependencies, early, publication)?; fences.timestamp_publications = inherited_publications; + fences.covers = order.wait_through[index]; self.sequence[index] = order.sequence; if fences.publishes() { self.publishers[index].push_within_capacity(order.sequence, fences.clone())?; @@ -715,6 +721,9 @@ trait FrontierEntry: outstanding::Status { fn timestamp_publications(&self) -> &[Arc] { &[] } + fn covers(&self) -> Option { + None + } fn completed(&self) -> &Fence; fn scheduled(&self) -> &Fence; } @@ -734,6 +743,10 @@ impl FrontierEntry for Fences { .map_or(&[], |v| v.as_slice()) } + fn covers(&self) -> Option { + self.covers + } + fn completed(&self) -> &Fence { &self.completed } @@ -781,8 +794,57 @@ fn collect_publication_predecessors( Ok(()) } +/// The pending publications of one covered prefix, oldest first, with the prefix each entry +/// covers on its own engine. +struct PublicationChain(KVec<(u64, Option, Arc)>); + +impl PublicationChain { + fn new() -> Self { + Self(KVec::new()) + } + + fn note( + &mut self, + sequence: u64, + entry: &E, + publication: &Arc, + ) -> Result { + self.0 + .push((sequence, entry.covers(), publication.clone()), GFP_KERNEL)?; + Ok(()) + } + + /// Link every pending timestamp-free entry that no newer pending entry covers, into `out` + /// unless `direct` already has it. + /// + /// `collect_publication_predecessors()` links such an entry's timestamp writers instead of + /// the entry, but the entry can still fail (or already has, with its fence unsignalled) + /// while they are pending, and that error must reach this command. A newer pending entry + /// reaches the entries it covers through its own links, so in-order submission adds one + /// link per engine instead of one per pending entry. These links are kept apart from the + /// inherited writers, so the chain never widens into them. + fn link(self, direct: &[Arc], out: &mut KVec>) -> Result { + let mut covered = None; + for (sequence, covers, publication) in self.0.iter().rev() { + if !Order::contains(covered, *sequence) + && !publication.has_outputs() + && !direct + .iter() + .any(|existing| Arc::ptr_eq(existing, publication)) + { + push_unique_publication(out, publication)?; + } + covered = covered.max(*covers); + } + Ok(()) + } +} + struct EnqueueOrdering { predecessors: KVec>, + /// Pending timestamp-free entries linked so their failures reach this command + /// ([`PublicationChain::link`]); not inherited by later commands. + chain: KVec>, host_waits: KVec, firmware_waits: KVec<(Fence, Fence)>, } @@ -813,14 +875,17 @@ impl EnqueueOrdering { // `add_successor()` still delivers that failure immediately instead of // letting the successor signal success. let mut predecessors = KVec::new(); + let mut chained = KVec::new(); let mut host = KVec::new(); let mut firmware = KVec::new(); if same_chain { - for (_, entry) in same_covered.clone() { + let mut chain = PublicationChain::new(); + for (sequence, entry) in same_covered.clone() { let status = entry.status(); if status <= 0 { - if entry.pending_publication().is_some() { + if let Some(publication) = entry.pending_publication() { collect_publication_predecessors(entry, &mut predecessors)?; + chain.note(sequence, entry, publication)?; } else if status < 0 { // Failed after `prune_frontier()` without an active // publication: keep its already-signalled error fence. @@ -828,13 +893,19 @@ impl EnqueueOrdering { } } } + chain.link(&predecessors, &mut chained)?; } if cross_chain { - for (_, entry) in other_covered.clone() { - if entry.status() <= 0 && entry.pending_publication().is_some() { - collect_publication_predecessors(entry, &mut predecessors)?; + let mut chain = PublicationChain::new(); + for (sequence, entry) in other_covered.clone() { + if entry.status() <= 0 { + if let Some(publication) = entry.pending_publication() { + collect_publication_predecessors(entry, &mut predecessors)?; + chain.note(sequence, entry, publication)?; + } } } + chain.link(&predecessors, &mut chained)?; } if same_wait { @@ -873,6 +944,7 @@ impl EnqueueOrdering { Ok(Self { predecessors, + chain: chained, host_waits: host, firmware_waits: firmware, }) @@ -893,6 +965,7 @@ mod tests { completed: Fence, publication: Option>, timestamp_publications: KVec>, + covers: Option, } impl outstanding::Status for TestEntry { @@ -914,6 +987,10 @@ mod tests { self.timestamp_publications.as_slice() } + fn covers(&self) -> Option { + self.covers + } + fn completed(&self) -> &Fence { &self.completed } @@ -949,6 +1026,7 @@ mod tests { completed, publication: Some(publication.clone()), timestamp_publications: KVec::new(), + covers: None, }, Some(publication), ) @@ -961,6 +1039,7 @@ mod tests { completed, publication: None, timestamp_publications: KVec::new(), + covers: None, }, None, ) @@ -1429,6 +1508,7 @@ mod tests { let mut render_publishers: Outstanding = Outstanding::new(0); render_publishers.reserve(32).unwrap(); + let mut last: Option> = None; for seq in 1..=32u64 { let plan = EnqueueOrdering::build( &render_publishers, @@ -1443,16 +1523,107 @@ mod tests { true, ) .unwrap(); + // The writer, plus the newest pending render, which covers the older ones. assert_eq!(plan.predecessors.len(), 1); assert!(Arc::ptr_eq(&plan.predecessors[0], &pub_a)); + assert_eq!(plan.chain.len(), usize::from(seq > 1)); + if let Some(newest) = plan.chain.first() { + assert!(Arc::ptr_eq(newest, last.as_ref().unwrap())); + } let (mut entry, pub_r) = test_entry(&contexts, &status, Some(false)); let pub_r = pub_r.unwrap(); - PreparedPublication::new(pub_r, plan.predecessors.iter()) - .unwrap() - .activate(); + PreparedPublication::new( + pub_r.clone(), + plan.predecessors.iter().chain(plan.chain.iter()), + ) + .unwrap() + .activate(); entry.timestamp_publications = plan.predecessors; + entry.covers = (seq > 1).then_some(seq - 1); render_publishers.push_within_capacity(seq, entry).unwrap(); + last = Some(pub_r); + } + pub_a.finish(Ok([1, 2, 0, 0])); + } + + /// A timestamp-free render B whose writer A is still pending fails. A later render C that + /// covers B links A directly, and must still inherit B's failure instead of signalling + /// success when A succeeds, whether B fails before or after C is enqueued. + fn failed_timestamp_free_entry_fails_covering_successor(fail_before_enqueue: bool) { + let contexts = FenceContexts::new(1, c_str!("asahi_q_tsfail"), TEST_KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + let (comp_a, pub_a) = test_entry(&contexts, &status, Some(true)); + let pub_a = pub_a.unwrap(); + PreparedPublication::new(pub_a.clone(), core::iter::empty()) + .unwrap() + .activate(); + let compute_frontier = frontier([(1, comp_a)]); + + let mut render_publishers: Outstanding = Outstanding::new(0); + render_publishers.reserve(1).unwrap(); + let plan_b = EnqueueOrdering::build( + &render_publishers, + &compute_frontier, + Order { + sequence: 1, + wait_through: [None, Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + let (mut entry_b, pub_b) = test_entry(&contexts, &status, Some(false)); + let pub_b = pub_b.unwrap(); + PreparedPublication::new(pub_b.clone(), plan_b.predecessors.iter()) + .unwrap() + .activate(); + entry_b.timestamp_publications = plan_b.predecessors; + render_publishers.push_within_capacity(1, entry_b).unwrap(); + if fail_before_enqueue { + pub_b.finish(Err(EIO)); + } + + let plan_c = EnqueueOrdering::build( + &render_publishers, + &compute_frontier, + Order { + sequence: 2, + wait_through: [Some(1), Some(1)], + tiling_wait_through: [None, None], + }, + Engine::Render, + false, + true, + ) + .unwrap(); + assert!(plan_c.predecessors.iter().any(|p| Arc::ptr_eq(p, &pub_a))); + assert!(plan_c.chain.iter().any(|p| Arc::ptr_eq(p, &pub_b))); + let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, true).unwrap(); + PreparedPublication::new( + pub_c.clone(), + plan_c.predecessors.iter().chain(plan_c.chain.iter()), + ) + .unwrap() + .activate(); + if !fail_before_enqueue { + pub_b.finish(Err(EIO)); } + pub_c.finish(Ok([5, 6, 0, 0])); + assert_eq!(fence_status(&fence_c), 0); pub_a.finish(Ok([1, 2, 0, 0])); + assert!(fence_status(&fence_c) < 0); + } + + #[test] + fn timestamp_free_entry_failed_before_enqueue_fails_covering_successor() { + failed_timestamp_free_entry_fails_covering_successor(true); + } + + #[test] + fn timestamp_free_entry_failing_after_enqueue_fails_covering_successor() { + failed_timestamp_free_entry_fails_covering_successor(false); } } diff --git a/tools/asahi/g17-publication-direct-lazy-tests.py b/tools/asahi/g17-publication-direct-lazy-tests.py index f0215b7713e03..348107dfdfe20 100755 --- a/tools/asahi/g17-publication-direct-lazy-tests.py +++ b/tools/asahi/g17-publication-direct-lazy-tests.py @@ -1,12 +1,15 @@ #!/usr/bin/env python3 -# SPDX-License-Identifier: GPL-2.0-only OR MIT +# SPDX-License-Identifier: GPL-2.0-only """Host test for direct timestamp-writer linking and lazy Publication attachment. Verifies: 1. `collect_publication_predecessors()` in `queue/mod.rs` links directly to pending timestamp writers (`has_outputs()`) and failed entries (`status() < 0`) via `timestamp_publications`, preventing an O(N^2) clique of intermediate - timestamp-free pass-through links. + timestamp-free pass-through links, while `PublicationChain::link()` keeps the + newest uncovered pending timestamp-free entry linked so its failure still + reaches a covering successor, whether it fails before or after the successor + is enqueued. 2. `Publication` in `completion/publication.rs` defers predecessor attachment until `finish()` with `target: None` in `deferred_links` (no Arc self-cycle when dropped unfinished), skips locking cleanly settled predecessors on the @@ -47,7 +50,8 @@ def build_harness(mutation=None): finish_fn = item(pub_src, 'pub(crate) fn finish(self: &Arc,') attach_fn = item(pub_src, 'fn attach_deferred(self: &Arc,') publish_fn = item(pub_src, 'fn publish(&self, result: Result<[u64; 4]>) -> Links') - is_pending_fn = item(pub_src, 'pub(crate) fn is_pending(&self) -> bool') + is_pending_fn = item(pub_src, 'fn pending_within(&self, depth: usize) -> bool') + chain_fn = item(q_src, 'fn link(self, direct: &[Arc], out: &mut KVec>)') if mutation == 'clique-chain': collect_fn = collect_fn.replace( @@ -79,6 +83,8 @@ def build_harness(mutation=None): '', 1, ) + elif mutation == 'drop-chain-link': + build_fn = build_fn.replace('chain.link(&predecessors, &mut chained)?;', '', 2) elif mutation == 'skip-fast-check': attach_fn = attach_fn.replace( 'if predecessor.settled_clean.load(Ordering::Acquire) {', @@ -98,6 +104,10 @@ def build_harness(mutation=None): 'clear_settled_on_err': 'self.settled_clean.store(false, Ordering::Release);' in publish_fn, 'finish_takes_deferred': 'core::mem::take(&mut state.deferred_links)' in finish_fn, 'is_pending_settles': 'state.upstream_released = true;' in is_pending_fn, + 'bounded_probe': 'pred.pending_within(depth - 1)' in is_pending_fn, + 'covers_field': 'pub(crate) covers: Option,' in job_src, + 'chain_links': build_fn.count('chain.link(&predecessors, &mut chained)?;') == 2 + and 'Order::contains(covered, *sequence)' in chain_fn, } # Behavioral Rust model mirroring the exact lazy Publication + direct-writer rules. @@ -107,12 +117,14 @@ def build_harness(mutation=None): cycle_target_some = mutation == 'cycle-target-some' skip_err_clear = mutation == 'skip-error-clear-settled' skip_fast = mutation == 'skip-fast-check' + drop_chain = mutation == 'drop-chain-link' return f''' use std::sync::{{Arc, Mutex, Weak, atomic::{{AtomicBool, AtomicI32, AtomicUsize, Ordering}}}}; const PRODUCER_FAILED: i32 = -5; const EIO: i32 = -5; +const PENDING_PROBE_DEPTH: usize = 4; type Links = Option>; @@ -181,6 +193,10 @@ def build_harness(mutation=None): fn has_outputs(&self) -> bool {{ self.has_outputs }} fn is_pending(&self) -> bool {{ + self.pending_within(PENDING_PROBE_DEPTH) + }} + + fn pending_within(&self, depth: usize) -> bool {{ if !self.pending.load(Ordering::Acquire) {{ return false; }} @@ -216,7 +232,7 @@ def build_harness(mutation=None): drop(dropped); match probe {{ Some(p) => {{ - if p.is_pending() {{ + if depth == 0 || p.pending_within(depth - 1) {{ return true; }} }} @@ -408,10 +424,46 @@ def build_harness(mutation=None): }} struct Entry {{ + seq: u64, + covers: Option, pub_node: Arc, inherited: Vec>, }} +fn has(out: &[Arc], p: &Arc) -> bool {{ + out.iter().any(|e| Arc::ptr_eq(e, p)) +}} + +// EnqueueOrdering::build() over one covered prefix: the flattened writers (inherited by later +// commands) and the chain links (PublicationChain::link), kept apart. +fn build(prefix: &[Entry]) -> (Vec>, Vec>) {{ + let mut direct = Vec::new(); + let mut pending = Vec::new(); + for e in prefix {{ + if e.pub_node.fence_status.load(Ordering::Acquire) > 0 || !e.pub_node.is_pending() {{ + continue; + }} + collect(e, &mut direct); + pending.push(e); + }} + let mut chain = Vec::new(); + if !{str(drop_chain).lower()} {{ + let mut covered: Option = None; + for e in pending.iter().rev() {{ + let inside = covered.is_some_and(|c| e.seq != 0 && e.seq <= c); + if !inside && !e.pub_node.has_outputs() && !has(&direct, &e.pub_node) && !has(&chain, &e.pub_node) {{ + chain.push(e.pub_node.clone()); + }} + covered = covered.max(e.covers); + }} + }} + (direct, chain) +}} + +fn all(direct: &[Arc], chain: &[Arc]) -> Vec> {{ + direct.iter().chain(chain.iter()).cloned().collect() +}} + fn collect(entry: &Entry, out: &mut Vec>) {{ if !entry.pub_node.is_pending() {{ return; @@ -448,25 +500,27 @@ def build_harness(mutation=None): assert!({str(src_checks['clear_settled_on_err']).lower()}, "publish(Err) must clear settled_clean"); assert!({str(src_checks['finish_takes_deferred']).lower()}, "finish() must take deferred_links before attaching"); assert!({str(src_checks['is_pending_settles']).lower()}, "is_pending() must settle clean deferred chains"); + assert!({str(src_checks['bounded_probe']).lower()}, "is_pending() must bound its predecessor probe"); + assert!({str(src_checks['covers_field']).lower()}, "Fences must record the prefix it covers"); + assert!({str(src_checks['chain_links']).lower()}, "EnqueueOrdering::build must chain both covered prefixes"); - // 1. 64-deep timestamp-free chain behind 1 writer must stay O(1) links per node (NOT O(N^2) clique). + // 1. 64-deep timestamp-free chain behind 1 writer must stay O(1) links per node (NOT O(N^2) clique): + // the writer plus the newest pending entry, which covers the older ones. let writer = Publication::new(true); activate(&writer, &[]); - let mut entries = vec![Entry {{ pub_node: writer.clone(), inherited: vec![] }}]; + let mut entries = vec![Entry {{ seq: 1, covers: None, pub_node: writer.clone(), inherited: vec![] }}]; let mut total_links = 0usize; - for _ in 0..64 {{ - let mut preds = Vec::new(); - for e in &entries {{ - collect(e, &mut preds); - }} - assert_eq!(preds.len(), 1, "must link only to direct timestamp writer, got {{}}", preds.len()); + for seq in 2..=65u64 {{ + let (preds, chain) = build(&entries); + assert_eq!(preds.len(), 1, "must flatten to the direct timestamp writer, got {{}}", preds.len()); assert!(Arc::ptr_eq(&preds[0], &writer)); - total_links += preds.len(); + assert!(chain.len() <= 1, "chain must link only the newest pending entry, got {{}}", chain.len()); + total_links += preds.len() + chain.len(); let node = Publication::new(false); - activate(&node, &preds); - entries.push(Entry {{ pub_node: node, inherited: preds }}); + activate(&node, &all(&preds, &chain)); + entries.push(Entry {{ seq, covers: Some(seq - 1), pub_node: node, inherited: preds }}); }} - assert_eq!(total_links, 64); + assert!(total_links <= 2 * 64, "links {{}}", total_links); assert_eq!(writer.add_succ_calls.load(Ordering::Relaxed), 0, "lazy activate must not lock predecessor"); // 2. In-order writer finish drains 0 links and successors skip add_successor completely. @@ -493,7 +547,7 @@ def build_harness(mutation=None): activate(&w3, &[]); let mid = Publication::new(false); activate(&mid, &[w3.clone()]); - let mid_entry = Entry {{ pub_node: mid.clone(), inherited: vec![w3.clone()] }}; + let mid_entry = Entry {{ seq: 2, covers: Some(1), pub_node: mid.clone(), inherited: vec![w3.clone()] }}; w3.finish(Ok(())); mid.finish(Err(EIO)); let mut preds3 = Vec::new(); @@ -525,6 +579,36 @@ def build_harness(mutation=None): }} assert!(weak_c5.upgrade().is_none(), "unfinished deferred publication leaked via Arc self-cycle!"); + // 7./8. Timestamp-free B fails while its writer A is still pending (its fence still reads 0). + // C covers B; it flattens B to A, and must still inherit B's failure when A succeeds, + // whether B fails before (7) or after (8) C is enqueued. + for fail_before in [true, false] {{ + let a = Publication::new(true); + activate(&a, &[]); + let b = Publication::new(false); + activate(&b, &[a.clone()]); + let mut prefix = vec![ + Entry {{ seq: 1, covers: None, pub_node: a.clone(), inherited: vec![] }}, + Entry {{ seq: 2, covers: Some(1), pub_node: b.clone(), inherited: vec![a.clone()] }}, + ]; + if fail_before {{ + b.finish(Err(EIO)); + assert_eq!(b.fence_status.load(Ordering::Acquire), 0); + }} + let (preds, chain) = build(&prefix); + let c = Publication::new(true); + activate(&c, &all(&preds, &chain)); + prefix.clear(); + if !fail_before {{ + b.finish(Err(EIO)); + }} + c.finish(Ok(())); + a.finish(Ok(())); + assert_eq!(b.fence_status.load(Ordering::Acquire), EIO); + assert_eq!(c.fence_status.load(Ordering::Acquire), PRODUCER_FAILED, + "covering successor must inherit B's failure (fail_before={{}})", fail_before); + }} + println!("PASS g17-publication-direct-lazy-tests"); }} ''' @@ -539,6 +623,7 @@ def main(): 'cycle-target-some', 'skip-error-clear-settled', 'skip-fast-check', + 'drop-chain-link', ]) args = parser.parse_args() src = build_harness(args.mutation) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 6a5f1d13f32f5..62472ea210ffb 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -301,7 +301,8 @@ def mutations(flag, names, base, expect=KILL): 'g17-publication-direct-lazy-tests.py': [([], PASS)] + mutations('--mutation', ('clique-chain', 'skip-failed-status-direct', 'eager-activate', 'cycle-target-some', - 'skip-error-clear-settled', 'skip-fast-check'), []), + 'skip-error-clear-settled', 'skip-fast-check', + 'drop-chain-link'), []), 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', From 22a4e9c8826725368c60618bc8a298dd357ee827 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 20:25:40 -0500 Subject: [PATCH 3/6] drm/asahi: g17: end the publication probe on failed predecessors Publication::is_pending() settles a deferred timestamp-free publication once its predecessors are clean. Two cases were missing: A predecessor that released its successors early and then failed has pending and settled_clean both clear. The probe asked it, got "not pending", found it still unsettled and asked again, forever. Consume that link as terminal instead and keep PRODUCER_FAILED for finish(), so the probe ends and the failure is still published. Settling through the probe dropped the predecessor links but left successors that had already attached queued, so a successor that finished before the settlement waited for this command's own completion. Release them off-lock, as predecessors_done_ok() does. Add host tests for both cases. Signed-off-by: DjDeveloperr --- .../drm/asahi/g17/completion/publication.rs | 88 ++++++++---- .../g17-publication-direct-lazy-tests.py | 131 +++++++++++++++--- tools/asahi/run-host-tests.py | 3 +- 3 files changed, 178 insertions(+), 44 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index c055d63623a35..76d3d81716dab 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -14,6 +14,16 @@ use kernel::{new_mutex, prelude::*, sync::{Arc, Mutex}}; type Links = Option>; +/// One step of `Publication::pending_within()`, taken under the state lock and finished off it. +enum Probe { + /// A failed predecessor's link, consumed. + Consumed((Arc, KBox)), + /// Settled clean: the dropped predecessor links and the successors to release. + Settled(KVec<(Arc, KBox)>, Links), + /// Ask this unsettled timestamp-free predecessor. + Next(Arc), +} + /// How many unsettled timestamp-free predecessors deep `Publication::is_pending()` follows /// before it answers pending. Commands link the newest pending entry of their prefixes, so an /// unretired pipeline is a chain of such links; the bound keeps the probe off the stack, and a @@ -130,7 +140,7 @@ impl Publication { return true; } loop { - let (probe, dropped) = { + let step = { let mut state = self.state.lock(); if !self.pending.load(Ordering::Acquire) { return false; @@ -141,35 +151,71 @@ impl Publication { { return self.pending.load(Ordering::Acquire); } - let unsettled = state + let failed = state .deferred_links .iter() - .find(|(pred, _)| !pred.settled_clean.load(Ordering::Acquire)) - .map(|(pred, _)| pred.clone()); - match unsettled { - None => { - let old = core::mem::take(&mut state.deferred_links); - state.upstream_released = true; - self.settled_clean.store(true, Ordering::Release); - self.pending.store(false, Ordering::Release); - (None, old) + .position(|(pred, _)| pred.failed_after_release()); + if let Some(index) = failed { + // Terminal and settles nothing: consume the link and keep the failure for + // `finish()`, so the probe never retries this predecessor. + if state.predecessor_error.is_none() { + state.predecessor_error = Some(PRODUCER_FAILED); + } + Probe::Consumed(state.deferred_links.swap_remove(index)) + } else { + let unsettled = state + .deferred_links + .iter() + .find(|(pred, _)| !pred.settled_clean.load(Ordering::Acquire)) + .map(|(pred, _)| pred.clone()); + match unsettled { + None if state.predecessor_error.is_none() => { + let old = core::mem::take(&mut state.deferred_links); + state.upstream_released = true; + self.settled_clean.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + Probe::Settled(old, state.successors.take()) + } + // Pending until `finish()` publishes the consumed failure. + None => return true, + Some(pred) if !pred.has_outputs => Probe::Next(pred), + Some(_) => return true, } - Some(pred) if !pred.has_outputs => (Some(pred), KVec::new()), - Some(_) => return true, } }; - drop(dropped); - match probe { - Some(pred) => { + match step { + Probe::Consumed(link) => drop(link), + Probe::Settled(old, successors) => { + drop(old); + // Successors that attached before this settlement are released here, as + // `predecessors_done_ok()` releases them. + Self::drain(Self::released_ok(successors)); + return false; + } + Probe::Next(pred) => { if depth == 0 || pred.pending_within(depth - 1) { return true; } } - None => return false, } } } + /// Released its successors as upstream-clean, and then published a failure. + fn failed_after_release(&self) -> bool { + !self.pending.load(Ordering::Acquire) && !self.settled_clean.load(Ordering::Acquire) + } + + /// Mark successor links released by a clean upstream settlement. + fn released_ok(mut links: Links) -> Links { + let mut next = links.as_mut(); + while let Some(link) = next { + link.result = Ok(()); + next = link.next.as_mut(); + } + links + } + /// One terminal result, offered separately from its physical-retirement proof. pub(crate) fn finish(self: &Arc, result: Result<[u64; 4]>) { let (ready, to_attach) = { @@ -268,13 +314,7 @@ impl Publication { if let Some(result) = ready { return self.publish(result); } - let mut links = settled; - let mut next = links.as_mut(); - while let Some(link) = next { - link.result = Ok(()); - next = link.next.as_mut(); - } - links + Self::released_ok(settled) } fn predecessor_done(&self, result: Result) -> Links { diff --git a/tools/asahi/g17-publication-direct-lazy-tests.py b/tools/asahi/g17-publication-direct-lazy-tests.py index 348107dfdfe20..77235be4802a7 100755 --- a/tools/asahi/g17-publication-direct-lazy-tests.py +++ b/tools/asahi/g17-publication-direct-lazy-tests.py @@ -85,6 +85,10 @@ def build_harness(mutation=None): ) elif mutation == 'drop-chain-link': build_fn = build_fn.replace('chain.link(&predecessors, &mut chained)?;', '', 2) + elif mutation == 'retry-failed-pred': + is_pending_fn = is_pending_fn.replace('.position(|(pred, _)| pred.failed_after_release())', '.position(|_| false)', 1) + elif mutation == 'keep-attached-successors': + is_pending_fn = is_pending_fn.replace('Probe::Settled(old, state.successors.take())', 'Probe::Settled(old, None)', 1) elif mutation == 'skip-fast-check': attach_fn = attach_fn.replace( 'if predecessor.settled_clean.load(Ordering::Acquire) {', @@ -105,6 +109,10 @@ def build_harness(mutation=None): 'finish_takes_deferred': 'core::mem::take(&mut state.deferred_links)' in finish_fn, 'is_pending_settles': 'state.upstream_released = true;' in is_pending_fn, 'bounded_probe': 'pred.pending_within(depth - 1)' in is_pending_fn, + 'consume_failed': '.position(|(pred, _)| pred.failed_after_release())' in is_pending_fn + and 'Probe::Consumed(state.deferred_links.swap_remove(index))' in is_pending_fn, + 'release_attached': 'Probe::Settled(old, state.successors.take())' in is_pending_fn + and 'Self::drain(Self::released_ok(successors));' in is_pending_fn, 'covers_field': 'pub(crate) covers: Option,' in job_src, 'chain_links': build_fn.count('chain.link(&predecessors, &mut chained)?;') == 2 and 'Order::contains(covered, *sequence)' in chain_fn, @@ -118,6 +126,8 @@ def build_harness(mutation=None): skip_err_clear = mutation == 'skip-error-clear-settled' skip_fast = mutation == 'skip-fast-check' drop_chain = mutation == 'drop-chain-link' + retry_failed = mutation == 'retry-failed-pred' + keep_attached = mutation == 'keep-attached-successors' return f''' use std::sync::{{Arc, Mutex, Weak, atomic::{{AtomicBool, AtomicI32, AtomicUsize, Ordering}}}}; @@ -128,6 +138,12 @@ def build_harness(mutation=None): type Links = Option>; +enum Probe {{ + Consumed((Arc, Box)), + Settled(Vec<(Arc, Box)>, Links), + Next(Arc), +}} + struct Link {{ target: Option>, result: Result<(), i32>, @@ -204,7 +220,7 @@ def build_harness(mutation=None): return true; }} loop {{ - let (probe, dropped) = {{ + let step = {{ let mut state = self.state.lock().unwrap(); if !self.pending.load(Ordering::Acquire) {{ return false; @@ -212,35 +228,66 @@ def build_harness(mutation=None): if state.published.is_some() || state.claimed || state.deferred_links.is_empty() {{ return self.pending.load(Ordering::Acquire); }} - let unsettled = state - .deferred_links - .iter() - .find(|(p, _)| !p.settled_clean.load(Ordering::Acquire)) - .map(|(p, _)| p.clone()); - match unsettled {{ - None => {{ - let old = std::mem::take(&mut state.deferred_links); - state.upstream_released = true; - self.settled_clean.store(true, Ordering::Release); - self.pending.store(false, Ordering::Release); - (None, old) + let failed = if {str(retry_failed).lower()} {{ + None + }} else {{ + state.deferred_links.iter().position(|(p, _)| p.failed_after_release()) + }}; + if let Some(index) = failed {{ + if state.predecessor_error.is_none() {{ + state.predecessor_error = Some(PRODUCER_FAILED); + }} + Probe::Consumed(state.deferred_links.swap_remove(index)) + }} else {{ + let unsettled = state + .deferred_links + .iter() + .find(|(p, _)| !p.settled_clean.load(Ordering::Acquire)) + .map(|(p, _)| p.clone()); + match unsettled {{ + None if state.predecessor_error.is_none() => {{ + let old = std::mem::take(&mut state.deferred_links); + state.upstream_released = true; + self.settled_clean.store(true, Ordering::Release); + self.pending.store(false, Ordering::Release); + let succ = if {str(keep_attached).lower()} {{ None }} else {{ state.successors.take() }}; + Probe::Settled(old, succ) + }} + None => return true, + Some(p) if !p.has_outputs => Probe::Next(p), + Some(_) => return true, }} - Some(p) if !p.has_outputs => (Some(p), Vec::new()), - Some(_) => return true, }} }}; - drop(dropped); - match probe {{ - Some(p) => {{ + match step {{ + Probe::Consumed(link) => drop(link), + Probe::Settled(old, successors) => {{ + drop(old); + Self::drain(Self::released_ok(successors)); + return false; + }} + Probe::Next(p) => {{ if depth == 0 || p.pending_within(depth - 1) {{ return true; }} }} - None => return false, }} }} }} + fn failed_after_release(&self) -> bool {{ + !self.pending.load(Ordering::Acquire) && !self.settled_clean.load(Ordering::Acquire) + }} + + fn released_ok(mut links: Links) -> Links {{ + let mut next = links.as_mut(); + while let Some(link) = next {{ + link.result = Ok(()); + next = link.next.as_mut(); + }} + links + }} + fn finish(self: &Arc, result: Result<(), i32>) {{ let (ready, to_attach) = {{ let mut state = self.state.lock().unwrap(); @@ -501,6 +548,8 @@ def build_harness(mutation=None): assert!({str(src_checks['finish_takes_deferred']).lower()}, "finish() must take deferred_links before attaching"); assert!({str(src_checks['is_pending_settles']).lower()}, "is_pending() must settle clean deferred chains"); assert!({str(src_checks['bounded_probe']).lower()}, "is_pending() must bound its predecessor probe"); + assert!({str(src_checks['consume_failed']).lower()}, "is_pending() must consume a predecessor that failed after releasing"); + assert!({str(src_checks['release_attached']).lower()}, "early settlement must release attached successors"); assert!({str(src_checks['covers_field']).lower()}, "Fences must record the prefix it covers"); assert!({str(src_checks['chain_links']).lower()}, "EnqueueOrdering::build must chain both covered prefixes"); @@ -609,7 +658,49 @@ def build_harness(mutation=None): "covering successor must inherit B's failure (fail_before={{}})", fail_before); }} + // 9. B released its successors early (writer A clean) and then failed. P, still deferred on B, + // must end its probe (not retry B forever) and publish B's failure. + {{ + let a = Publication::new(true); + activate(&a, &[]); + let b = Publication::new(false); + activate(&b, &[a.clone()]); + let p = Publication::new(false); + activate(&p, &[b.clone()]); + a.finish(Ok(())); + assert!(!b.is_pending(), "B settles once A published cleanly"); + b.finish(Err(EIO)); + assert!(b.failed_after_release()); + let probe = p.clone(); + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || {{ let _ = tx.send(probe.is_pending()); }}); + let pending = rx + .recv_timeout(std::time::Duration::from_secs(5)) + .expect("probe of a predecessor that failed after releasing never ended"); + assert!(pending, "a consumed failure keeps P pending until finish()"); + p.finish(Ok(())); + assert_eq!(p.fence_status.load(Ordering::Acquire), PRODUCER_FAILED); + }} + + // 10. S finished and attached to B before B settled. B settling through is_pending() must + // release S then, not when some unrelated completion finishes B. + {{ + let a = Publication::new(true); + activate(&a, &[]); + let b = Publication::new(false); + activate(&b, &[a.clone()]); + let s = Publication::new(true); + activate(&s, &[b.clone()]); + s.finish(Ok(())); + a.finish(Ok(())); + assert_eq!(s.fence_status.load(Ordering::Acquire), 0); + assert!(!b.is_pending()); + assert_eq!(s.fence_status.load(Ordering::Acquire), 1, + "successor attached before an early settlement must be released by it"); + }} + println!("PASS g17-publication-direct-lazy-tests"); + std::process::exit(0); }} ''' @@ -624,6 +715,8 @@ def main(): 'skip-error-clear-settled', 'skip-fast-check', 'drop-chain-link', + 'retry-failed-pred', + 'keep-attached-successors', ]) args = parser.parse_args() src = build_harness(args.mutation) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 62472ea210ffb..6cf12bf7235f3 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -302,7 +302,8 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('clique-chain', 'skip-failed-status-direct', 'eager-activate', 'cycle-target-some', 'skip-error-clear-settled', 'skip-fast-check', - 'drop-chain-link'), []), + 'drop-chain-link', 'retry-failed-pred', + 'keep-attached-successors'), []), 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', From e73586f89ef879db2ecf2bbb549a0b1ed541c379 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 20:35:51 -0500 Subject: [PATCH 4/6] drm/asahi: g17: subscribe a deferred publication once a waiter queues on it A timestamp-free publication links itself to its predecessors only at its own finish(), or when a probe settles it. A successor that finished first and queued on it therefore stayed unsignalled after the predecessors published, until that command retired or something probed it; a fence waiter never probes. When a waiter queues on an unfinished deferred timestamp-free publication, subscribe it to its predecessors right away, holding a sentinel as finish() does, so their completion settles it and releases the waiter. Subscriptions this starts in turn are bounded by the probe depth; a publication past the bound links at its own finish(), or when a probe settles it and releases what queued on it. Require in the host test that the waiter signals on the writer's completion alone, and cover the bounded chain. Signed-off-by: DjDeveloperr --- .../drm/asahi/g17/completion/publication.rs | 65 ++++++++---- .../g17-publication-direct-lazy-tests.py | 99 +++++++++++++++---- tools/asahi/run-host-tests.py | 2 +- 3 files changed, 128 insertions(+), 38 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 76d3d81716dab..67d6956fae54d 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -24,10 +24,11 @@ enum Probe { Next(Arc), } -/// How many unsettled timestamp-free predecessors deep `Publication::is_pending()` follows -/// before it answers pending. Commands link the newest pending entry of their prefixes, so an -/// unretired pipeline is a chain of such links; the bound keeps the probe off the stack, and a -/// probe that stops early only leaves the settlement to `finish()`. +/// How many unsettled timestamp-free predecessors deep `Publication::is_pending()` probes, and +/// how many deferred predecessors in turn one waiter subscribes (`Publication::add_successor()`). +/// Commands link the newest pending entry of their prefixes, so an unretired pipeline is a chain +/// of such links; the bound keeps both off the stack. A probe that stops early answers pending, +/// and a publication past the bound links itself at its own `finish()`. const PENDING_PROBE_DEPTH: usize = 4; struct Link { @@ -239,11 +240,17 @@ impl Publication { return; } if !to_attach.is_empty() { - self.attach_deferred(to_attach); + self.attach_deferred(to_attach, PENDING_PROBE_DEPTH); } } - fn attach_deferred(self: &Arc, deferred: KVec<(Arc, KBox)>) { + /// Link this publication to its deferred predecessors; the caller holds one sentinel in + /// `remaining` for this. + fn attach_deferred( + self: &Arc, + deferred: KVec<(Arc, KBox)>, + depth: usize, + ) { let mut fast_ok = 0usize; for (predecessor, mut link) in deferred { if predecessor.settled_clean.load(Ordering::Acquire) { @@ -251,7 +258,7 @@ impl Publication { drop(link); } else { link.target = Some(self.clone()); - predecessor.add_successor(link); + predecessor.add_successor(link, depth); } } Self::drain(self.predecessors_done_ok(1 + fast_ok)); @@ -336,22 +343,44 @@ impl Publication { None } - fn add_successor(&self, mut link: KBox) { - let immediate = { + /// Deliver `link` now if this publication has settled, or queue it until it does. + /// + /// An unfinished timestamp-free publication keeps its predecessor links deferred until its + /// own `finish()`. Once a waiter queues on it, subscribe it to those predecessors (at most + /// `depth` deferred publications deep), so their completion settles it and releases the + /// waiter without waiting for this command's own completion. + fn add_successor(self: &Arc, mut link: KBox, depth: usize) { + let deferred = { let mut state = self.state.lock(); - if let Some(result) = state.published { - result + let immediate = if let Some(result) = state.published { + Some(result) } else if state.upstream_released { - Ok(()) + Some(Ok(())) } else { - link.next = state.successors.take(); - state.successors = Some(link); + None + }; + if let Some(result) = immediate { + drop(state); + if let Some(target) = link.target.take() { + Self::drain(target.predecessor_done(result)); + } + return; + } + link.next = state.successors.take(); + state.successors = Some(link); + if depth == 0 + || self.has_outputs + || state.result.is_some() + || state.deferred_links.is_empty() + { return; } + let deferred = core::mem::take(&mut state.deferred_links); + // Hold a sentinel (+1) while attaching off-lock, as `finish()` does. + state.remaining += 1 + deferred.len(); + deferred }; - if let Some(target) = link.target.take() { - Self::drain(target.predecessor_done(immediate)); - } + self.attach_deferred(deferred, depth - 1); } /// Iterative depth-first notification, O(nodes + links), with no stack growth. @@ -436,7 +465,7 @@ impl Prepared { } }; if let Some(links) = attach_now { - self.target.attach_deferred(links); + self.target.attach_deferred(links, PENDING_PROBE_DEPTH); } } } diff --git a/tools/asahi/g17-publication-direct-lazy-tests.py b/tools/asahi/g17-publication-direct-lazy-tests.py index 77235be4802a7..ae637e1366618 100755 --- a/tools/asahi/g17-publication-direct-lazy-tests.py +++ b/tools/asahi/g17-publication-direct-lazy-tests.py @@ -48,10 +48,11 @@ def build_harness(mutation=None): activate_fn = item(pub_src, 'pub(crate) fn activate(self)') new_prep_fn = item(pub_src, 'pub(crate) fn new<\'a>(') finish_fn = item(pub_src, 'pub(crate) fn finish(self: &Arc,') - attach_fn = item(pub_src, 'fn attach_deferred(self: &Arc,') + attach_fn = item(pub_src, 'fn attach_deferred(') publish_fn = item(pub_src, 'fn publish(&self, result: Result<[u64; 4]>) -> Links') is_pending_fn = item(pub_src, 'fn pending_within(&self, depth: usize) -> bool') chain_fn = item(q_src, 'fn link(self, direct: &[Arc], out: &mut KVec>)') + add_succ_fn = item(pub_src, 'fn add_successor(self: &Arc, mut link: KBox, depth: usize)') if mutation == 'clique-chain': collect_fn = collect_fn.replace( @@ -89,6 +90,8 @@ def build_harness(mutation=None): is_pending_fn = is_pending_fn.replace('.position(|(pred, _)| pred.failed_after_release())', '.position(|_| false)', 1) elif mutation == 'keep-attached-successors': is_pending_fn = is_pending_fn.replace('Probe::Settled(old, state.successors.take())', 'Probe::Settled(old, None)', 1) + elif mutation == 'no-subscribe': + add_succ_fn = add_succ_fn.replace('let deferred = core::mem::take(&mut state.deferred_links);', 'let deferred = KVec::new();', 1) elif mutation == 'skip-fast-check': attach_fn = attach_fn.replace( 'if predecessor.settled_clean.load(Ordering::Acquire) {', @@ -111,6 +114,8 @@ def build_harness(mutation=None): 'bounded_probe': 'pred.pending_within(depth - 1)' in is_pending_fn, 'consume_failed': '.position(|(pred, _)| pred.failed_after_release())' in is_pending_fn and 'Probe::Consumed(state.deferred_links.swap_remove(index))' in is_pending_fn, + 'subscribe_deferred': 'let deferred = core::mem::take(&mut state.deferred_links);' in add_succ_fn + and 'self.attach_deferred(deferred, depth - 1);' in add_succ_fn, 'release_attached': 'Probe::Settled(old, state.successors.take())' in is_pending_fn and 'Self::drain(Self::released_ok(successors));' in is_pending_fn, 'covers_field': 'pub(crate) covers: Option,' in job_src, @@ -127,6 +132,7 @@ def build_harness(mutation=None): skip_fast = mutation == 'skip-fast-check' drop_chain = mutation == 'drop-chain-link' retry_failed = mutation == 'retry-failed-pred' + no_subscribe = mutation == 'no-subscribe' keep_attached = mutation == 'keep-attached-successors' return f''' @@ -308,11 +314,11 @@ def build_harness(mutation=None): return; }} if !to_attach.is_empty() {{ - self.attach_deferred(to_attach); + self.attach_deferred(to_attach, PENDING_PROBE_DEPTH); }} }} - fn attach_deferred(self: &Arc, deferred: Vec<(Arc, Box)>) {{ + fn attach_deferred(self: &Arc, deferred: Vec<(Arc, Box)>, depth: usize) {{ let mut fast_ok = 0usize; for (pred, mut link) in deferred {{ if !{str(skip_fast).lower()} && pred.settled_clean.load(Ordering::Acquire) {{ @@ -320,7 +326,7 @@ def build_harness(mutation=None): drop(link); }} else {{ link.target = Some(self.clone()); - pred.add_successor(link); + pred.add_successor(link, depth); }} }} Self::drain(self.predecessors_done_ok(1 + fast_ok)); @@ -396,23 +402,39 @@ def build_harness(mutation=None): None }} - fn add_successor(&self, mut link: Box) {{ + fn add_successor(self: &Arc, mut link: Box, depth: usize) {{ self.add_succ_calls.fetch_add(1, Ordering::Relaxed); - let immediate = {{ + let deferred = {{ let mut state = self.state.lock().unwrap(); - if let Some(res) = state.published {{ - res + let immediate = if let Some(res) = state.published {{ + Some(res) }} else if state.upstream_released {{ - Ok(()) + Some(Ok(())) }} else {{ - link.next = state.successors.take(); - state.successors = Some(link); + None + }}; + if let Some(res) = immediate {{ + drop(state); + if let Some(target) = link.target.take() {{ + Self::drain(target.predecessor_done(res)); + }} return; }} + link.next = state.successors.take(); + state.successors = Some(link); + if {str(no_subscribe).lower()} + || depth == 0 + || self.has_outputs + || state.result.is_some() + || state.deferred_links.is_empty() + {{ + return; + }} + let deferred = std::mem::take(&mut state.deferred_links); + state.remaining += 1 + deferred.len(); + deferred }}; - if let Some(target) = link.target.take() {{ - Self::drain(target.predecessor_done(immediate)); - }} + self.attach_deferred(deferred, depth - 1); }} fn drain(mut pending: Links) {{ @@ -454,7 +476,7 @@ def build_harness(mutation=None): target.state.lock().unwrap().remaining += links.len(); for (p, mut l) in links {{ l.target = Some(target.clone()); - p.add_successor(l); + p.add_successor(l, PENDING_PROBE_DEPTH); }} Publication::drain(target.predecessors_done_ok(1)); return; @@ -550,6 +572,7 @@ def build_harness(mutation=None): assert!({str(src_checks['bounded_probe']).lower()}, "is_pending() must bound its predecessor probe"); assert!({str(src_checks['consume_failed']).lower()}, "is_pending() must consume a predecessor that failed after releasing"); assert!({str(src_checks['release_attached']).lower()}, "early settlement must release attached successors"); + assert!({str(src_checks['subscribe_deferred']).lower()}, "a queued waiter must subscribe a deferred publication to its predecessors"); assert!({str(src_checks['covers_field']).lower()}, "Fences must record the prefix it covers"); assert!({str(src_checks['chain_links']).lower()}, "EnqueueOrdering::build must chain both covered prefixes"); @@ -682,8 +705,8 @@ def build_harness(mutation=None): assert_eq!(p.fence_status.load(Ordering::Acquire), PRODUCER_FAILED); }} - // 10. S finished and attached to B before B settled. B settling through is_pending() must - // release S then, not when some unrelated completion finishes B. + // 10. S finished and attached to deferred B while B's writer A was pending. A's completion + // alone must settle B and release S: no probe of B and no completion of B in between. {{ let a = Publication::new(true); activate(&a, &[]); @@ -692,11 +715,48 @@ def build_harness(mutation=None): let s = Publication::new(true); activate(&s, &[b.clone()]); s.finish(Ok(())); - a.finish(Ok(())); assert_eq!(s.fence_status.load(Ordering::Acquire), 0); + a.finish(Ok(())); + assert_eq!(s.fence_status.load(Ordering::Acquire), 1, + "a waiter on a deferred publication must be released by its writer's completion"); + b.finish(Ok(())); + }} + + // 11. A successor attached before a probe settles B is released by that settlement too. + {{ + let a = Publication::new(true); + activate(&a, &[]); + let b = Publication::new(false); + activate(&b, &[a.clone()]); + a.finish(Ok(())); + let s = Publication::new(true); + activate(&s, &[b.clone()]); + s.finish(Ok(())); + assert_eq!(s.fence_status.load(Ordering::Acquire), 1, + "a waiter on a deferred publication whose writer already published must not wait"); assert!(!b.is_pending()); + }} + + // 12. A waiter subscribes at most PENDING_PROBE_DEPTH deferred publications deep. Past that, + // the deepest subscribed node stays queued on a deferred one; a probe that settles it must + // release that queued link, and the chain above it, up to the waiter. + {{ + let w = Publication::new(true); + activate(&w, &[]); + let mut chain = vec![w.clone()]; + for _ in 0..PENDING_PROBE_DEPTH + 2 {{ + let n = Publication::new(false); + activate(&n, &[chain.last().unwrap().clone()]); + chain.push(n); + }} + let s = Publication::new(true); + activate(&s, &[chain.last().unwrap().clone()]); + s.finish(Ok(())); + w.finish(Ok(())); + let deep = chain[2].clone(); + assert!(!deep.is_pending()); assert_eq!(s.fence_status.load(Ordering::Acquire), 1, - "successor attached before an early settlement must be released by it"); + "settling past the subscription bound must release the queued chain up to the waiter"); }} println!("PASS g17-publication-direct-lazy-tests"); @@ -717,6 +777,7 @@ def main(): 'drop-chain-link', 'retry-failed-pred', 'keep-attached-successors', + 'no-subscribe', ]) args = parser.parse_args() src = build_harness(args.mutation) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 6cf12bf7235f3..11974e8f76664 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -303,7 +303,7 @@ def mutations(flag, names, base, expect=KILL): 'eager-activate', 'cycle-target-some', 'skip-error-clear-settled', 'skip-fast-check', 'drop-chain-link', 'retry-failed-pred', - 'keep-attached-successors'), []), + 'keep-attached-successors', 'no-subscribe'), []), 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', From 69fd36afe7c4151591b049530b8e5f92f27df8b3 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 20:42:17 -0500 Subject: [PATCH 5/6] drm/asahi: g17: subscribe the whole deferred chain without a depth limit Subscribing a deferred publication when a waiter queues on it stopped four publications deep. Past that the intermediaries stayed deferred, so the writer's completion did not signal the waiter, and an intermediary failing later made that same waiter report the error. Subscribe iteratively instead: add_successor() only queues the link and reports whether the publication needs subscribing, and subscribe() walks a stack threaded through State::subscribe_next, linking each queued publication and pushing the deferred ones it reaches in turn. It neither recurses nor allocates, and each publication is queued at most once. Require in the host test that the writer's completion alone signals the waiter through 4, 5 and 6 deferred intermediaries, and that a later intermediary failure leaves it unchanged; both fail with the old depth limit. Signed-off-by: DjDeveloperr --- .../drm/asahi/g17/completion/publication.rs | 122 +++++++++----- .../g17-publication-direct-lazy-tests.py | 154 ++++++++++++------ tools/asahi/run-host-tests.py | 3 +- 3 files changed, 184 insertions(+), 95 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 67d6956fae54d..b32598fd06544 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -24,11 +24,10 @@ enum Probe { Next(Arc), } -/// How many unsettled timestamp-free predecessors deep `Publication::is_pending()` probes, and -/// how many deferred predecessors in turn one waiter subscribes (`Publication::add_successor()`). -/// Commands link the newest pending entry of their prefixes, so an unretired pipeline is a chain -/// of such links; the bound keeps both off the stack. A probe that stops early answers pending, -/// and a publication past the bound links itself at its own `finish()`. +/// How many unsettled timestamp-free predecessors deep `Publication::is_pending()` follows +/// before it answers pending. Commands link the newest pending entry of their prefixes, so an +/// unretired pipeline is a chain of such links; the bound keeps the probe off the stack, and a +/// probe that stops early only leaves the settlement to the links. const PENDING_PROBE_DEPTH: usize = 4; struct Link { @@ -56,6 +55,9 @@ struct State { // still has no result of its own; successors have already been released. upstream_released: bool, successors: Links, + // Queued once for `Publication::subscribe()`, and the next publication on that stack. + subscribe_queued: bool, + subscribe_next: Option>, } impl State { @@ -112,6 +114,8 @@ impl Publication { published: None, upstream_released: false, successors: None, + subscribe_queued: false, + subscribe_next: None, }, "G17 host timestamp publication"), }), GFP_KERNEL, @@ -240,16 +244,24 @@ impl Publication { return; } if !to_attach.is_empty() { - self.attach_deferred(to_attach, PENDING_PROBE_DEPTH); + self.attach_deferred(to_attach); } } /// Link this publication to its deferred predecessors; the caller holds one sentinel in /// `remaining` for this. - fn attach_deferred( + fn attach_deferred(self: &Arc, deferred: KVec<(Arc, KBox)>) { + let mut stack = None; + self.link_deferred(deferred, &mut stack); + Self::subscribe(stack); + } + + /// [`Self::attach_deferred`], pushing each deferred predecessor that a link now waits on + /// onto `stack` for [`Self::subscribe`]. + fn link_deferred( self: &Arc, deferred: KVec<(Arc, KBox)>, - depth: usize, + stack: &mut Option>, ) { let mut fast_ok = 0usize; for (predecessor, mut link) in deferred { @@ -258,12 +270,41 @@ impl Publication { drop(link); } else { link.target = Some(self.clone()); - predecessor.add_successor(link, depth); + if predecessor.add_successor(link) { + predecessor.state.lock().subscribe_next = stack.take(); + *stack = Some(predecessor); + } } } Self::drain(self.predecessors_done_ok(1 + fast_ok)); } + /// Link every publication on `stack`, and every deferred one it reaches in turn, to its + /// predecessors, so the writer's completion alone settles a waiter's whole chain however + /// deep the unretired pipeline is. The stack is threaded through `State::subscribe_next`, + /// so this neither recurses nor allocates. + fn subscribe(mut stack: Option>) { + while let Some(node) = stack.take() { + let deferred = { + let mut state = node.state.lock(); + stack = state.subscribe_next.take(); + if state.result.is_some() + || state.published.is_some() + || state.upstream_released + || state.deferred_links.is_empty() + { + // `finish()` or a probe linked or settled it meanwhile. + continue; + } + let deferred = core::mem::take(&mut state.deferred_links); + // Hold a sentinel (+1) while linking off-lock, as `finish()` does. + state.remaining += 1 + deferred.len(); + deferred + }; + node.link_deferred(deferred, &mut stack); + } + } + fn publish(&self, result: Result<[u64; 4]>) -> Links { if let Err(error) = result { // Inherited failure is visible to the client without inventing a @@ -345,42 +386,33 @@ impl Publication { /// Deliver `link` now if this publication has settled, or queue it until it does. /// - /// An unfinished timestamp-free publication keeps its predecessor links deferred until its - /// own `finish()`. Once a waiter queues on it, subscribe it to those predecessors (at most - /// `depth` deferred publications deep), so their completion settles it and releases the - /// waiter without waiting for this command's own completion. - fn add_successor(self: &Arc, mut link: KBox, depth: usize) { - let deferred = { - let mut state = self.state.lock(); - let immediate = if let Some(result) = state.published { - Some(result) - } else if state.upstream_released { - Some(Ok(())) - } else { - None - }; - if let Some(result) = immediate { - drop(state); - if let Some(target) = link.target.take() { - Self::drain(target.predecessor_done(result)); - } - return; - } - link.next = state.successors.take(); - state.successors = Some(link); - if depth == 0 - || self.has_outputs - || state.result.is_some() - || state.deferred_links.is_empty() - { - return; - } - let deferred = core::mem::take(&mut state.deferred_links); - // Hold a sentinel (+1) while attaching off-lock, as `finish()` does. - state.remaining += 1 + deferred.len(); - deferred + /// Returns whether this publication must now be subscribed to its predecessors + /// ([`Self::subscribe`]): an unfinished timestamp-free publication keeps them deferred + /// until its own `finish()`, and the queued waiter must not wait for that. + fn add_successor(&self, mut link: KBox) -> bool { + let mut state = self.state.lock(); + let immediate = if let Some(result) = state.published { + Some(result) + } else if state.upstream_released { + Some(Ok(())) + } else { + None }; - self.attach_deferred(deferred, depth - 1); + if let Some(result) = immediate { + drop(state); + if let Some(target) = link.target.take() { + Self::drain(target.predecessor_done(result)); + } + return false; + } + link.next = state.successors.take(); + state.successors = Some(link); + let subscribe = !self.has_outputs + && !state.subscribe_queued + && state.result.is_none() + && !state.deferred_links.is_empty(); + state.subscribe_queued |= subscribe; + subscribe } /// Iterative depth-first notification, O(nodes + links), with no stack growth. @@ -465,7 +497,7 @@ impl Prepared { } }; if let Some(links) = attach_now { - self.target.attach_deferred(links, PENDING_PROBE_DEPTH); + self.target.attach_deferred(links); } } } diff --git a/tools/asahi/g17-publication-direct-lazy-tests.py b/tools/asahi/g17-publication-direct-lazy-tests.py index ae637e1366618..ff94977c1af3e 100755 --- a/tools/asahi/g17-publication-direct-lazy-tests.py +++ b/tools/asahi/g17-publication-direct-lazy-tests.py @@ -52,7 +52,9 @@ def build_harness(mutation=None): publish_fn = item(pub_src, 'fn publish(&self, result: Result<[u64; 4]>) -> Links') is_pending_fn = item(pub_src, 'fn pending_within(&self, depth: usize) -> bool') chain_fn = item(q_src, 'fn link(self, direct: &[Arc], out: &mut KVec>)') - add_succ_fn = item(pub_src, 'fn add_successor(self: &Arc, mut link: KBox, depth: usize)') + add_succ_fn = item(pub_src, 'fn add_successor(&self, mut link: KBox) -> bool') + subscribe_fn = item(pub_src, 'fn subscribe(mut stack: Option>)') + link_fn = item(pub_src, 'fn link_deferred(') if mutation == 'clique-chain': collect_fn = collect_fn.replace( @@ -91,9 +93,9 @@ def build_harness(mutation=None): elif mutation == 'keep-attached-successors': is_pending_fn = is_pending_fn.replace('Probe::Settled(old, state.successors.take())', 'Probe::Settled(old, None)', 1) elif mutation == 'no-subscribe': - add_succ_fn = add_succ_fn.replace('let deferred = core::mem::take(&mut state.deferred_links);', 'let deferred = KVec::new();', 1) + add_succ_fn = add_succ_fn.replace('&& !state.deferred_links.is_empty();', '&& false;', 1) elif mutation == 'skip-fast-check': - attach_fn = attach_fn.replace( + link_fn = link_fn.replace( 'if predecessor.settled_clean.load(Ordering::Acquire) {', 'if false {', 1, @@ -107,15 +109,18 @@ def build_harness(mutation=None): 'lazy_activate': 'state.deferred_links = self.links;' in activate_fn and 'predecessor.add_successor' not in activate_fn, 'no_cycle_prep': 'target: None,' in new_prep_fn, - 'fast_settled_check': 'if predecessor.settled_clean.load(Ordering::Acquire) {' in attach_fn, + 'fast_settled_check': 'if predecessor.settled_clean.load(Ordering::Acquire) {' in link_fn, 'clear_settled_on_err': 'self.settled_clean.store(false, Ordering::Release);' in publish_fn, 'finish_takes_deferred': 'core::mem::take(&mut state.deferred_links)' in finish_fn, 'is_pending_settles': 'state.upstream_released = true;' in is_pending_fn, 'bounded_probe': 'pred.pending_within(depth - 1)' in is_pending_fn, 'consume_failed': '.position(|(pred, _)| pred.failed_after_release())' in is_pending_fn and 'Probe::Consumed(state.deferred_links.swap_remove(index))' in is_pending_fn, - 'subscribe_deferred': 'let deferred = core::mem::take(&mut state.deferred_links);' in add_succ_fn - and 'self.attach_deferred(deferred, depth - 1);' in add_succ_fn, + 'subscribe_deferred': '&& !state.deferred_links.is_empty();' in add_succ_fn + and 'state.subscribe_queued |= subscribe;' in add_succ_fn + and '*stack = Some(predecessor);' in link_fn + and 'node.link_deferred(deferred, &mut stack);' in subscribe_fn + and 'depth' not in subscribe_fn and 'depth' not in link_fn, 'release_attached': 'Probe::Settled(old, state.successors.take())' in is_pending_fn and 'Self::drain(Self::released_ok(successors));' in is_pending_fn, 'covers_field': 'pub(crate) covers: Option,' in job_src, @@ -133,6 +138,7 @@ def build_harness(mutation=None): drop_chain = mutation == 'drop-chain-link' retry_failed = mutation == 'retry-failed-pred' no_subscribe = mutation == 'no-subscribe' + bounded_subscribe = mutation == 'bounded-subscribe' keep_attached = mutation == 'keep-attached-successors' return f''' @@ -166,6 +172,7 @@ def build_harness(mutation=None): published: Option>, upstream_released: bool, successors: Links, + subscribe_queued: bool, }} impl State {{ @@ -208,6 +215,7 @@ def build_harness(mutation=None): published: None, upstream_released: false, successors: None, + subscribe_queued: false, }}), }}) }} @@ -314,11 +322,18 @@ def build_harness(mutation=None): return; }} if !to_attach.is_empty() {{ - self.attach_deferred(to_attach, PENDING_PROBE_DEPTH); + self.attach_deferred(to_attach); }} }} - fn attach_deferred(self: &Arc, deferred: Vec<(Arc, Box)>, depth: usize) {{ + fn attach_deferred(self: &Arc, deferred: Vec<(Arc, Box)>) {{ + let mut stack = Vec::new(); + self.link_deferred(deferred, &mut stack, 0); + Self::subscribe(stack); + }} + + fn link_deferred(self: &Arc, deferred: Vec<(Arc, Box)>, + stack: &mut Vec<(Arc, usize)>, level: usize) {{ let mut fast_ok = 0usize; for (pred, mut link) in deferred {{ if !{str(skip_fast).lower()} && pred.settled_clean.load(Ordering::Acquire) {{ @@ -326,12 +341,31 @@ def build_harness(mutation=None): drop(link); }} else {{ link.target = Some(self.clone()); - pred.add_successor(link, depth); + // bounded-subscribe reproduces the depth cut of e73586f89ef8. + if pred.add_successor(link) && !({str(bounded_subscribe).lower()} && level >= PENDING_PROBE_DEPTH) {{ + stack.push((pred, level + 1)); + }} }} }} Self::drain(self.predecessors_done_ok(1 + fast_ok)); }} + fn subscribe(mut stack: Vec<(Arc, usize)>) {{ + while let Some((node, level)) = stack.pop() {{ + let deferred = {{ + let mut state = node.state.lock().unwrap(); + if state.result.is_some() || state.published.is_some() || state.upstream_released + || state.deferred_links.is_empty() {{ + continue; + }} + let deferred = std::mem::take(&mut state.deferred_links); + state.remaining += 1 + deferred.len(); + deferred + }}; + node.link_deferred(deferred, &mut stack, level); + }} + }} + fn publish(&self, result: Result<(), i32>) -> Links {{ self.fence_status.store(match result {{ Ok(()) => 1, Err(e) => e }}, Ordering::Release); let mut links = {{ @@ -402,39 +436,32 @@ def build_harness(mutation=None): None }} - fn add_successor(self: &Arc, mut link: Box, depth: usize) {{ + fn add_successor(&self, mut link: Box) -> bool {{ self.add_succ_calls.fetch_add(1, Ordering::Relaxed); - let deferred = {{ - let mut state = self.state.lock().unwrap(); - let immediate = if let Some(res) = state.published {{ - Some(res) - }} else if state.upstream_released {{ - Some(Ok(())) - }} else {{ - None - }}; - if let Some(res) = immediate {{ - drop(state); - if let Some(target) = link.target.take() {{ - Self::drain(target.predecessor_done(res)); - }} - return; - }} - link.next = state.successors.take(); - state.successors = Some(link); - if {str(no_subscribe).lower()} - || depth == 0 - || self.has_outputs - || state.result.is_some() - || state.deferred_links.is_empty() - {{ - return; - }} - let deferred = std::mem::take(&mut state.deferred_links); - state.remaining += 1 + deferred.len(); - deferred + let mut state = self.state.lock().unwrap(); + let immediate = if let Some(res) = state.published {{ + Some(res) + }} else if state.upstream_released {{ + Some(Ok(())) + }} else {{ + None }}; - self.attach_deferred(deferred, depth - 1); + if let Some(res) = immediate {{ + drop(state); + if let Some(target) = link.target.take() {{ + Self::drain(target.predecessor_done(res)); + }} + return false; + }} + link.next = state.successors.take(); + state.successors = Some(link); + let subscribe = !{str(no_subscribe).lower()} + && !self.has_outputs + && !state.subscribe_queued + && state.result.is_none() + && !state.deferred_links.is_empty(); + state.subscribe_queued |= subscribe; + subscribe }} fn drain(mut pending: Links) {{ @@ -476,7 +503,7 @@ def build_harness(mutation=None): target.state.lock().unwrap().remaining += links.len(); for (p, mut l) in links {{ l.target = Some(target.clone()); - p.add_successor(l, PENDING_PROBE_DEPTH); + p.add_successor(l); }} Publication::drain(target.predecessors_done_ok(1)); return; @@ -737,14 +764,14 @@ def build_harness(mutation=None): assert!(!b.is_pending()); }} - // 12. A waiter subscribes at most PENDING_PROBE_DEPTH deferred publications deep. Past that, - // the deepest subscribed node stays queued on a deferred one; a probe that settles it must - // release that queued link, and the chain above it, up to the waiter. - {{ + // 12. Chains of 4, 5 and 6 deferred intermediaries between writer W and waiter S: W's + // completion alone must signal S (no probe, no intermediary completion), and an + // intermediary failing afterwards must not change S's result. + for depth in [PENDING_PROBE_DEPTH, PENDING_PROBE_DEPTH + 1, PENDING_PROBE_DEPTH + 2] {{ let w = Publication::new(true); activate(&w, &[]); let mut chain = vec![w.clone()]; - for _ in 0..PENDING_PROBE_DEPTH + 2 {{ + for _ in 0..depth {{ let n = Publication::new(false); activate(&n, &[chain.last().unwrap().clone()]); chain.push(n); @@ -752,11 +779,39 @@ def build_harness(mutation=None): let s = Publication::new(true); activate(&s, &[chain.last().unwrap().clone()]); s.finish(Ok(())); + assert_eq!(s.fence_status.load(Ordering::Acquire), 0); w.finish(Ok(())); - let deep = chain[2].clone(); - assert!(!deep.is_pending()); assert_eq!(s.fence_status.load(Ordering::Acquire), 1, - "settling past the subscription bound must release the queued chain up to the waiter"); + "writer completion alone must signal the waiter through {{}} deferred intermediaries", depth); + chain[1].finish(Err(EIO)); + for n in &chain[2..] {{ + n.finish(Ok(())); + }} + assert_eq!(s.fence_status.load(Ordering::Acquire), 1, + "a later intermediary failure must not change a signalled waiter ({{}} deep)", depth); + }} + + // 13. A successor queued on B before B subscribes is released when a probe settles B. + {{ + let a = Publication::new(true); + activate(&a, &[]); + let b = Publication::new(false); + activate(&b, &[a.clone()]); + let s = Publication::new(true); + activate(&s, &[]); + let link = Box::new(Link {{ target: Some(s.clone()), result: Ok(()), next: None, resume: None }}); + {{ + let mut st = s.state.lock().unwrap(); + st.remaining += 1; + st.result = Some(Ok(())); + }} + // Queue only; leave B unsubscribed, as a racing probe would find it. + let _ = b.add_successor(link); + a.finish(Ok(())); + assert_eq!(s.fence_status.load(Ordering::Acquire), 0); + assert!(!b.is_pending()); + assert_eq!(s.fence_status.load(Ordering::Acquire), 1, + "a probe settlement must release successors queued on the settled publication"); }} println!("PASS g17-publication-direct-lazy-tests"); @@ -778,6 +833,7 @@ def main(): 'retry-failed-pred', 'keep-attached-successors', 'no-subscribe', + 'bounded-subscribe', ]) args = parser.parse_args() src = build_harness(args.mutation) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 11974e8f76664..fed98cf33e816 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -303,7 +303,8 @@ def mutations(flag, names, base, expect=KILL): 'eager-activate', 'cycle-target-some', 'skip-error-clear-settled', 'skip-fast-check', 'drop-chain-link', 'retry-failed-pred', - 'keep-attached-successors', 'no-subscribe'), []), + 'keep-attached-successors', 'no-subscribe', + 'bounded-subscribe'), []), 'g17-m5-multiqueue-contention-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-claim-outer', 'raw-compute-scope', 'raw-render-scope', 'unlocked-scope-drop', From 1213e012b40c0d12b5662ebd6cd724a05fa55ef2 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Fri, 27 Nov 2026 20:56:41 -0500 Subject: [PATCH 6/6] drm/asahi: g17: call Iterator::chain explicitly for publication links The kernel prelude brings pin_init::Init::chain into scope, so `.iter().chain(...)` on the predecessor and chain link slices is ambiguous (E0034). Name Iterator::chain. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/queue/mod.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index ece0bbb673fd3..3ef5fad4bbfb0 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -322,7 +322,7 @@ impl Queue { .map(|target| { PreparedPublication::new( target, - ordering.predecessors.iter().chain(ordering.chain.iter()), + Iterator::chain(ordering.predecessors.iter(), ordering.chain.iter()), ) }) .transpose()?; @@ -1534,7 +1534,7 @@ mod tests { let pub_r = pub_r.unwrap(); PreparedPublication::new( pub_r.clone(), - plan.predecessors.iter().chain(plan.chain.iter()), + Iterator::chain(plan.predecessors.iter(), plan.chain.iter()), ) .unwrap() .activate(); @@ -1604,7 +1604,7 @@ mod tests { let (pub_c, fence_c) = Publication::test_pair(&contexts, &status, true).unwrap(); PreparedPublication::new( pub_c.clone(), - plan_c.predecessors.iter().chain(plan_c.chain.iter()), + Iterator::chain(plan_c.predecessors.iter(), plan_c.chain.iter()), ) .unwrap() .activate();