From f716cdde0277a7ce68714d184713d67cee3a8e5c Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:42:53 -0500 Subject: [PATCH 1/6] drm/asahi: g17: bound a submission's syncs before parsing them A SUBMIT names its input and output syncs by count and pointer, and the ioctl parses every one of them before the queue sees the submission: each becomes a parsed record holding a syncobj and fence reference, and each timeline output a chain node its syncobj keeps once installed. G17 put no bound on their number. G15 and G16 refuse more than 4096 in total, but only in their queues, after parsing. Move that bound to file.rs as MAX_SYNCS_PER_SUBMISSION, which G15 and G16 now name, and give the GPU trait a max_syncs() admission bound that the ioctl checks next to max_cmdbuf_size(), before anything is copied or allocated. G17 returns the shared bound, so userspace that submits on G15 and G16 submits the same way on G17. Other generations keep their current behaviour. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/file.rs | 9 +++++++++ drivers/gpu/drm/asahi/g15/command.rs | 2 +- drivers/gpu/drm/asahi/g16/command.rs | 2 +- drivers/gpu/drm/asahi/g17/mod.rs | 4 ++++ drivers/gpu/drm/asahi/gpu.rs | 5 +++++ 5 files changed, 20 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index fc2d2dd6cedaf..4cb3591b774a5 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -149,6 +149,9 @@ pub(crate) const DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: u32 = const DEBUG_CLASS: DebugFlags = DebugFlags::File; pub(crate) const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; +/// Most input plus output syncs of one SUBMIT, on the GPUs that bound them +/// ([`gpu::Gpu::max_syncs`]). +pub(crate) const MAX_SYNCS_PER_SUBMISSION: usize = 4096; /// A client instance of an `mmu::Vm` address space. struct Vm { @@ -1898,6 +1901,12 @@ impl File { if data.cmdbuf_size as usize > gpu.max_cmdbuf_size() { return Err(E2BIG); } + // Before anything is allocated for the syncs: each one costs a parsed record, and + // a timeline output a chain node its syncobj keeps. + if data.in_sync_count as usize + data.out_sync_count as usize > gpu.max_syncs() { + cls_pr_debug!(Errors, "submit: Too many syncs\n"); + return Err(EINVAL); + } if let Some(manager) = gpu.manager() { manager.update_globals(); } diff --git a/drivers/gpu/drm/asahi/g15/command.rs b/drivers/gpu/drm/asahi/g15/command.rs index edb076df3d493..88ec0ab836be0 100644 --- a/drivers/gpu/drm/asahi/g15/command.rs +++ b/drivers/gpu/drm/asahi/g15/command.rs @@ -39,7 +39,7 @@ use crate::{file, mmu, timestamp, util::AnyBitPattern, util::Reader}; /// Largest command buffer. pub(crate) const MAX_CMDBUF: usize = 4 << 20; /// Most input plus output syncs of one SUBMIT. -pub(crate) const MAX_SYNCS: usize = 4096; +pub(crate) const MAX_SYNCS: usize = crate::file::MAX_SYNCS_PER_SUBMISSION; /// Hardware commands per SUBMIT. const MAX_COMMANDS: u32 = crate::file::MAX_COMMANDS_PER_SUBMISSION; diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 197d31e93fa0f..13ad1c6f2dc0a 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -24,7 +24,7 @@ use crate::{file, mmu, util::AnyBitPattern, util::Reader}; /// Largest command buffer. pub(crate) const MAX_CMDBUF: usize = 4 << 20; /// Most input plus output syncs of one SUBMIT. -pub(crate) const MAX_SYNCS: usize = 4096; +pub(crate) const MAX_SYNCS: usize = crate::file::MAX_SYNCS_PER_SUBMISSION; /// Hardware commands per SUBMIT. pub(crate) const MAX_COMMANDS: u32 = crate::file::MAX_COMMANDS_PER_SUBMISSION; diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 68167f1740256..1671f873889b6 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -2837,6 +2837,10 @@ impl gpu::Gpu for Gpu { command::MAX_STREAM } + fn max_syncs(&self) -> usize { + crate::file::MAX_SYNCS_PER_SUBMISSION + } + fn syncobj_wait_hint(&self) -> Option<(u32, u32)> { self.shared.feed.wait_hint() } diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index fb5359137b668..f2690393e2681 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -410,6 +410,11 @@ pub(crate) trait Gpu: Send + Sync { usize::MAX } + /// Admission bound on a submission's input plus output syncs, checked before parsing them. + fn max_syncs(&self) -> usize { + usize::MAX + } + /// The firmware statistics snapshot of this GPU, if its firmware reports any. fn stats_snapshot(&self) -> Option>; From ae6999ed9368c64a07a1971f8bd9d1d0dc7994bd Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:47:05 -0500 Subject: [PATCH 2/6] drm/asahi: install a submission's timeline outputs on one syncobj once Every output of a submission receives the same fence. Installing a timeline point, drm_syncobj_add_point() walks the syncobj's chain for garbage collection, one node per step while the fence it holds is unsignalled, and each installation adds a node. N outputs that name one timeline syncobj therefore cost N(N+1)/2 chain steps under the queue lock, and keep N chain nodes on the syncobj. G17 installs its outputs both when it accepts a submission and when it refuses one after resolving them, so an empty command stream is enough. Such submissions are not only malformed ones: the Vulkan runtime merges a signal-only batch into the batch before it, so one submission can signal a timeline at two rising points. Merge those outputs before any chain node is allocated: keep the last output of each timeline syncobj, at the highest of its points. Waits are unchanged: dma_fence_chain_find_seqno() resolves any of the merged points to the one node, whose fence is the submission's, and the syncobj's last submitted point is the same. Binary outputs are left as they are, and the cumulative anchor never merges, so an output aliasing it is still refused. The merge sorts the outputs that can merge, and allocates only when a submission has two or more of them. KUnit: asahi_submit_outputs. Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/file.rs | 125 ++++++++++++++++++++++++++++++++++ 1 file changed, 125 insertions(+) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 4cb3591b774a5..b34a67331f177 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -342,6 +342,7 @@ impl SyncItem { } base += chunk as u32; } + let anchor = Self::coalesce_outputs(&mut vec, in_count as usize, anchor)?; if let Some(anchor) = anchor { let bundle = crate::g17::sync_output::SignalBundle::new( &vec[in_count as usize..], @@ -358,6 +359,130 @@ impl SyncItem { Ok(vec) } + + /// Merges the timeline outputs of `syncs` (outputs from `first` on) that name the same + /// syncobj ([`coalesce_timeline_outputs`]), before any chain node is allocated for them. + /// Returns the index of the cumulative `anchor` after the merge. The anchor never merges, + /// so another output naming its syncobj is still refused. + fn coalesce_outputs( + syncs: &mut KVec, + first: usize, + anchor: Option, + ) -> Result> { + let mergeable = |&(index, sync): &(usize, &SyncItem)| { + index >= first && sync.timeline && Some(index) != anchor + }; + let count = syncs.iter().enumerate().filter(mergeable).count(); + if count < 2 { + return Ok(anchor); + } + let mut named = KVec::with_capacity(count, GFP_KERNEL)?; + for (index, sync) in syncs.iter().enumerate().filter(mergeable) { + named.push( + (sync.syncobj.as_raw() as usize, index, sync.timeline_value), + GFP_KERNEL, + )?; + } + let merged = coalesce_timeline_outputs(&mut named)?; + if merged.is_empty() { + return Ok(anchor); + } + for &(_, index, point) in named.iter() { + syncs[index].timeline_value = point; + } + let anchor = anchor + .map(|anchor| anchor - merged.iter().take_while(|&&index| index < anchor).count()); + let mut index = 0; + let mut next = merged.iter().peekable(); + syncs.retain(|_| { + let gone = next.next_if_eq(&&index).is_some(); + index += 1; + !gone + }); + Ok(anchor) + } +} + +/// Timeline outputs of one submission that name the same syncobj all receive the +/// submission's fence. Installing each walks the syncobj's unsignalled fence chain, which +/// every installation lengthens, so N of them would walk it N times. They merge into the +/// last of them, at the highest of their points: a wait for any of those points still +/// resolves to the submission's fence. +/// +/// `named` holds each mergeable output's syncobj, index and point. Leaves each kept output's +/// entry with its merged point and returns the merged-away outputs' indices, in order. +fn coalesce_timeline_outputs(named: &mut [(usize, usize, u64)]) -> Result> { + named.sort_unstable_by_key(|&(syncobj, index, _)| (syncobj, index)); + let mut merged = KVec::new(); + for group in named.chunk_by_mut(|a, b| a.0 == b.0) { + let Some(((_, _, point), earlier)) = group.split_last_mut() else { + continue; + }; + for &(_, index, earlier_point) in earlier.iter() { + *point = (*point).max(earlier_point); + merged.push(index, GFP_KERNEL)?; + } + } + merged.sort_unstable(); + Ok(merged) +} + +#[kernel::macros::kunit_tests(asahi_submit_outputs)] +mod output_tests { + use super::*; + + fn merge(outputs: &[(usize, u64)]) -> (KVec, KVec<(usize, u64)>) { + let mut named = KVec::new(); + for (index, &(syncobj, point)) in outputs.iter().enumerate() { + named.push((syncobj, index, point), GFP_KERNEL).unwrap(); + } + let merged = coalesce_timeline_outputs(&mut named).unwrap(); + let mut kept = KVec::new(); + for &(_, index, point) in named.iter() { + if !merged.contains(&index) { + kept.push((index, point), GFP_KERNEL).unwrap(); + } + } + kept.sort_unstable(); + (merged, kept) + } + + #[test] + fn distinct_syncobjs_stay_as_they_are() { + let (merged, kept) = merge(&[(1, 5), (2, 5), (3, 0)]); + assert!(merged.is_empty()); + assert_eq!(&kept[..], &[(0, 5), (1, 5), (2, 0)]); + } + + #[test] + fn rising_points_keep_the_last_and_highest() { + // Two batches that each signal one timeline, merged into one submission. + let (merged, kept) = merge(&[(1, 5), (2, 9), (1, 6)]); + assert_eq!(&merged[..], &[0]); + assert_eq!(&kept[..], &[(1, 9), (2, 6)]); + } + + #[test] + fn falling_points_keep_the_highest_at_the_last() { + let (merged, kept) = merge(&[(4, 9), (4, 3), (4, 7)]); + assert_eq!(&merged[..], &[0, 1]); + assert_eq!(&kept[..], &[(2, 9)]); + } + + #[test] + fn repeats_of_one_point_leave_one_output() { + let mut outputs = KVec::new(); + for _ in 0..MAX_SYNCS_PER_SUBMISSION { + outputs.push((7, 3), GFP_KERNEL).unwrap(); + } + let (merged, kept) = merge(&outputs); + assert_eq!(merged.len(), MAX_SYNCS_PER_SUBMISSION - 1); + assert!(merged + .iter() + .enumerate() + .all(|(order, &index)| order == index)); + assert_eq!(&kept[..], &[(MAX_SYNCS_PER_SUBMISSION - 1, 3)]); + } } #[derive(Clone)] From 43f3740cfbd05132ce393643812db2bc60825e5d Mon Sep 17 00:00:00 2001 From: Dj <43033058+DjDeveloperr@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:47:50 -0500 Subject: [PATCH 3/6] drm/asahi: g17: return a closed queue's unpublished identities at close A queue's context holds an execution identity, a QoS ID and, on some variants, a render identity, all from small device-wide pools. If the firmware saw the context, closing the queue arms a scheduler release, and the identities return when the firmware has consumed it. If it never saw the context, teardown::Pending::close() keeps nothing, and the identities return only with the context's last reference. That reference can outlive the queue by as long as userspace likes. When a client exits, its scheduler entities cancel the jobs still waiting for an input fence, but drm_sched frees such a job only once every one of its dependencies has signalled (drm_sched_entity_kill_jobs_work()), and the job holds the queue's backend and so its context. Meanwhile the queue's admission slot and its process's queue share are returned at close. Each exiting client with such a job then leaves an execution identity in use that no open queue accounts for. On M5, where every queue has its own, enough of them leave a new queue waiting for contexts that are not closing, and it fails with ENOSPC. Once both schedulers are torn down nothing of the queue can be published any more, so the firmware can never see that context: return its execution identity, QoS ID and unused render identity at close, next to the queue's admission. The cancelled jobs keep only memory, and still signal their outputs after their inputs, as drm_sched requires. QosLease now gives its ID back once, early or on drop. KUnit: asahi_g17_qos_capacity (an_id_given_back_early_is_given_back_once). Signed-off-by: Dj <43033058+DjDeveloperr@users.noreply.github.com> --- drivers/gpu/drm/asahi/g17/context.rs | 53 +++++++++++++++++++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 8 ++- drivers/gpu/drm/asahi/g17/teardown.rs | 10 ++-- 3 files changed, 64 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 6e377d0f29a42..23ac21d08a9ec 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -81,6 +81,7 @@ impl QosIds { ids: self.clone(), id: id as u8, seen: AtomicBool::new(false), + returned: AtomicBool::new(false), }, GFP_KERNEL, )?) @@ -92,9 +93,15 @@ struct QosLease { id: u8, /// The firmware may have seen this ID. seen: AtomicBool, + /// The ID went back to the device's pool. + returned: AtomicBool, } -impl Drop for QosLease { - fn drop(&mut self) { +impl QosLease { + /// Gives the ID back, once: early ([`Context::release_unpublished`]) or on drop. + fn give_back(&self) { + if self.returned.swap(true, Ordering::AcqRel) { + return; + } let fence = if self.seen.load(Ordering::Acquire) { super::channel::control_fence() } else { @@ -109,6 +116,11 @@ impl Drop for QosLease { state.released |= 1u128 << id; } } +impl Drop for QosLease { + fn drop(&mut self) { + self.give_back(); + } +} struct WorkStorage { object: PooledObject, @@ -477,6 +489,19 @@ impl Context { None => self.execution.release(), } } + /// Its queue closed before the firmware saw this context, and nothing of the queue can + /// publish any more. Returns the finite identities no firmware record can name: the + /// execution identity, the QoS ID and an unused render identity. A published context + /// returns its own once its scheduler release is consumed. Either way they do not wait + /// for the context's last reference, which a cancelled job keeps until its inputs signal. + pub(crate) fn release_unpublished(&self) { + if self.is_published() { + return; + } + self.release_execution(); + self.qos.give_back(); + self.release_render_id(); + } /// `other` runs in this context's shared execution context. pub(crate) fn shares_execution(&self, other: &Context) -> bool { self.share.is_some() && core::ptr::eq(&*self.execution, &*other.execution) @@ -895,6 +920,30 @@ mod capacity_tests { } } + #[test] + fn an_id_given_back_early_is_given_back_once() { + let ids = QosIds::new().unwrap(); + let (early, other) = (ids.acquire().unwrap(), ids.acquire().unwrap()); + assert_eq!(ids.used(), 2); + early.give_back(); + early.give_back(); + assert_eq!(ids.used(), 1); + let clock = ids.state.lock().clock; + // Every free ID is taken while the early holder lives, its own again among them. + let mut rest = KVec::with_capacity(QOS_IDS - 3, GFP_KERNEL).unwrap(); + for _ in 0..QOS_IDS - 3 { + rest.push(ids.acquire().unwrap(), GFP_KERNEL).unwrap(); + } + assert!(matches!(ids.acquire(), Err(ENOSPC))); + assert!(rest.iter().any(|lease| lease.id == early.id)); + // Dropping the early holder gives nothing back: its ID is the new owner's. + drop(early); + assert_eq!(ids.used(), QOS_IDS as u32 - 2); + assert_eq!(ids.state.lock().clock, clock); + drop((other, rest)); + assert_eq!(ids.used(), 0); + } + #[test] fn a_released_qos_row_still_in_use_is_cleared_later() { let ids = QosIds::new().unwrap(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index eb271e87a3289..075396e41d8cc 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -94,7 +94,7 @@ impl Backend { }; // Retain a published scheduler before a never-kicked physical graph is // removed. The teardown entry owns its root until control consumption. - firmware + let retained = firmware .queues .teardown .close(&self.context, super::now_ns())?; @@ -106,6 +106,12 @@ impl Backend { firmware.queues.sync_render_holds(); firmware.queues.admission.release_owner(self.owner); drop(state); + // Both schedulers are gone, so the firmware cannot see a context it has not seen yet. + // Its identities return with the queue's admission, not after the jobs that the + // closing entities cancelled: those wait for their inputs before they are freed. + if !retained { + self.context.release_unpublished(); + } // Its idle channel, or its slot and never-published QID, is free. self.shared.channels.notify(); self.shared.queue_events(); diff --git a/drivers/gpu/drm/asahi/g17/teardown.rs b/drivers/gpu/drm/asahi/g17/teardown.rs index 39208dc7b3f34..acf804814b5c0 100644 --- a/drivers/gpu/drm/asahi/g17/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/teardown.rs @@ -173,20 +173,22 @@ impl Pending { } /// No allocation is needed at close. A scheduler page never exposed to firmware requires - /// no release, unless the Registry already retained one of its displaced graphs. - pub(crate) fn close(&mut self, context: &Arc, now: u64) -> Result { + /// no release, unless the Registry already retained one of its displaced graphs. Returns + /// whether the context waits here for a release. + pub(crate) fn close(&mut self, context: &Arc, now: u64) -> Result { if let Some(index) = self.find(context) { let entry = &mut self.entries[index]; if entry.phase == Phase::Deferred { entry.phase = Phase::Draining; entry.armed = now; } - return Ok(()); + return Ok(true); } if context.is_published() { self.insert(context, Phase::Draining, now)?; + return Ok(true); } - Ok(()) + Ok(false) } /// Publish in insertion order. Mandatory control replies and a full control ring stop this From b04ba72e86ee8223bcf23f36c11c191614269051 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 04:08:11 -0500 Subject: [PATCH 4/6] tools/asahi: give the host-test stand-ins the closed-queue release and the sync bound Two host tests compile driver files against stand-ins that lacked what this branch's earlier commits use. g17-admission-order-tests.py builds release_queue(), which now calls Context::release_unpublished(); its stand-in Context gets it as a no-op, since the fixture models slot holds, not identities. test-command-stream.py builds g16/command.rs, whose MAX_SYNCS now names file::MAX_SYNCS_PER_SUBMISSION; its stand-in file module gets the constant. No runtime code changes. Signed-off-by: DjDeveloperr --- tools/asahi/g17-admission-order-tests.py | 2 ++ .../selftests/drivers/gpu/asahi-m4/test-command-stream.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index a55d4c7fbe6f9..ce3aa9b26b891 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -434,6 +434,8 @@ def release_fixture(): impl Context { pub fn is_published(&self) -> bool { self.published } pub fn scheduler_va(&self) -> u64 { self.scheduler } + // The identities are not modelled; release_queue() returns them at close. + pub fn release_unpublished(&self) {} } } pub mod teardown { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py index f1684b4122557..d2f094768972c 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py @@ -121,7 +121,7 @@ impl core::ops::Deref for KVec { type Target = [T]; fn deref(&self) -> &[T] { &self.0 } } impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } } mod uapi { include!("FULL_UAPI"); } -mod file { pub const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; } +mod file { pub const MAX_COMMANDS_PER_SUBMISSION: u32 = 64; pub const MAX_SYNCS_PER_SUBMISSION: usize = 4096; } mod hw { pub const USER_RANGE: core::ops::Range = 0x4000..((1u64 << 42) - 0x8000); pub mod sizes { pub const MAX_ATTACHMENTS: usize = 16; pub const TA_LIGHT_TILEMAP_BYTES: u64 = 64 * 1024; } From ff6b94853dd83fc4f27112fc81f0d37e4f9f74ff Mon Sep 17 00:00:00 2001 From: Ryan Murray <81541646+RyanTheTide@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:33:00 +1100 Subject: [PATCH 5/6] drm/asahi: take the submission's KVVec in coalesce_outputs() main (#3021) made the parsed sync list a KVVec, and this branch's coalesce_outputs() still took a KVec, so the forward merge no longer builds (E0308 at file.rs:332). Take &mut KVVec; the body only uses Vec methods. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/file.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 823d1fa0bf4f4..086a3016ba671 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -352,7 +352,7 @@ impl SyncItem { /// Returns the index of the cumulative `anchor` after the merge. The anchor never merges, /// so another output naming its syncobj is still refused. fn coalesce_outputs( - syncs: &mut KVec, + syncs: &mut KVVec, first: usize, anchor: Option, ) -> Result> { From 0c4976b9ffb574b328786cb38c8b329c293c075c Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 3 Dec 2026 05:32:05 -0500 Subject: [PATCH 6/6] drm/asahi: end an output merge at a binary output of the same syncobj A binary output replaces the syncobj's fence, chain and points. With timeline 9, binary, then timeline 7 on one syncobj the last point is 7, but merging the two timeline outputs across the binary one moved point 9 to the last output and published 9. Keep the binary outputs in the merge list as boundaries. Add a KUnit case, and a host test that checks every list of up to five outputs on two syncobjs against installing each output in order. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/file.rs | 76 +++++++++++--- tools/asahi/g17-submit-outputs-tests.py | 134 ++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 3 files changed, 195 insertions(+), 16 deletions(-) create mode 100755 tools/asahi/g17-submit-outputs-tests.py diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 560230f8501df..89da52d87fc1d 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -352,18 +352,18 @@ impl SyncItem { first: usize, anchor: Option, ) -> Result> { - let mergeable = |&(index, sync): &(usize, &SyncItem)| { - index >= first && sync.timeline && Some(index) != anchor - }; - let count = syncs.iter().enumerate().filter(mergeable).count(); - if count < 2 { + let outputs = |&(index, _): &(usize, &SyncItem)| index >= first && Some(index) != anchor; + let timeline = |(_, sync): &(usize, &SyncItem)| sync.timeline; + let named = syncs.iter().enumerate().filter(outputs); + if named.filter(timeline).count() < 2 { return Ok(anchor); } - let mut named = KVec::with_capacity(count, GFP_KERNEL)?; - for (index, sync) in syncs.iter().enumerate().filter(mergeable) { + let mut named = KVVec::with_capacity(syncs.len() - first, GFP_KERNEL_ACCOUNT)?; + for (index, sync) in syncs.iter().enumerate().filter(outputs) { + let point = sync.timeline.then_some(sync.timeline_value); named.push( - (sync.syncobj.as_raw() as usize, index, sync.timeline_value), - GFP_KERNEL, + (sync.syncobj.as_raw() as usize, index, point), + GFP_KERNEL_ACCOUNT, )?; } let merged = coalesce_timeline_outputs(&mut named)?; @@ -371,7 +371,9 @@ impl SyncItem { return Ok(anchor); } for &(_, index, point) in named.iter() { - syncs[index].timeline_value = point; + if let Some(point) = point { + syncs[index].timeline_value = point; + } } let anchor = anchor .map(|anchor| anchor - merged.iter().take_while(|&&index| index < anchor).count()); @@ -390,14 +392,16 @@ impl SyncItem { /// submission's fence. Installing each walks the syncobj's unsignalled fence chain, which /// every installation lengthens, so N of them would walk it N times. They merge into the /// last of them, at the highest of their points: a wait for any of those points still -/// resolves to the submission's fence. +/// resolves to the submission's fence. A binary output of the same syncobj between two of +/// them replaces the chain, points and all, so nothing merges across it. /// -/// `named` holds each mergeable output's syncobj, index and point. Leaves each kept output's -/// entry with its merged point and returns the merged-away outputs' indices, in order. -fn coalesce_timeline_outputs(named: &mut [(usize, usize, u64)]) -> Result> { +/// `named` holds each output's syncobj, index and point, `None` for a binary output. Leaves +/// each kept output's entry with its merged point and returns the merged-away outputs' +/// indices, in order. +fn coalesce_timeline_outputs(named: &mut [(usize, usize, Option)]) -> Result> { named.sort_unstable_by_key(|&(syncobj, index, _)| (syncobj, index)); let mut merged = KVec::new(); - for group in named.chunk_by_mut(|a, b| a.0 == b.0) { + for group in named.chunk_by_mut(|a, b| a.0 == b.0 && a.2.is_some() && b.2.is_some()) { let Some(((_, _, point), earlier)) = group.split_last_mut() else { continue; }; @@ -414,7 +418,7 @@ fn coalesce_timeline_outputs(named: &mut [(usize, usize, u64)]) -> Result (KVec, KVec<(usize, u64)>) { + fn merge_any(outputs: &[(usize, Option)]) -> (KVec, KVec<(usize, Option)>) { let mut named = KVec::new(); for (index, &(syncobj, point)) in outputs.iter().enumerate() { named.push((syncobj, index, point), GFP_KERNEL).unwrap(); @@ -430,6 +434,20 @@ mod output_tests { (merged, kept) } + /// Timeline outputs only. + fn merge(outputs: &[(usize, u64)]) -> (KVec, KVec<(usize, u64)>) { + let mut timelines = KVec::new(); + for &(syncobj, point) in outputs { + timelines.push((syncobj, Some(point)), GFP_KERNEL).unwrap(); + } + let (merged, any) = merge_any(&timelines); + let mut kept = KVec::new(); + for &(index, point) in any.iter() { + kept.push((index, point.unwrap()), GFP_KERNEL).unwrap(); + } + (merged, kept) + } + #[test] fn distinct_syncobjs_stay_as_they_are() { let (merged, kept) = merge(&[(1, 5), (2, 5), (3, 0)]); @@ -452,6 +470,32 @@ mod output_tests { assert_eq!(&kept[..], &[(2, 9)]); } + #[test] + fn a_binary_output_of_the_same_syncobj_ends_a_merge() { + // The binary output replaces the chain: the syncobj ends at 7, not at 9. + let outputs = [(4, Some(9)), (4, None), (4, Some(7))]; + let (merged, kept) = merge_any(&outputs); + assert!(merged.is_empty()); + assert_eq!(&kept[..], &[(0, Some(9)), (1, None), (2, Some(7))]); + // Either side still merges, around repeated binary outputs too, and another syncobj's + // binary output ends nothing. + let outputs = [ + (4, Some(9)), + (4, Some(8)), + (4, None), + (4, None), + (4, Some(3)), + (5, None), + (4, Some(5)), + ]; + let (merged, kept) = merge_any(&outputs); + assert_eq!(&merged[..], &[0, 4]); + assert_eq!( + &kept[..], + &[(1, Some(9)), (2, None), (3, None), (5, None), (6, Some(5))] + ); + } + #[test] fn repeats_of_one_point_leave_one_output() { let mut outputs = KVec::new(); diff --git a/tools/asahi/g17-submit-outputs-tests.py b/tools/asahi/g17-submit-outputs-tests.py new file mode 100755 index 0000000000000..ed7f930dfd9a1 --- /dev/null +++ b/tools/asahi/g17-submit-outputs-tests.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Host test: merging a submission's repeated timeline outputs changes no syncobj (linux#3200). + +Compiles the real `SyncItem::coalesce_outputs()` and `coalesce_timeline_outputs()` from +`drivers/gpu/drm/asahi/file.rs`, with their KUnit cases, against a host model of a syncobj's +payload: an add_point() never lowers the chain's point (dma_fence_chain_init()), and a +replace_fence() drops the chain. Every sequence of up to five outputs on two syncobjs, with +and without a cumulative anchor, leaves both syncobjs with the payload that installing each +output in order leaves. + +`--mutation merge-across-binary` merges timeline outputs across a binary output of the same +syncobj, as before the fix; the run must then fail. +""" +import argparse +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +FILE = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/file.rs' + +HOST = r''' +use std::ops::{Deref, DerefMut}; +type Result = core::result::Result; +#[derive(Clone, Copy)] struct Flags; +const GFP_KERNEL: Flags = Flags; +const GFP_KERNEL_ACCOUNT: Flags = Flags; +const MAX_SYNCS_PER_SUBMISSION: usize = 4096; +struct KVec(Vec); +type KVVec = KVec; +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn with_capacity(n: usize, _: Flags) -> Result { Ok(Self(Vec::with_capacity(n))) } + fn push(&mut self, v: T, _: Flags) -> Result { self.0.push(v); Ok(()) } + fn retain(&mut self, f: impl FnMut(&mut T) -> bool) { self.0.retain_mut(f) } +} +impl Deref for KVec { type Target = [T]; fn deref(&self) -> &[T] { &self.0 } } +impl DerefMut for KVec { fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } } +#[derive(Clone, Copy)] struct SyncObj(usize); +impl SyncObj { fn as_raw(&self) -> *const u8 { self.0 as *const u8 } } +#[derive(Clone, Copy)] struct SyncItem { syncobj: SyncObj, timeline_value: u64, timeline: bool } + +/// What each syncobj holds: nothing, a plain fence, or a chain ending at a point. +#[derive(Clone, Copy, Debug, PartialEq)] enum Payload { Empty, Binary, Chain(u64) } +fn install(outputs: &[SyncItem]) -> [Payload; 2] { + let mut objects = [Payload::Empty; 2]; + for sync in outputs { + let payload = &mut objects[sync.syncobj.0 - 1]; + *payload = match *payload { + Payload::Chain(point) if sync.timeline => Payload::Chain(point.max(sync.timeline_value)), + _ if sync.timeline => Payload::Chain(sync.timeline_value), + _ => Payload::Binary, + }; + } + objects +} + +#[test] +fn every_short_output_list_leaves_the_same_payloads() { + // Output `code`: the syncobj and a binary output or one of three points. + let item = |code: usize| SyncItem { + syncobj: SyncObj(1 + code / 4), + timeline_value: (code % 4) as u64, + timeline: code % 4 != 0, + }; + for inputs in 0..2 { + for len in 0..=5u32 { + for mut list in 0..8usize.pow(len) { + let mut outputs = KVec::new(); + for _ in 0..len { + outputs.push(item(list % 8), GFP_KERNEL).unwrap(); + list /= 8; + } + // An input takes no part, whatever it names; and no output but the anchor may + // name the anchor's syncobj. + for anchor in (0..=len as usize).map(|at| (at < len as usize).then_some(at)) { + if anchor.is_some_and(|at| (0..len as usize).any( + |i| i != at && outputs[i].syncobj.0 == outputs[at].syncobj.0) + || !outputs[at].timeline) { continue; } + let mut syncs = KVec::new(); + for _ in 0..inputs { syncs.push(item(7), GFP_KERNEL).unwrap(); } + for &sync in outputs.iter() { syncs.push(sync, GFP_KERNEL).unwrap(); } + let moved = SyncItem::coalesce_outputs( + &mut syncs, inputs, anchor.map(|at| at + inputs)).unwrap(); + assert_eq!(install(&syncs[inputs..]), install(&outputs)); + assert_eq!(moved.map(|at| syncs[at].syncobj.0), + anchor.map(|at| outputs[at].syncobj.0)); + } + } + } + } +} +''' + + +def item(source, signature): + """The item beginning at `signature`, through its matching closing brace.""" + assert source.count(signature) == 1, f'{signature!r}: {source.count(signature)} matches' + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['merge-across-binary']) + args = parser.parse_args() + text = FILE.read_text() + code = ('impl SyncItem {\n' + item(text, 'fn coalesce_outputs(') + '\n}\n' + + item(text, 'fn coalesce_timeline_outputs(') + + '\n#[cfg(test)]\n' + item(text, 'mod output_tests {')) + if args.mutation: + boundary = ' && a.2.is_some() && b.2.is_some()' + assert code.count(boundary) == 1 + code = code.replace(boundary, '') + with tempfile.TemporaryDirectory(prefix='g17-submit-outputs-') as tmp: + source = Path(tmp) / 'outputs.rs' + source.write_text(HOST + code) + binary = Path(tmp) / 'outputs' + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '--test', '-O', '-Awarnings', + str(source), '-o', str(binary)], check=True) + run = subprocess.run([str(binary)], capture_output=True, text=True, timeout=120) + print(run.stdout + run.stderr) + sys.exit(run.returncode) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index c60b58486a190..3052593cc917c 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -477,6 +477,7 @@ def mutations(flag, names, base, expect=KILL): 'check-outside-lock'), []), 'g17-owner-release-order-tests.py': [([], PASS)], 'g17-pool-release-tests.py': [([], PASS)], + 'g17-submit-outputs-tests.py': [([], PASS)] + mutations('--mutation', ['merge-across-binary'], []), # no-drain-release is the old rule: only a lease ends a slot's quarantine. 'g17-quarantine-drain-tests.py': [([], PASS)] + mutations('--mutation', ('no-drain-release', 'without-witness', 'ignore-leases', 'no-last-lease',