diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index f1170ee9a4cdf..b32598fd06544 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -14,8 +14,26 @@ 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 +/// probe that stops early only leaves the settlement to the links. +const PENDING_PROBE_DEPTH: usize = 4; + 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 +42,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, @@ -33,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 { @@ -58,6 +83,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 +103,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, @@ -83,6 +114,8 @@ impl Publication { published: None, upstream_released: false, successors: None, + subscribe_queued: false, + subscribe_next: None, }, "G17 host timestamp publication"), }), GFP_KERNEL, @@ -93,24 +126,182 @@ 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) + self.pending_within(PENDING_PROBE_DEPTH) + } + + fn pending_within(&self, depth: usize) -> bool { + if !self.pending.load(Ordering::Acquire) { + return false; + } + if self.has_outputs { + return true; + } + loop { + let step = { + 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 failed = state + .deferred_links + .iter() + .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, + } + } + }; + 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; + } + } + } + } + } + + /// 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, 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); + } + } + + /// 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)>) { + 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)>, + stack: &mut Option>, + ) { + 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()); + 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); } } @@ -130,7 +321,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 +336,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 +352,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 { @@ -170,29 +362,57 @@ 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 add_successor(&self, mut link: KBox) { - let immediate = { + 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(); - if let Some(result) = state.published { - result - } else if state.upstream_released { - Ok(()) - } else { - link.next = state.successors.take(); - state.successors = Some(link); - return; + debug_assert!(state.remaining != 0); + if state.predecessor_error.is_none() { + state.predecessor_error = Some(PRODUCER_FAILED); } + state.remaining -= 1; + state.claim() }; - Self::drain(link.target.predecessor_done(immediate)); + if let Some(result) = ready { + return self.publish(result); + } + None + } + + /// Deliver `link` now if this publication has settled, or queue it until it does. + /// + /// 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 + }; + 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. @@ -201,7 +421,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 +441,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 +458,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 +470,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 +642,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..b0c469c1b10b5 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -549,6 +549,13 @@ 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>>>, + /// 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, } @@ -680,7 +687,15 @@ 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, + 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 2bb536c65a68a..3ef5fad4bbfb0 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], @@ -306,20 +312,32 @@ 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().copied())) + .map(|target| { + PreparedPublication::new( + target, + Iterator::chain(ordering.predecessors.iter(), ordering.chain.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 +423,13 @@ 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; + fences.covers = order.wait_through[index]; self.sequence[index] = order.sequence; if fences.publishes() { self.publishers[index].push_within_capacity(order.sequence, fences.clone())?; @@ -698,6 +718,12 @@ trait FrontierEntry: outstanding::Status { fn pending_publication(&self) -> Option<&Arc> { self.publication().filter(|publication| publication.is_pending()) } + fn timestamp_publications(&self) -> &[Arc] { + &[] + } + fn covers(&self) -> Option { + None + } fn completed(&self) -> &Fence; fn scheduled(&self) -> &Fence; } @@ -711,6 +737,16 @@ 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 covers(&self) -> Option { + self.covers + } + fn completed(&self) -> &Fence { &self.completed } @@ -720,18 +756,105 @@ 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(()) +} + +/// 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)>, } -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, @@ -752,14 +875,17 @@ impl<'a> EnqueueOrdering<'a> { // `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 let Some(publication) = entry.pending_publication() { - predecessors.push(publication, GFP_KERNEL)?; + 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. @@ -767,15 +893,19 @@ impl<'a> EnqueueOrdering<'a> { } } } + chain.link(&predecessors, &mut chained)?; } if cross_chain { - for (_, entry) in other_covered.clone() { + let mut chain = PublicationChain::new(); + for (sequence, entry) in other_covered.clone() { if entry.status() <= 0 { if let Some(publication) = entry.pending_publication() { - predecessors.push(publication, GFP_KERNEL)?; + collect_publication_predecessors(entry, &mut predecessors)?; + chain.note(sequence, entry, publication)?; } } } + chain.link(&predecessors, &mut chained)?; } if same_wait { @@ -814,6 +944,7 @@ impl<'a> EnqueueOrdering<'a> { Ok(Self { predecessors, + chain: chained, host_waits: host, firmware_waits: firmware, }) @@ -833,6 +964,8 @@ mod tests { scheduled: Fence, completed: Fence, publication: Option>, + timestamp_publications: KVec>, + covers: Option, } impl outstanding::Status for TestEntry { @@ -850,6 +983,14 @@ mod tests { self.publication.as_ref() } + fn timestamp_publications(&self) -> &[Arc] { + self.timestamp_publications.as_slice() + } + + fn covers(&self) -> Option { + self.covers + } + fn completed(&self) -> &Fence { &self.completed } @@ -884,6 +1025,8 @@ mod tests { scheduled, completed, publication: Some(publication.clone()), + timestamp_publications: KVec::new(), + covers: None, }, Some(publication), ) @@ -895,6 +1038,8 @@ mod tests { scheduled, completed, publication: None, + timestamp_publications: KVec::new(), + covers: None, }, None, ) @@ -937,7 +1082,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 +1110,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 +1168,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 +1422,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 +1481,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 +1492,138 @@ 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(); + let mut last: Option> = None; + 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(); + // 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.clone(), + Iterator::chain(plan.predecessors.iter(), 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(), + Iterator::chain(plan_c.predecessors.iter(), 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 new file mode 100755 index 0000000000000..ff94977c1af3e --- /dev/null +++ b/tools/asahi/g17-publication-direct-lazy-tests.py @@ -0,0 +1,851 @@ +#!/usr/bin/env python3 +# 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, 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 + 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(') + 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, 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( + '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 == '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 == 'no-subscribe': + add_succ_fn = add_succ_fn.replace('&& !state.deferred_links.is_empty();', '&& false;', 1) + elif mutation == 'skip-fast-check': + link_fn = link_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 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': '&& !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, + '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. + 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' + 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''' +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>; + +enum Probe {{ + Consumed((Arc, Box)), + Settled(Vec<(Arc, Box)>, Links), + Next(Arc), +}} + +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, + subscribe_queued: bool, +}} + +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, + subscribe_queued: false, + }}), + }}) + }} + + 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; + }} + if self.has_outputs {{ + return true; + }} + loop {{ + let step = {{ + 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 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, + }} + }} + }}; + 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; + }} + }} + }} + }} + }} + + 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(); + 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 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) {{ + fast_ok += 1; + drop(link); + }} else {{ + link.target = Some(self.clone()); + // 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 = {{ + 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) -> bool {{ + self.add_succ_calls.fetch_add(1, Ordering::Relaxed); + 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 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) {{ + 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 {{ + 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; + }} + 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"); + 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"); + + // 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 {{ seq: 1, covers: None, pub_node: writer.clone(), inherited: vec![] }}]; + let mut total_links = 0usize; + 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)); + 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, &all(&preds, &chain)); + entries.push(Entry {{ seq, covers: Some(seq - 1), pub_node: node, inherited: preds }}); + }} + 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. + 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 {{ 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(); + 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!"); + + // 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); + }} + + // 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 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, &[]); + let b = Publication::new(false); + activate(&b, &[a.clone()]); + let s = Publication::new(true); + activate(&s, &[b.clone()]); + s.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. 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..depth {{ + 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(())); + assert_eq!(s.fence_status.load(Ordering::Acquire), 0); + w.finish(Ok(())); + assert_eq!(s.fence_status.load(Ordering::Acquire), 1, + "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"); + std::process::exit(0); +}} +''' + + +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', + 'drop-chain-link', + 'retry-failed-pred', + 'keep-attached-successors', + 'no-subscribe', + 'bounded-subscribe', + ]) + 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..fed98cf33e816 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -298,6 +298,13 @@ 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', + 'drop-chain-link', 'retry-failed-pred', + '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',