From 3543a1e5a210f2f1ed6c5a2ab7eb4137ce1b7a50 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 03:42:52 -0300 Subject: [PATCH 01/10] drm/asahi: g17: count what a queue's pending commands keep allocated drm_sched credits bound only the commands on the firmware rings. Behind them a userspace queue can keep any number of commands pending behind a stalled job or a foreign fence: a compute job may run for 30 s, a chain of slow jobs longer. Each keeps its Packet (about 1.3 KB of validated command), its fence vectors and its scheduler dependencies, and its publication keeps one link per covered pending publication. Several of those grow with the number of other pending commands a command covers, so the total grows with the square of the queue's depth. Charging the allocations to the memcg bounds it only under a memory.max. Give each G17 queue a budget of units (queue::budget): 128 per command for its own state, plus one per fence reference, scheduler dependency, inherited timestamp wait and publication link it holds. The Packet holds the charge for its own state and vectors and gives it back when it is freed (drm_sched free_job). The publication holds the one for its links and gives it back once every link has been delivered, each freed by the drain: not when the publication itself goes, since its own queue's frontier keeps it until the next submission, which may be the one waiting for those units. Every release runs in process context (free_job and event work, ioctls, queue teardown), and the budget's lock is taken only when a release takes it below the limit. The budget is 2048 commands' worth, a policy constant: about 2.3 times the deepest queue measured. On an M4 Pro with m4.202, Cyberpunk 2077 keeps up to 874 commands pending on one queue, with up to about 24,000 scheduler dependencies among them, and a Hearthstone session up to 339. 2048 is 32 times the queue's hardware credits there (32 render and 32 compute); amdgpu's default software queue is 16 times its hardware depth. A command's own state counts 128 units (about 2.5 KB, 80 publication links' worth, rounded up), so the whole budget is about 8 MB of references. Add Queue::room() and the wait in the submit ioctl: a submission to a full queue sleeps, interruptibly and without the queue's lock, until the queue has room, and checks again under the lock. It sleeps before anything is published, so a signal restarts the ioctl with nothing installed in its output syncobjs. Nothing reports the G17 queue full yet; the next commit does. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/file.rs | 15 +- .../drm/asahi/g17/completion/publication.rs | 46 +++++- drivers/gpu/drm/asahi/g17/job.rs | 4 + drivers/gpu/drm/asahi/g17/queue/budget.rs | 155 ++++++++++++++++++ drivers/gpu/drm/asahi/g17/queue/mod.rs | 29 ++++ drivers/gpu/drm/asahi/queue/mod.rs | 12 ++ 6 files changed, 259 insertions(+), 2 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g17/queue/budget.rs diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index f82b5f7a551f7..3d5532fd8fea2 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -1989,7 +1989,20 @@ impl File { }; let objects = file.inner().objects(); - let mut guard = queue.lock(); + // A full queue takes the submission once it has room. Sleep without its lock, which + // nothing that frees the room takes, and check again under it. Nothing is published yet, + // so a signal restarts the ioctl. + let mut guard = loop { + let guard = queue.lock(); + let Some(room) = guard.queue.room() else { + break guard; + }; + drop(guard); + if let Err(error) = room.wait() { + queue.lock().return_cmdbuf(cmdbuf); + return Err(error); + } + }; let ret = guard.queue.submit( reg_data, id, diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index b22bb9a5b5e78..3c5a13889c13e 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -33,6 +33,10 @@ struct State { // still has no result of its own; successors have already been released. upstream_released: bool, successors: Links, + /// The queue budget units of this publication's links ([`Prepared::with_charge`]), given back + /// once every link has been delivered and freed. Not when the publication goes: its own + /// queue's frontier keeps it until the next submission, which may be waiting for these units. + links_charge: Option, } impl State { @@ -83,6 +87,7 @@ impl Publication { published: None, upstream_released: false, successors: None, + links_charge: None, }, "G17 host timestamp publication"), }), GFP_KERNEL, @@ -148,6 +153,7 @@ impl Publication { } fn predecessor_done(&self, result: Result) -> Links { + let mut delivered = None; let (ready, settled) = { let mut state = self.state.lock(); debug_assert!(state.remaining != 0); @@ -155,6 +161,10 @@ impl Publication { state.predecessor_error = Some(PRODUCER_FAILED); } state.remaining -= 1; + if state.remaining == 0 { + // Every link to this publication has been delivered; the drain frees each. + delivered = state.links_charge.take(); + } if let Some(ready) = state.claim() { (Some(ready), None) } else if state.remaining == 0 @@ -172,6 +182,7 @@ impl Publication { (None, None) } }; + drop(delivered); if let Some(result) = ready { return self.publish(result); } @@ -228,6 +239,7 @@ impl Publication { pub(crate) struct Prepared { target: Arc, links: KVec<(Arc, KBox)>, + charge: Option, } impl Prepared { @@ -245,7 +257,18 @@ impl Prepared { }, GFP_KERNEL)?; links.push((predecessor.clone(), link), GFP_KERNEL)?; } - Ok(Self { target, links }) + Ok(Self { target, links, charge: None }) + } + + /// How many links activation installs. + pub(crate) fn links(&self) -> usize { + self.links.len() + } + + /// Keeps `charge` for the links until the publication goes. + pub(crate) fn with_charge(mut self, charge: crate::g17::queue::budget::Charge) -> Self { + self.charge = Some(charge); + self } /// Called after all fallible scheduler setup and before any GPU publication. @@ -255,6 +278,7 @@ impl Prepared { debug_assert!(state.remaining == 1 && !state.claimed); // The fully allocated link vector bounds this count below usize::MAX. state.remaining += self.links.len(); + state.links_charge = self.charge; } for (predecessor, link) in self.links { predecessor.add_successor(link); @@ -308,6 +332,26 @@ mod tests { (Publication::new(output, status.clone(), has_outputs).unwrap(), handle) } + #[test] + fn link_units_come_back_once_the_links_are_delivered() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_charge"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let budget = crate::g17::queue::budget::Budget::with_limit(1).unwrap(); + let (producer, _producer_fence) = make_pub(&contexts, &status, true); + let (consumer, _consumer_fence) = make_pub(&contexts, &status, false); + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + let prepared = Prepared::new(consumer.clone(), core::iter::once(&producer)).unwrap(); + assert_eq!(prepared.links(), 1); + prepared.with_charge(budget.charge(1)).activate(); + // The link is pending in the producer's successor list. + assert!(budget.full()); + producer.finish(Ok([1, 2, 0, 0])); + // Delivered: the units come back while `consumer` still holds the publication, as its + // queue's frontier does until the next submission. + assert_eq!(budget.used(), 0); + drop(consumer); + } + #[test] fn consumer_retiring_before_delayed_producer_failure_inherits_error() { let contexts = FenceContexts::new(1, c_str!("asahi_pub_test"), KEY).unwrap(); diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 2cb029a0ce1ab..4681ed5228b79 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -138,6 +138,8 @@ pub(crate) struct Packet { /// When the job's watchdog allowance ends (host ns, [`super::timeout::Allowance::end`]): /// zero under the default allowance, `u64::MAX` for a longer one not yet placed. allowance_end: AtomicU64, + /// Its queue's budget units for this state ([`super::queue::budget`]). + _charge: super::queue::budget::Charge, /// The command's place in the order both engines publish in /// ([`super::port::Port::next_publication`]), zero until it is published. The watchdog /// compares it with the newest publication that retired ([`super::timeout::overtaken`]). @@ -153,6 +155,7 @@ impl Packet { completion: Arc, inputs: KVec, firmware: KVec, + charge: super::queue::budget::Charge, ) -> Result> { let footprint = match &command { Validated::Render { attachments, pass, .. } => { @@ -177,6 +180,7 @@ impl Packet { early: AtomicI32::new(0), backlog: AtomicBool::new(false), allowance_end: AtomicU64::new(0), + _charge: charge, ordinal: AtomicU64::new(0), })); Ok(packet.into()) diff --git a/drivers/gpu/drm/asahi/g17/queue/budget.rs b/drivers/gpu/drm/asahi/g17/queue/budget.rs new file mode 100644 index 0000000000000..e3bf99414c5d6 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/queue/budget.rs @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! How much a userspace queue's pending commands may keep allocated. +//! +//! drm_sched credits bound only the commands on the firmware rings. Behind them a queue could keep +//! any number of commands waiting on a stalled job or a foreign fence, and each keeps its packet, +//! its fence vectors and its publication links, several of which grow with the number of other +//! pending commands it covers. So each queue has a budget of units: [`COMMAND_UNITS`] for a +//! command's own state and one for each fence reference or publication link it holds. A +//! submission waits, interruptibly, while the queue has used the whole budget, and the units come +//! back as that memory is freed ([`Charge`]). + +use kernel::{ + new_condvar, new_mutex, + prelude::*, + sync::{Arc, CondVar, Mutex}, +}; +use core::sync::atomic::{AtomicUsize, Ordering}; + +/// The commands a queue may keep pending when they hold no references, a policy constant: about +/// 2.3 times the deepest queue measured (Cyberpunk 2077, 874 commands pending on one queue on an +/// M4 Pro; a Hearthstone session, 339). That is 32 times the queue's hardware credits there (32 +/// render and 32 compute); amdgpu's default software queue is 16 times its hardware depth. +pub(crate) const COMMANDS: usize = 2048; + +/// One command's own state: its packet with the validated command, its completion and frontier +/// entries, about 2.5 KB, or 80 publication links (32 bytes, the largest reference), rounded up. +pub(crate) const COMMAND_UNITS: usize = 128; + +/// The whole budget of one queue: about 8 MB of what its pending commands hold however it is made +/// up (as links), and one submission (sized by its own arguments) past it. +pub(crate) const UNITS: usize = COMMANDS * COMMAND_UNITS; + +#[pin_data] +pub(crate) struct Budget { + used: AtomicUsize, + limit: usize, + #[pin] + wait: Mutex<()>, + #[pin] + freed: CondVar, +} + +impl Budget { + pub(crate) fn new() -> Result> { + Self::with_limit(UNITS) + } + + pub(crate) fn with_limit(limit: usize) -> Result> { + Arc::pin_init( + pin_init!(Self { + used: AtomicUsize::new(0), + limit, + wait <- new_mutex!((), "g17::Budget::wait"), + freed <- new_condvar!("g17::Budget::freed"), + }), + GFP_KERNEL, + ) + } + + /// The queue has used its whole budget: a submission waits ([`Self::wait_for_room`]) before + /// it is taken. + pub(crate) fn full(&self) -> bool { + self.used.load(Ordering::Acquire) >= self.limit + } + + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn used(&self) -> usize { + self.used.load(Ordering::Acquire) + } + + /// Takes `units` until the returned charge drops. Never refused: a submission is admitted + /// whole once the queue is below its budget, so it may end up to one submission past it. + pub(crate) fn charge(self: &Arc, units: usize) -> Charge { + self.used.fetch_add(units, Ordering::AcqRel); + Charge { budget: self.clone(), units } + } + + /// Sleeps, interruptibly, until the queue is below its budget. Called without the queue's + /// lock: what frees the budget never takes it. + pub(crate) fn wait_for_room(&self) -> Result { + let mut guard = self.wait.lock(); + while self.full() { + if self.freed.wait_interruptible(&mut guard) { + return Err(ERESTARTSYS); + } + } + Ok(()) + } +} + +impl crate::queue::Room for Budget { + fn wait(&self) -> Result { + self.wait_for_room() + } +} + +/// Units of a [`Budget`] held by whatever owns the charged memory. +pub(crate) struct Charge { + budget: Arc, + units: usize, +} + +impl Drop for Charge { + fn drop(&mut self) { + let budget = &self.budget; + let before = budget.used.fetch_sub(self.units, Ordering::AcqRel); + // Only dropping below the budget can let a waiter in. Taking the lock orders this wake-up + // after a waiter's check, so it cannot miss it. + if before >= budget.limit && before - self.units < budget.limit { + let _guard = budget.wait.lock(); + budget.freed.notify_all(); + } + } +} + +#[kernel::macros::kunit_tests(asahi_g17_queue_budget)] +mod tests { + use super::*; + + #[test] + fn charges_fill_the_budget_until_they_drop() { + let budget = Budget::with_limit(10).unwrap(); + let first = budget.charge(4); + let second = budget.charge(6); + assert!(budget.full()); + drop(first); + assert!(!budget.full()); + assert_eq!(budget.used(), 6); + drop(second); + assert_eq!(budget.used(), 0); + // A submission is admitted whole below the budget, so a charge may pass it. + let large = budget.charge(25); + assert!(budget.full()); + drop(large); + assert!(!budget.full()); + } + + #[test] + fn a_waiter_wakes_once_a_charge_drops_elsewhere() { + let budget = Budget::with_limit(1).unwrap(); + let charge = budget.charge(1); + assert!(budget.full()); + // Dropped by another task, as the scheduler's free_job work or event work drops a + // packet while the submitter sleeps. + kernel::workqueue::system() + .try_spawn(GFP_KERNEL, move || { + kernel::time::delay::fsleep(kernel::time::Delta::from_millis(20)); + drop(charge); + }) + .unwrap(); + assert_eq!(budget.wait_for_room(), Ok(())); + assert!(!budget.full()); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 4df522c98daf9..c497c83652794 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -31,6 +31,7 @@ use kernel::{ static FENCE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); pub(crate) mod admission; +pub(crate) mod budget; mod outstanding; use outstanding::Outstanding; @@ -125,6 +126,8 @@ pub(crate) struct Queue { /// The commands and VM pins of the ioctl being submitted, kept empty between /// ioctls so their room is allocated once ([`Self::prepare_submission`]). scratch: Scratch, + /// What this queue's pending commands may keep allocated. + budget: Arc, // Closing the userspace queue releases admission even if firmware still // retains one of its execution contexts or installed physical graphs. _slot: admission::QueueSlot, @@ -184,6 +187,7 @@ impl Queue { finished: KVVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], scratch: Scratch::default(), + budget: budget::Budget::new()?, _slot: slot, }) } @@ -411,6 +415,20 @@ impl Queue { checked_inputs.push(ready.clone(), GFP_KERNEL)?; } } + // Charged until the memory goes: the packet's own state and vectors, its scheduler job's + // dependencies (held until the job runs, so no later than the packet), and the + // timestamp waits its frontier entries keep. Links go with the publication. + let charge = self.budget.charge( + budget::COMMAND_UNITS + + checked_inputs.len() + + firmware.len() + + dependencies.len() + + inherited_timestamp_waits.as_ref().map_or(0, |waits| waits.len()), + ); + let publication = publication.map(|publication| { + let links = publication.links(); + publication.with_charge(self.budget.charge(links)) + }); // Publish from the ioctl whenever nothing has to wait, at any depth. // The backend falls back to the scheduler behind any backlog or on any // capacity miss, so submission order is preserved. @@ -423,6 +441,7 @@ impl Queue { completion, checked_inputs, firmware, + charge, )?; let scheduler = match engine { Engine::Render => &mut self.render, @@ -527,7 +546,17 @@ impl Queue { } } +/// A queue's [`crate::queue::Queue::room`]: none while its pending commands hold its whole budget. +fn room(budget: &Arc) -> Option> { + let _ = budget; + None +} + impl crate::queue::Queue for Queue { + fn room(&self) -> Option> { + room(&self.budget) + } + fn set_compute_timeout(&mut self, requested_ms: u32) -> Result { // The compute scheduler takes the allowance when the first compute command creates it. if self.compute.is_some() { diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index fd1d332a99aec..0c1427f7a68c5 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -170,6 +170,12 @@ struct TvbUser { seen: TvbUse, } +/// What a submission to a full queue sleeps on until the queue has room ([`Queue::room`]). +pub(crate) trait Room: Send + Sync { + /// Sleeps, interruptibly, until the queue has room: ERESTARTSYS on a signal. + fn wait(&self) -> Result; +} + /// Trait implemented by all versioned queues. pub(crate) trait Queue: Send + Sync { /// Sets the watchdog allowance of the queue's compute commands to `requested_ms` @@ -203,6 +209,12 @@ pub(crate) trait Queue: Send + Sync { objects: Pin<&xarray::XArray>>, ) -> Result; + /// What a submission must wait on, without the queue's lock, before the queue takes it: + /// `None` when it has room. Queues without a bound on pending work always have room. + fn room(&self) -> Option> { + None + } + /// Waits for the work submitted so far to finish, before the mappings of a closing /// client go. Queues whose VMs keep user mappings for accepted jobs need not wait. fn drain(&mut self) {} From 445e8c7a2a624a00c96faac84d1ad7390441b63c Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 03:42:53 -0300 Subject: [PATCH 02/10] drm/asahi: g17: make a submission wait while its queue is full A G17 queue now reports itself full once its pending commands hold its whole budget, and the submit ioctl sleeps until they have given enough of it back. As amdgpu's CS ioctl waits for the job sched_jobs submissions back, the wait is interruptible and comes before anything is published. It cannot wait on itself. Every input is a fence that exists when the submission is made (an unmaterialized timeline point is refused), and userspace keeps wait-before-signal in its own submit thread, so the commands holding the budget depend only on accepted work and existing fences, which the watchdog and recovery end in finite time. A failed or killed VM's commands are cancelled and freed like any others, and the next submission is then refused with EIO. The sleep holds no queue, device or VM lock and no preparation lease, so nothing that frees the budget waits for it. Userspace needs no change: Borealis and the Gallium driver see a submission that takes longer, as on amdgpu, and libdrm restarts an interrupted one. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/mod.rs | 17 +++++++++++++++-- include/uapi/drm/asahi_drm.h | 3 +++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index c497c83652794..639e7d7bf0b6a 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -548,8 +548,7 @@ impl Queue { /// A queue's [`crate::queue::Queue::room`]: none while its pending commands hold its whole budget. fn room(budget: &Arc) -> Option> { - let _ = budget; - None + budget.full().then(|| budget.clone() as Arc) } impl crate::queue::Queue for Queue { @@ -1029,6 +1028,20 @@ mod tests { } } + #[test] + fn a_queue_has_room_until_its_pending_commands_hold_the_budget() { + let budget = budget::Budget::with_limit(4).unwrap(); + assert!(room(&budget).is_none()); + let pending = budget.charge(3); + assert!(room(&budget).is_none()); + let more = budget.charge(1); + // Full: the next submission sleeps on the budget without the queue's lock. + assert!(room(&budget).is_some()); + drop(pending); + assert!(room(&budget).is_none()); + drop(more); + } + #[test] fn transitive_render_chains_publication_without_host_wait() { let none = frontier([]); diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index fb91658169745..bb94746c4e6c9 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -658,6 +658,9 @@ struct drm_asahi_vm_status { * and execution context, returning an allocation error if resources run out. * @max_in_flight_per_queue: Hardware scheduler credits per queue. Software * may enqueue additional jobs, which wait behind preceding work/dependencies. + * SUBMIT sleeps, interruptibly, while the queue's pending jobs already hold + * the state the kernel allows one queue (about 2048 jobs), and takes the + * submission once earlier jobs have finished. * @flags: Reserved, zero. * @pad: Reserved, zero. * From 1a9a915a106597e32d76cda6faf2913ad8fcc1cf Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 15:44:48 -0300 Subject: [PATCH 03/10] drm/asahi: g17: keep the submission order window above the queue budget A context refuses a new submission with EBUSY once ORDER_WINDOW (1024) of its submissions wait behind the oldest one still waiting for its work-state node (WorkStateLease::deferred()). Vulkan sees a lost device. The queue budget is meant to make a submitter sleep instead, but it counts commands: a client submitting one dependency-free command per ioctl can queue 2048 behind a stalled job, so the window refused it first. On an M4 Pro (7.3.0-m4.205 with the budget backported) a compute stream of 0.5 ms kicks at depth 4096 got that EBUSY while its queue held about half its budget. Make the window 4096 submissions, 512 bytes of bits per context, and assert that it stays above the most submissions the budget lets wait: each holds at least one command's units, and one submission of up to MAX_COMMANDS_PER_SUBMISSION is admitted below the budget, so at most 2048 + 64. A full queue then always makes its submitter sleep before the window could refuse it. Order's bitmap is indexed modulo the window and walked by Order::pass(), which needs no other change. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context/identity.rs | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index fabed7ae649d3..ce55403d8ca92 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -97,8 +97,19 @@ impl WorkStates { } /// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the -/// turn remembered for ioctls that left early. -pub(super) const ORDER_WINDOW: u64 = 1024; +/// turn remembered for ioctls that left early. A submission past it is refused (EBUSY, a lost +/// device to Vulkan), so it is kept above the most submissions the queue's budget lets wait +/// ([`super::super::queue::budget`]): a full queue makes its submitter sleep first. 512 bytes of +/// bits per context. +pub(super) const ORDER_WINDOW: u64 = 4096; + +// Every waiting submission holds at least one command's units, and one submission is admitted +// below the budget whatever its size. +const _: () = assert!( + ORDER_WINDOW + > (super::super::queue::budget::UNITS / super::super::queue::budget::COMMAND_UNITS + + crate::file::MAX_COMMANDS_PER_SUBMISSION as usize) as u64 +); /// The order in which a context's ioctls take work-state nodes. /// @@ -374,6 +385,26 @@ mod tests { assert!(!order.leave(a)); } + #[test] + fn single_command_submissions_fill_the_budget_before_the_window() { + use crate::g17::queue::budget::{Budget, COMMAND_UNITS}; + // Submissions of one dependency-free command each, queued behind an oldest one that never + // takes its node (a stalled producer): the queue's budget must make the submitter sleep + // before the order window would refuse a submission with EBUSY. + let budget = Budget::new().unwrap(); + let mut order = Order::new(); + let mut charges = KVec::new(); + let mut submissions = 0; + while !budget.full() && order.assign().is_some() { + charges.push(budget.charge(COMMAND_UNITS), GFP_KERNEL).unwrap(); + submissions += 1; + } + // The window never refused one: the budget filled first, past the old window of 1024. + assert!(budget.full()); + assert!(order.assign().is_some()); + assert!(submissions > 1024); + } + #[test] fn no_ioctl_is_ordered_past_the_window() { let mut order = Order::new(); From 5f940654b4e67dbedb73ac5524e9b1e6483f3732 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 20:52:59 -0300 Subject: [PATCH 04/10] drm/asahi: g17: give a queue four times the pending budget Cyberpunk 2077 filled the queue budget. On an M4 Pro (7.3.0-m4.211 with the budget backported) its two busiest queues peaked at 311,000 and 309,000 of the 262,144 units, read from the inlined charges with kprobes, so their submitters slept. They held 555 and 522 pending commands: 71,000 units of command state, and about 240,000 units of references, 430 per command (publication links, firmware producer fences and scheduler dependencies). Make the budget 2^20 units, about 32 MB per queue if it were all links, three times that peak. A queue whose commands wait on nothing may now keep 8192 pending, so up to 8192 + 64 submissions wait, past the submission order window of 4096. Make the window 16384 (2 KB of bits per context) to keep the assert that a full queue makes its submitter sleep before the window could refuse it. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context/identity.rs | 6 +++--- drivers/gpu/drm/asahi/g17/queue/budget.rs | 15 ++++++--------- include/uapi/drm/asahi_drm.h | 5 +++-- 3 files changed, 12 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index ce55403d8ca92..1408a22db1e6c 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -99,9 +99,9 @@ impl WorkStates { /// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the /// turn remembered for ioctls that left early. A submission past it is refused (EBUSY, a lost /// device to Vulkan), so it is kept above the most submissions the queue's budget lets wait -/// ([`super::super::queue::budget`]): a full queue makes its submitter sleep first. 512 bytes of -/// bits per context. -pub(super) const ORDER_WINDOW: u64 = 4096; +/// ([`super::super::queue::budget`]): a full queue makes its submitter sleep first. 2 KB of bits +/// per context. +pub(super) const ORDER_WINDOW: u64 = 16384; // Every waiting submission holds at least one command's units, and one submission is admitted // below the budget whatever its size. diff --git a/drivers/gpu/drm/asahi/g17/queue/budget.rs b/drivers/gpu/drm/asahi/g17/queue/budget.rs index e3bf99414c5d6..41c209d244c93 100644 --- a/drivers/gpu/drm/asahi/g17/queue/budget.rs +++ b/drivers/gpu/drm/asahi/g17/queue/budget.rs @@ -17,19 +17,16 @@ use kernel::{ }; use core::sync::atomic::{AtomicUsize, Ordering}; -/// The commands a queue may keep pending when they hold no references, a policy constant: about -/// 2.3 times the deepest queue measured (Cyberpunk 2077, 874 commands pending on one queue on an -/// M4 Pro; a Hearthstone session, 339). That is 32 times the queue's hardware credits there (32 -/// render and 32 compute); amdgpu's default software queue is 16 times its hardware depth. -pub(crate) const COMMANDS: usize = 2048; - /// One command's own state: its packet with the validated command, its completion and frontier /// entries, about 2.5 KB, or 80 publication links (32 bytes, the largest reference), rounded up. pub(crate) const COMMAND_UNITS: usize = 128; -/// The whole budget of one queue: about 8 MB of what its pending commands hold however it is made -/// up (as links), and one submission (sized by its own arguments) past it. -pub(crate) const UNITS: usize = COMMANDS * COMMAND_UNITS; +/// The whole budget of one queue, a policy constant: about 32 MB of what its pending commands hold +/// however it is made up (as links), and one submission (sized by its own arguments) past it. +/// Cyberpunk 2077's busiest queue (an M4 Pro, 555 commands pending, about 430 references each) +/// peaked at about 311,000 units, so this leaves it more than 3 times that. A queue of commands +/// holding no references may keep 8192 pending (64 hardware credits' worth 128 times over). +pub(crate) const UNITS: usize = 1 << 20; #[pin_data] pub(crate) struct Budget { diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index bb94746c4e6c9..981f6d95847f1 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -659,8 +659,9 @@ struct drm_asahi_vm_status { * @max_in_flight_per_queue: Hardware scheduler credits per queue. Software * may enqueue additional jobs, which wait behind preceding work/dependencies. * SUBMIT sleeps, interruptibly, while the queue's pending jobs already hold - * the state the kernel allows one queue (about 2048 jobs), and takes the - * submission once earlier jobs have finished. + * the state the kernel allows one queue (8192 jobs that wait on nothing, + * fewer when each waits on many others), and takes the submission once + * earlier jobs have finished. * @flags: Reserved, zero. * @pad: Reserved, zero. * From 37a52ffe7a6d0f147b51fec05c1800f5d39555db Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 23:58:44 -0300 Subject: [PATCH 05/10] Revert "drm/asahi: g17: give a queue four times the pending budget" This reverts commit 5f940654b4e67dbedb73ac5524e9b1e6483f3732. The 4x budget was a stopgap for Cyberpunk filling the queue. The way forward is to cut the references a command holds at their source, which the budget then needs no extra room for, so the budget goes back to 2^18 units and the order window to 4096. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context/identity.rs | 6 +++--- drivers/gpu/drm/asahi/g17/queue/budget.rs | 15 +++++++++------ include/uapi/drm/asahi_drm.h | 5 ++--- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index 1408a22db1e6c..ce55403d8ca92 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -99,9 +99,9 @@ impl WorkStates { /// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the /// turn remembered for ioctls that left early. A submission past it is refused (EBUSY, a lost /// device to Vulkan), so it is kept above the most submissions the queue's budget lets wait -/// ([`super::super::queue::budget`]): a full queue makes its submitter sleep first. 2 KB of bits -/// per context. -pub(super) const ORDER_WINDOW: u64 = 16384; +/// ([`super::super::queue::budget`]): a full queue makes its submitter sleep first. 512 bytes of +/// bits per context. +pub(super) const ORDER_WINDOW: u64 = 4096; // Every waiting submission holds at least one command's units, and one submission is admitted // below the budget whatever its size. diff --git a/drivers/gpu/drm/asahi/g17/queue/budget.rs b/drivers/gpu/drm/asahi/g17/queue/budget.rs index 41c209d244c93..e3bf99414c5d6 100644 --- a/drivers/gpu/drm/asahi/g17/queue/budget.rs +++ b/drivers/gpu/drm/asahi/g17/queue/budget.rs @@ -17,16 +17,19 @@ use kernel::{ }; use core::sync::atomic::{AtomicUsize, Ordering}; +/// The commands a queue may keep pending when they hold no references, a policy constant: about +/// 2.3 times the deepest queue measured (Cyberpunk 2077, 874 commands pending on one queue on an +/// M4 Pro; a Hearthstone session, 339). That is 32 times the queue's hardware credits there (32 +/// render and 32 compute); amdgpu's default software queue is 16 times its hardware depth. +pub(crate) const COMMANDS: usize = 2048; + /// One command's own state: its packet with the validated command, its completion and frontier /// entries, about 2.5 KB, or 80 publication links (32 bytes, the largest reference), rounded up. pub(crate) const COMMAND_UNITS: usize = 128; -/// The whole budget of one queue, a policy constant: about 32 MB of what its pending commands hold -/// however it is made up (as links), and one submission (sized by its own arguments) past it. -/// Cyberpunk 2077's busiest queue (an M4 Pro, 555 commands pending, about 430 references each) -/// peaked at about 311,000 units, so this leaves it more than 3 times that. A queue of commands -/// holding no references may keep 8192 pending (64 hardware credits' worth 128 times over). -pub(crate) const UNITS: usize = 1 << 20; +/// The whole budget of one queue: about 8 MB of what its pending commands hold however it is made +/// up (as links), and one submission (sized by its own arguments) past it. +pub(crate) const UNITS: usize = COMMANDS * COMMAND_UNITS; #[pin_data] pub(crate) struct Budget { diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 981f6d95847f1..bb94746c4e6c9 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -659,9 +659,8 @@ struct drm_asahi_vm_status { * @max_in_flight_per_queue: Hardware scheduler credits per queue. Software * may enqueue additional jobs, which wait behind preceding work/dependencies. * SUBMIT sleeps, interruptibly, while the queue's pending jobs already hold - * the state the kernel allows one queue (8192 jobs that wait on nothing, - * fewer when each waits on many others), and takes the submission once - * earlier jobs have finished. + * the state the kernel allows one queue (about 2048 jobs), and takes the + * submission once earlier jobs have finished. * @flags: Reserved, zero. * @pad: Reserved, zero. * From b307da2c93b37ce7912ef7ba5ab6047ee06dfccb Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 13:53:15 -0300 Subject: [PATCH 06/10] Revert "drm/asahi: g17: keep the submission order window above the queue budget" This reverts commit 1a9a915a10659. Main now has ORDER_WINDOW 2048 with work-state lease splits capped at half of it, and that window is already enough for the queue budget: a following commit asserts and tests it. The larger window this commit set is not needed. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context/identity.rs | 35 ++----------------- 1 file changed, 2 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index ce55403d8ca92..fabed7ae649d3 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -97,19 +97,8 @@ impl WorkStates { } /// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the -/// turn remembered for ioctls that left early. A submission past it is refused (EBUSY, a lost -/// device to Vulkan), so it is kept above the most submissions the queue's budget lets wait -/// ([`super::super::queue::budget`]): a full queue makes its submitter sleep first. 512 bytes of -/// bits per context. -pub(super) const ORDER_WINDOW: u64 = 4096; - -// Every waiting submission holds at least one command's units, and one submission is admitted -// below the budget whatever its size. -const _: () = assert!( - ORDER_WINDOW - > (super::super::queue::budget::UNITS / super::super::queue::budget::COMMAND_UNITS - + crate::file::MAX_COMMANDS_PER_SUBMISSION as usize) as u64 -); +/// turn remembered for ioctls that left early. +pub(super) const ORDER_WINDOW: u64 = 1024; /// The order in which a context's ioctls take work-state nodes. /// @@ -385,26 +374,6 @@ mod tests { assert!(!order.leave(a)); } - #[test] - fn single_command_submissions_fill_the_budget_before_the_window() { - use crate::g17::queue::budget::{Budget, COMMAND_UNITS}; - // Submissions of one dependency-free command each, queued behind an oldest one that never - // takes its node (a stalled producer): the queue's budget must make the submitter sleep - // before the order window would refuse a submission with EBUSY. - let budget = Budget::new().unwrap(); - let mut order = Order::new(); - let mut charges = KVec::new(); - let mut submissions = 0; - while !budget.full() && order.assign().is_some() { - charges.push(budget.charge(COMMAND_UNITS), GFP_KERNEL).unwrap(); - submissions += 1; - } - // The window never refused one: the budget filled first, past the old window of 1024. - assert!(budget.full()); - assert!(order.assign().is_some()); - assert!(submissions > 1024); - } - #[test] fn no_ioctl_is_ordered_past_the_window() { let mut order = Order::new(); From 62886a7f9ddf9bacea4ae68269249d6cc2785ccb Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 01:37:03 -0300 Subject: [PATCH 07/10] drm/asahi: g17: check that a full queue sleeps before the order window refuses A context refuses a new submission with EBUSY, a lost device to Vulkan, once ORDER_WINDOW ordinals wait behind its oldest one. The queue budget must make a submitter sleep before that can happen. Every ordinal ahead of the turn that has not left is the lease of at least one pending command (a split is taken only for a following command), a submission is admitted only while its queue holds less than its budget, and each pending command holds at least COMMAND_UNITS of it. So an admitted submission finds fewer than UNITS / COMMAND_UNITS such ordinals, and the window of 2048 is enough for the budget of 2048 commands' worth. Assert that, and test it with multi-command submissions that split as often as the split cap allows, mixed with single-command ones, behind a stalled oldest ordinal. With a window of 1024 the test is refused. Ordinals of submissions that failed before their turn still count until the turn passes them; the budget does not bound those. Signed-off-by: Jonathan Goyvaerts (cherry picked from commit e0a2577ef83e7961b3291f1f25527b08488b0307) --- drivers/gpu/drm/asahi/g17/context/identity.rs | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index 5af933d0584da..5942c0b4ecbd3 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -104,6 +104,18 @@ pub(super) const ORDER_WINDOW: u64 = 2048; /// [`ORDER_WINDOW`] permanently reserved for new ioctls. pub(super) const ORDER_SPLIT_LIMIT: u64 = ORDER_WINDOW / 2; +// A full queue makes its submitter sleep before the window can refuse it (EBUSY, a lost device +// to Vulkan). Every ordinal ahead of the turn that has not left is the lease of at least one +// pending command: a split is taken only for a following command. A submission is admitted only +// while its queue holds less than its budget, and each pending command holds at least +// COMMAND_UNITS of it (`queue::budget`). So an admitted submission finds fewer than +// UNITS / COMMAND_UNITS such ordinals. Ordinals of submissions that left early (they failed +// before their turn) still count until the turn passes them; the budget does not bound those. +const _: () = assert!( + ORDER_WINDOW + >= (super::super::queue::budget::UNITS / super::super::queue::budget::COMMAND_UNITS) as u64 +); + /// The order in which a context's ioctls take work-state nodes. /// /// Each engine admits a context's ioctls in submission order, but the engines advance @@ -402,6 +414,37 @@ mod tests { assert!(order.assign().is_some()); } + #[test] + fn an_admitted_submission_always_finds_room_in_the_window() { + use crate::g17::queue::budget::{Budget, COMMAND_UNITS}; + // Behind an oldest ordinal that never takes its node, submissions arrive while the queue + // has budget left: first 64-command ones that split as often as they may (each split + // carries a command), then single-command ones, which take the most ordinals for their + // units. Each is admitted whole and charges its commands. The window must take every + // admitted one; the next sleeps on the budget. + let budget = Budget::new().unwrap(); + let mut order = Order::new(); + let mut charges = KVec::new(); + let mut submissions = 0u32; + let mut refused = 0u32; + while !budget.full() { + if order.assign().is_none() { + refused += 1; + break; + } + let commands = if submissions < 8 { 64 } else { 1 }; + for command in 0..commands { + if command > 0 { + let _ = order.assign_split(); + } + charges.push(budget.charge(COMMAND_UNITS), GFP_KERNEL).unwrap(); + } + submissions += 1; + } + assert_eq!(refused, 0); + assert!(budget.full()); + } + #[test] fn split_ordinals_reserve_half_the_window_for_new_ioctls() { let mut order = Order::new(); From 05ef58ba2dd5184a60711b515eb713f3448baeb9 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 16:20:23 -0500 Subject: [PATCH 08/10] drm/asahi: reclaim departed ordinals and wake budget waiters on teardown Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/file.rs | 69 ++++++----- drivers/gpu/drm/asahi/g17/context.rs | 2 +- drivers/gpu/drm/asahi/g17/context/identity.rs | 109 ++++++++---------- drivers/gpu/drm/asahi/g17/queue/budget.rs | 71 +++++++----- drivers/gpu/drm/asahi/g17/queue/mod.rs | 20 ++-- drivers/gpu/drm/asahi/g17/status.rs | 28 ++++- drivers/gpu/drm/asahi/queue/mod.rs | 9 +- 7 files changed, 172 insertions(+), 136 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index c2cc1464d56ab..b550d2540737c 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -379,6 +379,14 @@ fn admit_bind( ledger.admit(client, BOUND_OBJECT_BYTES) } +/// Closing the handle can wake a submitter independently of the queue's ioctl mutex. +#[pin_data] +struct QueueHandle { + admission: Option>, + #[pin] + state: Mutex, +} + /// A queue in a file's table. Its count in the creating process's share of the device's /// queues is given back once the queue itself is gone. pub(crate) struct TableQueue { @@ -394,7 +402,7 @@ impl TableQueue { const REUSE_CMDBUF_CAP: usize = 4096; /// Takes the cached command-buffer staging allocation so userspace copies run outside the - /// queue mutex (preventing `queue.lock()` -> `mmap_lock` lock-order inversion). + /// queue mutex (preventing `queue.state.lock()` -> `mmap_lock` lock-order inversion). fn take_cmdbuf(&mut self) -> KVVec { core::mem::take(&mut self.cmdbuf) } @@ -442,7 +450,7 @@ pub(crate) struct File { // Fields drop in order: the queues go first, so that a closing client's submitted work // can finish before its VMs unmap the user ranges. // #[pin] - queues: xarray::XArray>>, + queues: xarray::XArray>, // #[pin] vms: xarray::XArray>, // #[pin] @@ -554,7 +562,7 @@ impl File { let raw_queues = addr_of_mut!((*slot).queues); pin_init::raw_try_init( raw_queues, - xarray::XArray::>>::new( + xarray::XArray::>::new( xarray::AllocKind::Alloc1, ), )?; @@ -584,7 +592,7 @@ impl File { } #[allow(clippy::type_complexity)] - fn queues(self: Pin<&Self>) -> Pin<&xarray::XArray>>> { + fn queues(self: Pin<&Self>) -> Pin<&xarray::XArray>> { // SAFETY: Structural pinned projection for queues. // We never move out of this field. unsafe { self.map_unchecked(|s| &s.queues) } @@ -1537,13 +1545,13 @@ impl File { .queues() .find(index, usize::MAX) .map(|(idx, guard)| { - let queue: Arc> = guard.borrow().into(); + let queue: Arc = guard.borrow().into(); (idx, queue) }) else { break; }; - queue.lock().drain(); + queue.state.lock().drain(); if idx == usize::MAX { break; } @@ -1557,10 +1565,10 @@ impl File { let mut index = 0; while let Some((idx, entry)) = this.vms().find(index, usize::MAX) { let vm: &Vm = entry.borrow(); - if which(vm) { - if let Some(status) = vm.vm.status() { - status.mark_client_closed(); - } + let status = if which(vm) { vm.vm.status().cloned() } else { None }; + drop(entry); + if let Some(status) = status { + status.mark_client_closed(); } if idx == usize::MAX { break; @@ -1852,10 +1860,13 @@ impl File { data.queue_id = resv.index().try_into()?; resv.fill(Arc::pin_init( - new_mutex!(TableQueue { - queue, - cmdbuf: KVVec::new(), - _share: share, + pin_init!(QueueHandle { + admission: queue.admission(), + state <- new_mutex!(TableQueue { + queue, + cmdbuf: KVVec::new(), + _share: share, + }), }), GFP_KERNEL, )?)?; @@ -1872,11 +1883,9 @@ impl File { ) -> Result { // grab the queue so the xarray spinlock is dropped first let queue = file.inner().queues().remove(data.queue_id as usize); - if queue.is_none() { - Err(ENOENT) - } else { - Ok(0) - } + let queue = queue.ok_or(ENOENT)?; + if let Some(room) = &queue.admission { room.close(); } + Ok(0) } /// IOCTL: submit: Submit GPU work to a command submission queue. @@ -1902,7 +1911,7 @@ impl File { } // Upgrade to Arc to drop the XArray lock early - let queue: Arc> = file + let queue: Arc = file .inner() .queues() .lock() @@ -1931,11 +1940,11 @@ impl File { // Once G17 output syncobjs are resolved, its queue must install a fence // on every failure. Take the fallible userspace snapshot before that point, // staging into a buffer taken from the queue's reusable cache so user - // copies never execute under `queue.lock()`. + // copies never execute under `queue.state.lock()`. let mut cmdbuf = if guarded { - let mut buf = queue.lock().take_cmdbuf(); + let mut buf = queue.state.lock().take_cmdbuf(); if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { - queue.lock().return_cmdbuf(buf); + queue.state.lock().return_cmdbuf(buf); return Err(e); } Some(buf) @@ -1962,7 +1971,7 @@ impl File { Ok(syncs) => syncs, Err(e) => { if let Some(buf) = cmdbuf { - queue.lock().return_cmdbuf(buf); + queue.state.lock().return_cmdbuf(buf); } return Err(e); } @@ -1976,15 +1985,15 @@ impl File { id ); - // Copy the command buffer into the kernel outside `queue.lock()`. Because we + // Copy the command buffer into the kernel outside `queue.state.lock()`. Because we // need to iterate the command buffer twice, we do this in one big copy_from_user // to avoid TOCTOU issues. let cmdbuf = match cmdbuf.take() { Some(buf) => buf, None => { - let mut buf = queue.lock().take_cmdbuf(); + let mut buf = queue.state.lock().take_cmdbuf(); if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { - queue.lock().return_cmdbuf(buf); + queue.state.lock().return_cmdbuf(buf); return Err(e); } buf @@ -1996,13 +2005,13 @@ impl File { // nothing that frees the room takes, and check again under it. Nothing is published yet, // so a signal restarts the ioctl. let mut guard = loop { - let guard = queue.lock(); - let Some(room) = guard.queue.room() else { + let guard = queue.state.lock(); + let Some(room) = queue.admission.as_ref().filter(|room| room.must_wait()) else { break guard; }; drop(guard); if let Err(error) = room.wait() { - queue.lock().return_cmdbuf(cmdbuf); + queue.state.lock().return_cmdbuf(cmdbuf); return Err(error); } }; diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index cebeb73c78d9a..b13b4710f3bf3 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -364,7 +364,7 @@ impl Context { let render_id = Arc::pin_init(new_mutex!(render_id, "G17 context render pool identity"), GFP_KERNEL)?; let order = - Arc::pin_init(new_mutex!(Order::new(), "G17 context admission order"), GFP_KERNEL)?; + Arc::pin_init(new_mutex!(Order::new()?, "G17 context admission order"), GFP_KERNEL)?; Ok(Self { m5: alloc.uat.is_m5(), execution, diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index 5942c0b4ecbd3..694b6bca61967 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -96,8 +96,7 @@ impl WorkStates { } } -/// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the -/// turn remembered for ioctls that left early. +/// Maximum number of live ordinals waiting for a work-state node. pub(super) const ORDER_WINDOW: u64 = 2048; /// Cap for extra work-state splits inside multi-command ioctls, keeping the upper half of @@ -109,8 +108,7 @@ pub(super) const ORDER_SPLIT_LIMIT: u64 = ORDER_WINDOW / 2; // pending command: a split is taken only for a following command. A submission is admitted only // while its queue holds less than its budget, and each pending command holds at least // COMMAND_UNITS of it (`queue::budget`). So an admitted submission finds fewer than -// UNITS / COMMAND_UNITS such ordinals. Ordinals of submissions that left early (they failed -// before their turn) still count until the turn passes them; the budget does not bound those. +// UNITS / COMMAND_UNITS such ordinals. An early departure returns its slot immediately. const _: () = assert!( ORDER_WINDOW >= (super::super::queue::budget::UNITS / super::super::queue::budget::COMMAND_UNITS) as u64 @@ -137,81 +135,70 @@ const _: () = assert!( pub(super) struct Order { /// The next ordinal to hand out. next: u64, - /// The oldest ordinal that has neither taken a node nor left. - turn: u64, - /// Ordinals past the turn that left, as bits at ordinal % ORDER_WINDOW. - done: [u64; (ORDER_WINDOW / 64) as usize], - /// An ioctl was refused since the turn last moved: its publisher waits for the next move. + /// A FIFO of live tickets. Normal admission advances its head in constant time. + tickets: KVVec, + head: usize, + len: usize, refused: bool, } impl Order { - pub(super) const fn new() -> Self { - Self { + pub(super) fn new() -> Result { + Ok(Self { next: 0, - turn: 0, - done: [0; (ORDER_WINDOW / 64) as usize], + tickets: KVVec::from_elem(0, ORDER_WINDOW as usize, GFP_KERNEL)?, + head: 0, + len: 0, refused: false, - } + }) + } + fn slot(&self, offset: usize) -> usize { + (self.head + offset) % self.tickets.len() } - /// The ordinal of a new ioctl, in submission order. None while [`ORDER_WINDOW`] ioctls of - /// the context are past the oldest one still waiting for its node. pub(super) fn assign(&mut self) -> Option { - if self.next - self.turn >= ORDER_WINDOW { + if self.len == self.tickets.len() { return None; } let ordinal = self.next; self.next += 1; + let tail = self.slot(self.len); + self.tickets[tail] = ordinal; + self.len += 1; Some(ordinal) } - /// The ordinal of an extra work-state split within a multi-command ioctl. None once - /// [`ORDER_SPLIT_LIMIT`] ordinals are ahead of the turn so new ioctls keep full headroom. pub(super) fn assign_split(&mut self) -> Option { - if self.next - self.turn >= ORDER_SPLIT_LIMIT { - return None; - } + if self.len >= ORDER_SPLIT_LIMIT as usize { return None } self.assign() } - /// Whether the ioctl `ordinal` may take its node now: only at its turn. A refusal is - /// remembered until the turn next moves, so that move wakes the refused publisher. pub(super) fn admits(&mut self, ordinal: u64) -> bool { - let admits = ordinal == self.turn; + let admits = self.len != 0 && self.tickets[self.head] == ordinal; self.refused |= !admits; admits } - /// The ioctl `ordinal` took its node at its turn. Returns whether a refused ioctl may now be - /// admitted. pub(super) fn admit(&mut self, ordinal: u64) -> bool { - self.finish(ordinal) - } - /// The ioctl `ordinal` left without taking a node (it failed or was cancelled first). - /// Returns whether a refused ioctl may now be admitted. - pub(super) fn leave(&mut self, ordinal: u64) -> bool { - self.finish(ordinal) - } - fn finish(&mut self, ordinal: u64) -> bool { - if ordinal < self.turn { + if self.len == 0 || self.tickets[self.head] != ordinal { return false; } - if ordinal == self.turn { - self.pass(); - return core::mem::take(&mut self.refused); - } - // assign() keeps every ordinal within the window past the turn. - let bit = ordinal % ORDER_WINDOW; - self.done[(bit / 64) as usize] |= 1 << (bit % 64); - false + self.head = self.slot(1); + self.len -= 1; + core::mem::take(&mut self.refused) } - /// Moves the turn past the current ordinal and every following one already done. - fn pass(&mut self) { - loop { - self.turn += 1; - let bit = self.turn % ORDER_WINDOW; - let (word, mask) = ((bit / 64) as usize, 1u64 << (bit % 64)); - if self.done[word] & mask == 0 { + pub(super) fn leave(&mut self, ordinal: u64) -> bool { + if self.len == 0 || ordinal < self.tickets[self.head] { return false } + if self.tickets[self.head] == ordinal { return self.admit(ordinal) } + // Cancellation can remove a ticket anywhere. Compact only its younger + // neighbors, preserving their admission order across ring wraparound. + for offset in (1..self.len).rev() { + let index = self.slot(offset); + if self.tickets[index] == ordinal { + for pos in offset..self.len - 1 { + let dest = self.slot(pos); + self.tickets[dest] = self.tickets[self.slot(pos + 1)]; + } + self.len -= 1; break; } - self.done[word] &= !mask; } + false } } @@ -360,7 +347,7 @@ mod tests { #[test] fn ioctls_take_nodes_only_at_their_turn() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); let ordinals: [u64; 4] = core::array::from_fn(|_| order.assign().unwrap()); // Only the oldest waiting ioctl may take its node; the others are refused. for &ordinal in &ordinals[1..] { @@ -380,7 +367,7 @@ mod tests { #[test] fn ioctls_leaving_without_a_node_pass_the_turn() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); let (a, b, c, d) = ( order.assign().unwrap(), order.assign().unwrap(), @@ -400,15 +387,19 @@ mod tests { #[test] fn no_ioctl_is_ordered_past_the_window() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); let first = order.assign().unwrap(); let mut last = first; for _ in 1..ORDER_WINDOW { last = order.assign().unwrap(); } assert!(order.assign().is_none()); - // An ioctl leaving far ahead is remembered within the window. + // Keep the oldest blocked while more than a whole window of younger ioctls leave. assert!(!order.leave(last)); + for _ in 0..ORDER_WINDOW + 1 { + let replacement = order.assign().unwrap(); + assert!(!order.leave(replacement)); + } assert!(order.admits(first)); assert!(!order.admit(first)); assert!(order.assign().is_some()); @@ -423,7 +414,7 @@ mod tests { // units. Each is admitted whole and charges its commands. The window must take every // admitted one; the next sleeps on the budget. let budget = Budget::new().unwrap(); - let mut order = Order::new(); + let mut order = Order::new().unwrap(); let mut charges = KVec::new(); let mut submissions = 0u32; let mut refused = 0u32; @@ -447,7 +438,7 @@ mod tests { #[test] fn split_ordinals_reserve_half_the_window_for_new_ioctls() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); for _ in 0..ORDER_SPLIT_LIMIT { assert!(order.assign_split().is_some()); } @@ -460,7 +451,7 @@ mod tests { #[test] fn single_engine_admission_wakes_nobody() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); for _ in 0..24 { let ordinal = order.assign().unwrap(); assert!(order.admits(ordinal)); diff --git a/drivers/gpu/drm/asahi/g17/queue/budget.rs b/drivers/gpu/drm/asahi/g17/queue/budget.rs index e3bf99414c5d6..22ab9348f6124 100644 --- a/drivers/gpu/drm/asahi/g17/queue/budget.rs +++ b/drivers/gpu/drm/asahi/g17/queue/budget.rs @@ -10,12 +10,9 @@ //! submission waits, interruptibly, while the queue has used the whole budget, and the units come //! back as that memory is freed ([`Charge`]). -use kernel::{ - new_condvar, new_mutex, - prelude::*, - sync::{Arc, CondVar, Mutex}, -}; -use core::sync::atomic::{AtomicUsize, Ordering}; +use kernel::{prelude::*, sync::Arc}; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use crate::g17::status::VmStatus; /// The commands a queue may keep pending when they hold no references, a policy constant: about /// 2.3 times the deepest queue measured (Cyberpunk 2077, 874 commands pending on one queue on an @@ -35,29 +32,36 @@ pub(crate) const UNITS: usize = COMMANDS * COMMAND_UNITS; pub(crate) struct Budget { used: AtomicUsize, limit: usize, - #[pin] - wait: Mutex<()>, - #[pin] - freed: CondVar, + status: Arc, + closed: AtomicBool, } impl Budget { + pub(crate) fn for_vm(status: &Arc, limit: usize) -> Result> { + Arc::new(Self { + used: AtomicUsize::new(0), + limit, + status: status.clone(), + closed: AtomicBool::new(false), + }, GFP_KERNEL).map_err(Into::into) + } + + #[cfg(CONFIG_KUNIT = "y")] pub(crate) fn new() -> Result> { Self::with_limit(UNITS) } + #[cfg(CONFIG_KUNIT = "y")] pub(crate) fn with_limit(limit: usize) -> Result> { - Arc::pin_init( - pin_init!(Self { - used: AtomicUsize::new(0), - limit, - wait <- new_mutex!((), "g17::Budget::wait"), - freed <- new_condvar!("g17::Budget::freed"), - }), - GFP_KERNEL, - ) + Self::for_vm(&Arc::pin_init(VmStatus::new(), GFP_KERNEL)?, limit) } + pub(crate) fn close(&self) { + self.closed.store(true, Ordering::Release); + self.status.wake_budget_waiters(); + } + + /// The queue has used its whole budget: a submission waits ([`Self::wait_for_room`]) before /// it is taken. pub(crate) fn full(&self) -> bool { @@ -79,17 +83,19 @@ impl Budget { /// Sleeps, interruptibly, until the queue is below its budget. Called without the queue's /// lock: what frees the budget never takes it. pub(crate) fn wait_for_room(&self) -> Result { - let mut guard = self.wait.lock(); - while self.full() { - if self.freed.wait_interruptible(&mut guard) { - return Err(ERESTARTSYS); - } - } - Ok(()) + self.status.wait_for_budget(|| self.full(), || self.closed.load(Ordering::Acquire)) } } impl crate::queue::Room for Budget { + fn must_wait(&self) -> bool { + self.full() || self.closed.load(Ordering::Acquire) || self.status.client_closed() + } + + fn close(&self) { + Budget::close(self); + } + fn wait(&self) -> Result { self.wait_for_room() } @@ -108,8 +114,7 @@ impl Drop for Charge { // Only dropping below the budget can let a waiter in. Taking the lock orders this wake-up // after a waiter's check, so it cannot miss it. if before >= budget.limit && before - self.units < budget.limit { - let _guard = budget.wait.lock(); - budget.freed.notify_all(); + budget.status.wake_budget_waiters(); } } } @@ -136,6 +141,16 @@ mod tests { assert!(!budget.full()); } + #[test] + fn teardown_refuses_a_wait_without_a_charge_return() { + for vm in [false, true] { + let budget = Budget::with_limit(1).unwrap(); + let _external = budget.charge(1); + if vm { budget.status.mark_client_closed(); } else { budget.close(); } + assert_eq!(budget.wait_for_room(), Err(ENOENT)); + } + } + #[test] fn a_waiter_wakes_once_a_charge_drops_elsewhere() { let budget = Budget::with_limit(1).unwrap(); diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 7ea613972bbab..c47431ca26b5b 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -180,6 +180,7 @@ impl Queue { super::timeout::DEFAULT_ALLOWANCE_MS, )?); let failures = context.status().failures().finished; + let budget = budget::Budget::for_vm(context.status(), budget::UNITS)?; Ok(Self { dev: dev.into(), context, @@ -200,7 +201,7 @@ impl Queue { finished: KVVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], scratch: Scratch::default(), - budget: budget::Budget::new()?, + budget, _slot: slot, }) } @@ -564,14 +565,9 @@ impl Queue { } } -/// A queue's [`crate::queue::Queue::room`]: none while its pending commands hold its whole budget. -fn room(budget: &Arc) -> Option> { - budget.full().then(|| budget.clone() as Arc) -} - impl crate::queue::Queue for Queue { - fn room(&self) -> Option> { - room(&self.budget) + fn admission(&self) -> Option> { + Some(self.budget.clone()) } fn set_compute_timeout(&mut self, requested_ms: u32) -> Result { @@ -1091,14 +1087,14 @@ mod tests { #[test] fn a_queue_has_room_until_its_pending_commands_hold_the_budget() { let budget = budget::Budget::with_limit(4).unwrap(); - assert!(room(&budget).is_none()); + assert!(!crate::queue::Room::must_wait(&*budget)); let pending = budget.charge(3); - assert!(room(&budget).is_none()); + assert!(!crate::queue::Room::must_wait(&*budget)); let more = budget.charge(1); // Full: the next submission sleeps on the budget without the queue's lock. - assert!(room(&budget).is_some()); + assert!(crate::queue::Room::must_wait(&*budget)); drop(pending); - assert!(room(&budget).is_none()); + assert!(!crate::queue::Room::must_wait(&*budget)); drop(more); } diff --git a/drivers/gpu/drm/asahi/g17/status.rs b/drivers/gpu/drm/asahi/g17/status.rs index 5c062f8a2c8e8..33b9c15c838a7 100644 --- a/drivers/gpu/drm/asahi/g17/status.rs +++ b/drivers/gpu/drm/asahi/g17/status.rs @@ -23,6 +23,10 @@ pub(crate) struct VmStatus { reported_error: AtomicI32, /// The client's VM handle is gone: no client can see a lost device any more. client_closed: AtomicBool, + #[pin] + budget_wait_lock: Mutex<()>, + #[pin] + budget_wait: kernel::sync::CondVar, /// A queue of this VM went away while its work was still in the GPU, and the wait for that /// work ended. Never cleared. teardown_expired: AtomicBool, @@ -77,6 +81,8 @@ impl VmStatus { error: AtomicI32::new(0), reported_error: AtomicI32::new(0), client_closed: AtomicBool::new(false), + budget_wait_lock <- new_mutex!((), "G17 VM queue budget"), + budget_wait <- kernel::new_condvar!("G17 VM queue budget"), teardown_expired: AtomicBool::new(false), warned: AtomicBool::new(false), recovery_guilty: AtomicBool::new(false), @@ -152,16 +158,33 @@ impl VmStatus { self.client_closed.load(Ordering::Acquire) } + pub(crate) fn wait_for_budget(&self, full: impl Fn() -> bool, closed: impl Fn() -> bool) -> Result { + let mut guard = self.budget_wait_lock.lock(); + loop { + if closed() || self.client_closed() { return Err(ENOENT) } + if self.get() != 0 { return Err(EIO) } + if !full() { return Ok(()) } + if self.budget_wait.wait_interruptible(&mut guard) { return Err(ERESTARTSYS) } + } + } + + pub(crate) fn wake_budget_waiters(&self) { + let _guard = self.budget_wait_lock.lock(); + self.budget_wait.notify_all(); + } + /// Record permanent admission failure and report it to the client. #[track_caller] pub(crate) fn record(&self, error: Error) { self.report_failure(error); - let _ = self.error.compare_exchange( + if self.error.compare_exchange( 0, error.to_errno(), Ordering::SeqCst, Ordering::SeqCst, - ); + ).is_ok() { + self.wake_budget_waiters(); + } } pub(crate) fn reported_error(&self) -> i32 { @@ -275,6 +298,7 @@ impl VmStatus { /// more, even before its VM handle goes (the file drops its queues first). pub(crate) fn mark_client_closed(&self) { self.client_closed.store(true, Ordering::Release); + self.wake_budget_waiters(); } /// The client's VM handle is gone and nobody reads the mirror any more. The diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 0c1427f7a68c5..e8931b140233c 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -170,8 +170,10 @@ struct TvbUser { seen: TvbUse, } -/// What a submission to a full queue sleeps on until the queue has room ([`Queue::room`]). +/// What a submission to a full queue sleeps on until the queue has room ([`Queue::admission`]). pub(crate) trait Room: Send + Sync { + fn must_wait(&self) -> bool; + fn close(&self); /// Sleeps, interruptibly, until the queue has room: ERESTARTSYS on a signal. fn wait(&self) -> Result; } @@ -209,9 +211,8 @@ pub(crate) trait Queue: Send + Sync { objects: Pin<&xarray::XArray>>, ) -> Result; - /// What a submission must wait on, without the queue's lock, before the queue takes it: - /// `None` when it has room. Queues without a bound on pending work always have room. - fn room(&self) -> Option> { + /// A handle shared by submitters and queue destruction. Unbounded queues do not need one. + fn admission(&self) -> Option> { None } From 22e8797d9b93b3753d9e1ef2de614daa0968678a Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 17:04:58 -0500 Subject: [PATCH 09/10] drm/asahi: model the budget wake in the G15 input-error fixture The host fixture extracts VmStatus::record from the driver. Provide its wake hook in the fixture, where no thread is waiting on a queue budget, so the control and mutation cases exercise their input-error assertions again. Signed-off-by: DjDeveloperr --- tools/asahi/g15-input-error-tests.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/asahi/g15-input-error-tests.py b/tools/asahi/g15-input-error-tests.py index 0aa557e8dae80..008d4c688c151 100644 --- a/tools/asahi/g15-input-error-tests.py +++ b/tools/asahi/g15-input-error-tests.py @@ -46,6 +46,8 @@ def extract(text, marker): struct VmStatus{error:AtomicI32,reported_error:AtomicI32,client_closed:AtomicBool,teardown_expired:AtomicBool,warned:AtomicBool,recovery_guilty:AtomicBool,tgid:i32,comm:[u8;16],mirror:Mutex>} impl VmStatus { fn new(word:*mut i32)->Self{Self{error:AtomicI32::new(0),reported_error:AtomicI32::new(0),client_closed:AtomicBool::new(false),teardown_expired:AtomicBool::new(false),warned:AtomicBool::new(false),recovery_guilty:AtomicBool::new(false),tgid:1,comm:*b"host-test\0\0\0\0\0\0\0",mirror:Mutex(StdMutex::new(Some(Mirror{word})))}} + // This fixture has no submitters waiting for queue budget. + fn wake_budget_waiters(&self) {} __STATUS__ } mod g17 {use super::*;__POLICY__} From 81138b4d22f7a6de8e2b07d04a25a092d484c48d Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sat, 5 Dec 2026 03:41:57 -0300 Subject: [PATCH 10/10] drm/asahi: g17: charge a submission's input list to its queue's budget A pending command was charged for every fence it held, its input fences among them. Since its submission's inputs went into one list its commands share (Inputs), the list holds those fences, and nothing charged them: in_sync_count has no limit, so a queue behind a stalled job could keep any number of input fences alive past the budget. The list is now charged once, one unit per fence it holds and one for its merged fence, and gives the units back when its last command goes. A command whose compute sources take over some of its inputs, and so keeps a list of its own, is charged for that list the same way. The command's own charge still counts its scheduler dependencies, the input fences among them. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/mod.rs | 3 +- drivers/gpu/drm/asahi/g17/sync_input.rs | 59 ++++++++++++++++++------- tools/asahi/g17-command-inputs-tests.py | 18 +++++--- 3 files changed, 56 insertions(+), 24 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 4d85393717a58..9e745eeb01082 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -421,6 +421,7 @@ impl Queue { shared_inputs, inputs.iter().filter_map(|sync| sync.fence.as_ref()), |fence| sources.as_ref().is_some_and(|sources| sources.contains_input(fence)), + Some(&self.budget), )?; let input_dependencies = command_inputs.as_ref().map_or(&[][..], |inputs| inputs.dependencies()); @@ -810,7 +811,7 @@ impl crate::queue::Queue for Queue { Some(&output_fence), ); let shared_inputs = - Inputs::new(outputs.inputs().iter().filter_map(|sync| sync.fence.as_ref()))?; + Inputs::new(outputs.inputs().iter().filter_map(|sync| sync.fence.as_ref()), Some(&self.budget))?; let mut work_states = work_states.into_iter(); for entry in pending.iter_mut() { let guard = guards.next().ok_or(EIO)?; diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index a63d4267dad60..6a2f7e99e6937 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -4,6 +4,7 @@ //! because polling a container's status can signal it and run callbacks. use core::mem::MaybeUninit; +use super::queue::budget::Budget; use kernel::{bindings, dma_fence::{Fence, RawDmaFence}, prelude::*}; #[repr(C)] @@ -153,14 +154,17 @@ pub(crate) struct Inputs { /// One fence for all of them, past [`super::job::MERGED_DEPENDENCIES`]: what each command's /// scheduler job waits on instead of every input. merged: Option, + /// One unit of the queue's budget per fence the list holds, given back when the list goes. + _charge: Option, } impl Inputs { /// `None` when there is nothing to wait for. Userspace sets the count, so the list is charged /// to the caller and needs no contiguous pages. - pub(crate) fn new<'a>(inputs: impl IntoIterator) - -> Result>> - { + pub(crate) fn new<'a>( + inputs: impl IntoIterator, + budget: Option<&kernel::sync::Arc>, + ) -> Result>> { let mut fences = KVVec::new(); for fence in inputs { // An input that already signalled without error orders nothing and has no status left @@ -194,7 +198,8 @@ impl Inputs { } else { None }; - Ok(Some(kernel::sync::Arc::new(Self { fences, merged }, GFP_KERNEL_ACCOUNT)?)) + let _charge = budget.map(|budget| budget.charge(fences.len() + usize::from(merged.is_some()))); + Ok(Some(kernel::sync::Arc::new(Self { fences, merged, _charge }, GFP_KERNEL_ACCOUNT)?)) } #[cfg(CONFIG_KUNIT = "y")] @@ -250,6 +255,7 @@ pub(crate) fn command_inputs<'a>( shared: Option<&kernel::sync::Arc>, inputs: impl Iterator + Clone, covered: impl Fn(&Fence) -> bool, + budget: Option<&kernel::sync::Arc>, ) -> Result> { let Some(shared) = shared else { return Ok(None); @@ -258,7 +264,9 @@ pub(crate) fn command_inputs<'a>( return Ok(Some(shared.for_command()?)); } // Rare: the sources take over some inputs. Wait on the others only, in a list of its own. - Inputs::new(inputs.filter(|fence| !covered(fence)))?.map(|own| own.for_command()).transpose() + Inputs::new(inputs.filter(|fence| !covered(fence)), budget)? + .map(|own| own.for_command()) + .transpose() } /// One command's share of its submission's [`Inputs`]. @@ -569,7 +577,7 @@ mod inputs_tests { fn commands_of_one_submission_share_its_inputs() { let contexts = contexts(); let fences = unsignalled(&contexts, 64); - let inputs = Inputs::new(fences.iter()).unwrap().unwrap(); + let inputs = Inputs::new(fences.iter(), None).unwrap().unwrap(); let first = inputs.for_command().unwrap(); let second = inputs.for_command().unwrap(); // Every command still checks every input before publication. @@ -580,11 +588,28 @@ mod inputs_tests { assert!(first.dependencies().len() <= MERGED_DEPENDENCIES); } + #[test] + fn a_submissions_inputs_are_charged_once_until_its_last_command_goes() { + let contexts = contexts(); + let fences = unsignalled(&contexts, 64); + let budget = crate::g17::queue::budget::Budget::new().unwrap(); + let inputs = Inputs::new(fences.iter(), Some(&budget)).unwrap().unwrap(); + // 64 fences and the merged one, however many commands share them. + assert_eq!(budget.used(), 65); + let first = inputs.for_command().unwrap(); + let second = inputs.for_command().unwrap(); + assert_eq!(budget.used(), 65); + drop((inputs, first)); + assert_eq!(budget.used(), 65); + drop(second); + assert_eq!(budget.used(), 0); + } + #[test] fn a_few_inputs_stay_separate_dependencies() { let contexts = contexts(); let fences = unsignalled(&contexts, MERGED_DEPENDENCIES); - let inputs = Inputs::new(fences.iter()).unwrap().unwrap(); + let inputs = Inputs::new(fences.iter(), None).unwrap().unwrap(); let command = inputs.for_command().unwrap(); assert_eq!(command.dependencies().len(), MERGED_DEPENDENCIES); for (dependency, fence) in command.dependencies().iter().zip(fences.iter()) { @@ -596,7 +621,7 @@ mod inputs_tests { fn a_repeated_input_is_kept_once() { let contexts = contexts(); let fence = Fence::from_fence(&independent(&contexts).unwrap()); - let inputs = Inputs::new(core::iter::repeat(&fence).take(100)).unwrap().unwrap(); + let inputs = Inputs::new(core::iter::repeat(&fence).take(100), None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 1); assert_eq!(inputs.fences()[0].raw(), fence.raw()); } @@ -607,7 +632,7 @@ mod inputs_tests { let earlier = Fence::from_fence(&contexts.new_fence(0, CompletionFence).unwrap()); let later = Fence::from_fence(&contexts.new_fence(0, CompletionFence).unwrap()); let other = Fence::from_fence(&independent(&contexts).unwrap()); - let inputs = Inputs::new([&later, &other, &earlier]).unwrap().unwrap(); + let inputs = Inputs::new([&later, &other, &earlier], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 2); assert!(inputs.fences().iter().any(|fence| fence.raw() == later.raw())); assert!(inputs.fences().iter().any(|fence| fence.raw() == other.raw())); @@ -618,7 +643,7 @@ mod inputs_tests { let contexts = contexts(); let fences = unsignalled(&contexts, 2); let array = merge(&fences).unwrap(); - let inputs = Inputs::new([&array, &fences[0], &fences[1]]).unwrap().unwrap(); + let inputs = Inputs::new([&array, &fences[0], &fences[1]], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 2); for fence in fences.iter() { assert!(inputs.fences().iter().any(|kept| kept.raw() == fence.raw())); @@ -634,15 +659,15 @@ mod inputs_tests { heads.push(container.clone(), GFP_KERNEL).unwrap(); let sources = Sources::new(heads, KVec::new(), KVec::new(), KVec::new()).unwrap(); // The submission keeps the container's base fences, which the sources do not list. - let inputs = Inputs::new(core::iter::once(&container)).unwrap().unwrap(); + let inputs = Inputs::new(core::iter::once(&container), None).unwrap().unwrap(); assert!(inputs.fences().iter().all(|fence| !sources.contains_input(fence))); // Coverage is decided on the inputs as passed, so the command still waits on none. let covered = |fence: &Fence| sources.contains_input(fence); - assert!(command_inputs(Some(&inputs), core::iter::once(&container), covered).unwrap().is_none()); + assert!(command_inputs(Some(&inputs), core::iter::once(&container), covered, None).unwrap().is_none()); // With an input the sources leave, the command waits on that one only, in its own list. let other = Fence::from_fence(&independent(&contexts).unwrap()); - let both = Inputs::new([&container, &other]).unwrap().unwrap(); - let own = command_inputs(Some(&both), [&container, &other].into_iter(), covered) + let both = Inputs::new([&container, &other], None).unwrap().unwrap(); + let own = command_inputs(Some(&both), [&container, &other].into_iter(), covered, None) .unwrap() .unwrap(); assert!(!own.shares_with(&both.for_command().unwrap())); @@ -659,7 +684,7 @@ mod inputs_tests { failed.set_error(EIO); failed.signal(); let failed = Fence::from_fence(&failed); - let inputs = Inputs::new([&later, &failed]).unwrap().unwrap(); + let inputs = Inputs::new([&later, &failed], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 2); } @@ -669,13 +694,13 @@ mod inputs_tests { let done = independent(&contexts).unwrap(); done.signal(); let done = Fence::from_fence(&done); - assert!(Inputs::new(core::iter::once(&done)).unwrap().is_none()); + assert!(Inputs::new(core::iter::once(&done), None).unwrap().is_none()); let failed = independent(&contexts).unwrap(); failed.set_error(EIO); failed.signal(); let failed = Fence::from_fence(&failed); // A failed input keeps its status for the command to consume. - let inputs = Inputs::new([&done, &failed]).unwrap().unwrap(); + let inputs = Inputs::new([&done, &failed], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 1); assert_eq!(inputs.fences()[0].raw(), failed.raw()); } diff --git a/tools/asahi/g17-command-inputs-tests.py b/tools/asahi/g17-command-inputs-tests.py index df6d364cb69be..a2f0a696039f4 100755 --- a/tools/asahi/g17-command-inputs-tests.py +++ b/tools/asahi/g17-command-inputs-tests.py @@ -66,13 +66,19 @@ def build_harness(mutation=None): status: i32, }} +/// The queue budget the lists are charged to; not modelled. +struct Budget; + /// A submission's input fences not yet signalled without error. struct Inputs {{ fences: Vec, }} impl Inputs {{ - fn new<'a>(inputs: impl IntoIterator) -> Result>> {{ + fn new<'a>( + inputs: impl IntoIterator, + _budget: Option<&kernel::sync::Arc>, + ) -> Result>> {{ let fences: Vec = inputs.into_iter().filter(|fence| fence.status <= 0).copied().collect(); Ok((!fences.is_empty()).then(|| kernel::sync::Arc::new(Self {{ fences }}))) }} @@ -94,25 +100,25 @@ def build_harness(mutation=None): let b = Fence {{ id: 2, status: 0 }}; let done = Fence {{ id: 3, status: 1 }}; let all = [a, b, done]; - let shared = Inputs::new(all.iter()).unwrap(); + let shared = Inputs::new(all.iter(), None).unwrap(); // 1. No source covers an input: the command shares the submission's list. - let none = command_inputs(shared.as_ref(), all.iter(), |_| false).unwrap(); + let none = command_inputs(shared.as_ref(), all.iter(), |_| false, None).unwrap(); assert!(std::sync::Arc::ptr_eq(&none.as_ref().unwrap().0, shared.as_ref().unwrap()), "an uncovered command must share the submission's list"); assert_eq!(ids(&none), vec![1, 2]); // 2. Sources cover a: the command waits on b only, in a list of its own. - let part = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id == 1).unwrap(); + let part = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id == 1, None).unwrap(); assert_eq!(ids(&part), vec![2], "a partly covered command must wait on its uncovered inputs only"); assert!(!std::sync::Arc::ptr_eq(&part.as_ref().unwrap().0, shared.as_ref().unwrap())); // 3. Sources cover a and b; done has signalled: nothing to wait for. - let covered = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id != 3).unwrap(); + let covered = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id != 3, None).unwrap(); assert!(covered.is_none(), "a command its sources cover must wait on no input"); // 4. Nothing unsignalled in the submission: nothing to wait for. - assert!(command_inputs(None, [done].iter(), |_| false).unwrap().is_none()); + assert!(command_inputs(None, [done].iter(), |_| false, None).unwrap().is_none()); println!("PASS g17 command inputs"); }}