diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 3048fd4528411..86baf4ea7a820 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -295,6 +295,12 @@ impl Packet { !self.inputs.is_empty() || self.producers.is_some() } + /// Host-waited inputs keep a packet on the scheduler publication path; + /// already-published cross-engine firmware producers do not. + pub(crate) fn has_host_dependencies(&self) -> bool { + !self.inputs.is_empty() + } + pub(crate) fn begin_publication(&self) -> bool { self.publication .compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire) @@ -645,6 +651,10 @@ pub(crate) struct Fences { /// producers in firmware: what that engine's failure log must keep for it. pub(crate) producers: Option<(u64, Option)>, pub(crate) owner: Arc, + /// True when `Scheduler::enqueue()` already published this command inline + /// before returning, so later cross-engine consumers can publish inline too + /// without waiting for `scheduled` to signal through `drm_sched`. + pub(crate) inline_published: bool, } impl super::dependency::Retention for Fences { @@ -783,6 +793,7 @@ impl Scheduler { timestamp_waits: None, producers: None, owner: packet.completion.clone(), + inline_published: inline && packet.is_published(), }) } } diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index fa089b3a49030..366eaca406c63 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -333,6 +333,7 @@ impl Queue { publication, ordering_host_waits, ordering_firmware_waits, + ordering_firmware_published, inherited_timestamp_waits, ) = { let ordering = EnqueueOrdering::build( @@ -380,6 +381,7 @@ impl Queue { publication, ordering.host_waits, ordering.firmware_waits, + ordering.firmware_published, inherited_timestamp_waits, ) }; @@ -412,12 +414,17 @@ impl Queue { checked_inputs.push(fence, GFP_KERNEL)?; } // Firmware orders execution after each producer; the scheduler needs only the latest - // scheduled fence of them (dependency::ProducerWaits). + // scheduled fence of producers that have not already been published into firmware. let mut producer_waits = super::dependency::ProducerWaits::new(); - for (scheduled, _) in &ordering_firmware_waits { - producer_waits.producer(scheduled, |fence| { - Ok(dependencies.push(fence.clone(), GFP_KERNEL)?) - })?; + for ((scheduled, _), published) in ordering_firmware_waits + .iter() + .zip(ordering_firmware_published.iter()) + { + if !*published && job::fence_status(scheduled) <= 0 { + producer_waits.producer(scheduled, |fence| { + Ok(dependencies.push(fence.clone(), GFP_KERNEL)?) + })?; + } } // Their failures are checked through the other engine's failure log: one reference // instead of a completed fence per producer. @@ -838,6 +845,9 @@ trait FrontierEntry: outstanding::Status { } fn completed(&self) -> &Fence; fn scheduled(&self) -> &Fence; + fn inline_published(&self) -> bool { + false + } } impl FrontierEntry for Fences { @@ -860,6 +870,10 @@ impl FrontierEntry for Fences { fn scheduled(&self) -> &Fence { &self.scheduled } + + fn inline_published(&self) -> bool { + self.inline_published + } } fn push_unique_fence(out: &mut KVec, fence: &Fence) -> Result { @@ -895,6 +909,7 @@ struct EnqueueOrdering<'a> { reach: [u64; 2], host_waits: KVec, firmware_waits: KVec<(Fence, Fence)>, + firmware_published: KVec, inherited_timestamp_waits: KVec, } @@ -926,6 +941,7 @@ impl<'a> EnqueueOrdering<'a> { let mut predecessors = KVec::new(); let mut host = KVec::new(); let mut firmware = KVec::new(); + let mut firmware_published = KVec::new(); let mut inherited_timestamp_waits = KVec::new(); // A covered publication some kept predecessor already has as an ancestor needs no link of // its own: it fires before that predecessor, which fires before this command, and its @@ -1024,12 +1040,14 @@ impl<'a> EnqueueOrdering<'a> { (entry.scheduled().clone(), entry.completed().clone()), GFP_KERNEL, )?; + firmware_published.push(entry.inline_published(), GFP_KERNEL)?; } } else { firmware.push( (entry.scheduled().clone(), entry.completed().clone()), GFP_KERNEL, )?; + firmware_published.push(entry.inline_published(), GFP_KERNEL)?; } } @@ -1038,6 +1056,7 @@ impl<'a> EnqueueOrdering<'a> { reach, host_waits: host, firmware_waits: firmware, + firmware_published, inherited_timestamp_waits, }) } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 7a1510d1ebeb4..60a56eacd2aeb 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -3806,13 +3806,23 @@ impl Backend { /// its queue is already bound and nothing has to wait, as renders do. Any /// wait leaves the command, unpublished, to its scheduler. pub(super) fn try_compute_early(&self, packet: &Arc) -> bool { - if self.compute_backlog.load(Ordering::Acquire) != 0 || packet.has_dependencies() { + if self.compute_backlog.load(Ordering::Acquire) != 0 || packet.has_host_dependencies() { return false; } // A command the ray-traversal rule could hold now is left to its scheduler. if !self.traversal_inline(packet) { return false; } + if let Err(error) = packet.check_firmware_producers() { + if !packet.begin_publication() { + packet.completion.fail_unpublished(ECANCELED); + packet.set_early_result(Err(ECANCELED)); + return true; + } + packet.completion.fail_unpublished(error); + packet.set_early_result(Err(error)); + return true; + } if !packet.begin_publication() { packet.completion.fail_unpublished(ECANCELED); packet.set_early_result(Err(ECANCELED)); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index a4f1e442c0fc4..db15270f0ec07 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -578,13 +578,23 @@ impl Backend { } pub(in crate::g17) fn try_render_early(&self, packet: &Arc) -> bool { - if self.backlog.load(Ordering::Acquire) != 0 || packet.has_dependencies() { + if self.backlog.load(Ordering::Acquire) != 0 || packet.has_host_dependencies() { return false; } // As for compute: a render that traces rays is admitted by its scheduler. if !self.traversal_inline(packet) { return false; } + if let Err(error) = packet.check_firmware_producers() { + if !packet.begin_publication() { + packet.completion.fail_unpublished(ECANCELED); + packet.set_early_result(Err(ECANCELED)); + return true; + } + packet.completion.fail_unpublished(error); + packet.set_early_result(Err(error)); + return true; + } let admission = match self.admission.try_acquire_render(self.owner, self.render_pairs(packet).into(), Request::of(packet)) { Ok(Some(lease)) => lease, _ => return false, diff --git a/tools/asahi/g17-inline-cross-engine-tests.py b/tools/asahi/g17-inline-cross-engine-tests.py new file mode 100755 index 0000000000000..e0eed1337740e --- /dev/null +++ b/tools/asahi/g17-inline-cross-engine-tests.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test for G17 inline cross-engine publication behind already-published producers. + +Compiles production `has_host_dependencies()` (`job.rs`), the firmware-producer +dependency filtering in `queue/mod.rs`, and the early-publication guards in +`try_compute_early()` (`runtime.rs`) and `try_render_early()` +(`runtime/render/submit.rs`) to prove: +1. Already-inline-published or already-scheduled cross-engine producers do not + add `scheduled` waits to `dependencies`, so consumers stay eligible for + inline publication while retaining producer failure tracking. +2. Unpublished cross-engine producers still add their `scheduled` fence to + `dependencies` so the consumer waits for producer publication in `drm_sched`. +3. `try_compute_early()` and `try_render_early()` gate on host dependencies + only (`has_host_dependencies()`), allowing firmware-ordered cross-engine + packets to publish inline while still keeping host-waited packets on + `drm_sched`. +4. Failed firmware producers are caught by `check_firmware_producers()` in both + `try_compute_early()` and `try_render_early()`, failing the consumer + unpublished before any hardware publication. +""" +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' + +MUTATIONS = [ + 'always-wait-scheduled', + 'skip-unpublished-scheduled', + 'block-firmware-early', + 'skip-compute-producer-check', + 'skip-render-producer-check', + 'copy-try-early-bool', +] + + +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): + job_src = (G17 / 'job.rs').read_text() + queue_src = (G17 / 'queue/mod.rs').read_text() + runtime_src = (G17 / 'runtime.rs').read_text() + submit_src = (G17 / 'runtime/render/submit.rs').read_text() + + has_host_fn = item(job_src, 'pub(crate) fn has_host_dependencies(') + has_deps_fn = item(job_src, 'pub(crate) fn has_dependencies(') + comp_early_fn = item(runtime_src, 'pub(super) fn try_compute_early(') + rend_early_fn = item(submit_src, 'pub(in crate::g17) fn try_render_early(') + + # Extract the producer-wait loop and the decision to keep checking the log. + loop_sig = 'for ((scheduled, _), published) in ordering_firmware_waits' + loop_block = item(queue_src, loop_sig) + check_start = queue_src.index('let producer_check =') + check_end = queue_src.index(';', check_start) + 1 + producer_check = queue_src[check_start:check_end] + producer_check = producer_check.replace('order.wait_through[other]', 'prefix') + + # Extract the exact inline_published expression from Scheduler::enqueue(). + inline_pub_sig = ' inline_published: ' + assert job_src.count(inline_pub_sig) == 1, inline_pub_sig + ip_start = job_src.index(inline_pub_sig) + len(inline_pub_sig) + ip_end = job_src.index(',', ip_start) + inline_pub_expr = job_src[ip_start:ip_end].strip() + + if mutation == 'always-wait-scheduled': + old = 'if !*published && job::fence_status(scheduled) <= 0 {' + assert old in loop_block + loop_block = loop_block.replace(old, 'if true {', 1) + elif mutation == 'skip-unpublished-scheduled': + old = 'if !*published && job::fence_status(scheduled) <= 0 {' + assert old in loop_block + loop_block = loop_block.replace(old, 'if false {', 1) + elif mutation == 'block-firmware-early': + old = 'packet.has_host_dependencies()' + assert old in comp_early_fn and old in rend_early_fn + comp_early_fn = comp_early_fn.replace(old, 'packet.has_dependencies()', 1) + rend_early_fn = rend_early_fn.replace(old, 'packet.has_dependencies()', 1) + elif mutation == 'skip-compute-producer-check': + old = 'if let Err(error) = packet.check_firmware_producers() {' + assert old in comp_early_fn + comp_early_fn = comp_early_fn.replace(old, 'if let Err::<(), i32>(error) = Ok(()) {', 1) + elif mutation == 'skip-render-producer-check': + old = 'if let Err(error) = packet.check_firmware_producers() {' + assert old in rend_early_fn + rend_early_fn = rend_early_fn.replace(old, 'if let Err::<(), i32>(error) = Ok(()) {', 1) + elif mutation == 'copy-try-early-bool': + assert inline_pub_expr == 'inline && packet.is_published()', inline_pub_expr + inline_pub_expr = 'inline' + + # Verify structural pieces that feed into inline_published. + fences_has_inline = ( + 'pub(crate) inline_published: bool,' in job_src + and 'firmware_published.push(entry.inline_published(), GFP_KERNEL)?;' in queue_src + ) + + # Extract the guard prefix of try_compute_early and try_render_early up to begin_publication. + comp_guard_start = comp_early_fn.index('{') + 1 + comp_guard_end = comp_early_fn.index('let mut deferred =', comp_guard_start) + comp_guard = comp_early_fn[comp_guard_start:comp_guard_end] + + rend_guard_start = rend_early_fn.index('{') + 1 + rend_guard_end = rend_early_fn.index('let admission =', rend_guard_start) + rend_guard = rend_early_fn[rend_guard_start:rend_guard_end] + + # Normalize loop_block for std Vec instead of KVec(..., GFP_KERNEL)?. + loop_std = loop_block.replace( + 'Ok(dependencies.push(fence.clone(), GFP_KERNEL)?)', + '{ dependencies.push(fence.clone()); Ok::<(), i32>(()) }', + ) + + return f''' +use std::cell::Cell; +use std::sync::atomic::{{AtomicUsize, Ordering}}; + +const ECANCELED: i32 = -125; +type Result = std::result::Result; + +#[derive(Clone, Copy)] +struct Fence {{ + id: u32, + status: i32, +}} + +mod job {{ + use super::Fence; + pub fn fence_status(f: &Fence) -> i32 {{ + f.status + }} +}} + +struct ProducerWaits {{ + last: Option, +}} + +impl ProducerWaits {{ + fn new() -> Self {{ Self {{ last: None }} }} + fn producer(&mut self, fence: &Fence, mut emit: impl FnMut(&Fence) -> Result) -> Result {{ + if let Some(prev) = self.last.replace(*fence) {{ + emit(&prev)?; + }} + Ok(()) + }} + fn finish(self, mut emit: impl FnMut(&Fence) -> Result) -> Result {{ + if let Some(last) = self.last {{ + emit(&last)?; + }} + Ok(()) + }} +}} + +struct Completion {{ + failed_unpublished: Cell>, +}} + +impl Completion {{ + fn fail_unpublished(&self, err: i32) {{ + self.failed_unpublished.set(Some(err)); + }} +}} + +struct Packet {{ + inputs: Vec, + producers: Option, + began: Cell, + published: Cell, + early_result: Cell>, + completion: Completion, +}} + +impl Packet {{ + {has_deps_fn.replace('pub(crate) ', '')} + {has_host_fn.replace('pub(crate) ', '')} + fn check_firmware_producers(&self) -> Result {{ + self.producers.unwrap_or(Ok(())) + }} + fn begin_publication(&self) -> bool {{ + let ok = !self.began.get(); + self.began.set(true); + ok + }} + fn is_published(&self) -> bool {{ + self.published.get() + }} + fn set_early_result(&self, res: Result) {{ + self.early_result.set(Some(res)); + }} +}} + +fn compute_inline_published(inline: bool, packet: &Packet) -> bool {{ + {inline_pub_expr} +}} + +struct Backend {{ + backlog: AtomicUsize, + compute_backlog: AtomicUsize, + traversal_ok: bool, +}} + +impl Backend {{ + fn traversal_inline(&self, _packet: &Packet) -> bool {{ + self.traversal_ok + }} + fn run_compute_early_guard(&self, packet: &Packet) -> bool {{ + {comp_guard} + true + }} + fn run_render_early_guard(&self, packet: &Packet) -> bool {{ + {rend_guard} + true + }} +}} + +fn filter_producers( + ordering_firmware_waits: &[(Fence, Fence)], + ordering_firmware_published: &[bool], +) -> (Vec, Option<(u64, Option)>) {{ + let mut dependencies: Vec = Vec::new(); + let mut producer_waits = ProducerWaits::new(); + let _: Result = (|| {{ + {loop_std} + producer_waits.finish(|fence| {{ dependencies.push(fence.clone()); Ok(()) }})?; + Ok(()) + }})(); + let since = 3; + let prefix = Some(10); + {producer_check} + (dependencies, producer_check) +}} + +fn pkt(inputs: Vec, producers: Option) -> Packet {{ + Packet {{ + inputs, + producers, + began: Cell::new(false), + published: Cell::new(false), + early_result: Cell::new(None), + completion: Completion {{ failed_unpublished: Cell::new(None) }}, + }} +}} + +fn main() {{ + assert!({str(fences_has_inline).lower()}, "Fences::inline_published must flow into EnqueueOrdering"); + + let sched_pending = Fence {{ id: 10, status: 0 }}; + let sched_done = Fence {{ id: 11, status: 1 }}; + let comp_pending = Fence {{ id: 20, status: 0 }}; + + // 1. Producer published inline: no scheduled dependency, failure log tracked. + let (deps, check) = filter_producers(&[(sched_pending, comp_pending)], &[true]); + assert!(deps.is_empty(), "inline-published producer must not add scheduled dependency"); + assert_eq!(check, Some((3, Some(10)))); + + // 2. Producer already scheduled via drm_sched: no scheduled dependency, log tracked. + let (deps, check) = filter_producers(&[(sched_done, comp_pending)], &[false]); + assert!(deps.is_empty(), "already-scheduled producer must not add scheduled dependency"); + assert_eq!(check, Some((3, Some(10)))); + + // 3. Producer neither inline-published nor scheduled: MUST wait on scheduled fence. + let (deps, check) = filter_producers(&[(sched_pending, comp_pending)], &[false]); + assert_eq!(deps.len(), 1, "unpublished producer must add scheduled dependency"); + assert_eq!(deps[0].id, 10); + assert_eq!(check, Some((3, Some(10)))); + + let (deps, check) = filter_producers(&[], &[]); + assert!(deps.is_empty()); + assert_eq!(check, None); + + // 4. Early guards allow firmware-only cross-engine dependencies, block host waits. + let b = Backend {{ + backlog: AtomicUsize::new(0), + compute_backlog: AtomicUsize::new(0), + traversal_ok: true, + }}; + let p_fw_c = pkt(vec![], Some(Ok(()))); + assert!(b.run_compute_early_guard(&p_fw_c), "compute must publish inline with firmware-only deps"); + assert!(p_fw_c.completion.failed_unpublished.get().is_none()); + + let p_fw_r = pkt(vec![], Some(Ok(()))); + assert!(b.run_render_early_guard(&p_fw_r), "render must publish inline with firmware-only deps"); + assert!(p_fw_r.completion.failed_unpublished.get().is_none()); + + let p_host = pkt(vec![sched_pending], Some(Ok(()))); + assert!(!b.run_compute_early_guard(&p_host), "compute with host dep must stay on drm_sched"); + assert!(!b.run_render_early_guard(&p_host), "render with host dep must stay on drm_sched"); + + // 5. Failed firmware producer fails consumer unpublished in both compute and render. + let p_err_c = pkt(vec![], Some(Err(ECANCELED))); + assert!(b.run_compute_early_guard(&p_err_c)); + assert_eq!(p_err_c.completion.failed_unpublished.get(), Some(ECANCELED), "compute must catch failed producer"); + assert_eq!(p_err_c.early_result.get(), Some(Err(ECANCELED))); + + let p_err_r = pkt(vec![], Some(Err(ECANCELED))); + assert!(b.run_render_early_guard(&p_err_r)); + assert_eq!(p_err_r.completion.failed_unpublished.get(), Some(ECANCELED), "render must catch failed producer"); + assert_eq!(p_err_r.early_result.get(), Some(Err(ECANCELED))); + + // 6. Early failed producer (try_early returned true without hardware publication) + // followed by a cross-engine consumer: inline_published MUST be false so the + // consumer keeps its scheduled-fence wait and never omits it. + assert!(!p_err_c.is_published(), "early failed producer was never published to firmware"); + let prod_inline_pub = compute_inline_published(true, &p_err_c); + assert!(!prod_inline_pub, "inline_published must be false when try_early failed unpublished"); + let (deps, check) = filter_producers(&[(sched_pending, comp_pending)], &[prod_inline_pub]); + assert_eq!(deps.len(), 1, "consumer after early-failed producer must keep scheduled wait"); + assert_eq!(deps[0].id, 10); + assert_eq!(check, Some((3, Some(10)))); + + // Confirm a genuinely firmware-published inline producer sets inline_published = true. + let p_ok = pkt(vec![], None); + p_ok.published.set(true); + assert!(compute_inline_published(true, &p_ok)); + assert!(!compute_inline_published(false, &p_ok)); + + println!("PASS g17 inline cross-engine publication"); +}} +''' + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('--mutation', choices=MUTATIONS) + args = ap.parse_args() + + src = build_harness(args.mutation) + with tempfile.TemporaryDirectory(prefix='g17-inline-xeng-') as tmp: + rs = os.path.join(tmp, 'harness.rs') + bin_path = os.path.join(tmp, 'harness') + Path(rs).write_text(src) + c = subprocess.run(['rustc', '-O', rs, '-o', bin_path], capture_output=True, text=True) + if c.returncode != 0: + sys.stderr.write(c.stderr) + return 2 + r = subprocess.run([bin_path], capture_output=True, text=True) + sys.stdout.write(r.stdout) + sys.stderr.write(r.stderr) + return r.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index ab96117cd7086..9214ff8274794 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -481,6 +481,10 @@ def mutations(flag, names, base, expect=KILL): 'max-channels', 'multi-channel-max'), []), 'g17-m5-effort-tests.py': [([], PASS)] + mutations('--mutation', ('m5-ignores-bound', 'idle-counts-submitted'), []), + 'g17-inline-cross-engine-tests.py': [([], PASS)] + + mutations('--mutation', ('always-wait-scheduled', 'skip-unpublished-scheduled', + 'block-firmware-early', 'skip-compute-producer-check', + 'skip-render-producer-check', 'copy-try-early-bool'), []), 'g17-direct-stage-prefixes-tests.py': [([], PASS)] + mutations('--mutation', ('reject-staged', 'skip-render-tiling', 'skip-tiling-prefix', 'skip-compute-resolve',