From 98e9ab5b4753bcab64e7af93bf307175e4600c9a Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Tue, 17 Nov 2026 15:57:28 -0300 Subject: [PATCH 1/3] drm/asahi: g17: reuse each queue's publication batch Every publication allocated a DeferredBatch with room for two rings of completions (64 entries, about 3.5 KB through kvmalloc) and freed it when the publication ended: on the direct compute and render paths this was a kvmalloc and a kvfree in every submit ioctl. The backend now keeps the batch of its last publication once it is finished and lends it to the next one. A batch that still holds work is dropped as before, and concurrent publishers of one queue (the two engines' scheduler workers and the ioctl) each get their own: the first one back is kept. The batches are created and used exactly as before. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/runtime.rs | 90 ++++++++++++++++++- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 2 +- .../drm/asahi/g17/runtime/render/submit.rs | 2 +- 3 files changed, 91 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index d193f7d64ee93..83bfaf2c8381e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -757,6 +757,10 @@ pub(super) struct Backend { /// Render pairs this owner may hold, fixed at creation with its scheduler's /// credits and its render pool's sizing. pairs: u8, + /// The publication batch of this owner's last publication, finished and kept for the + /// next one ([`Backend::publication_batch`]). + #[pin] + spare_batch: kernel::sync::Mutex>, } impl Backend { @@ -901,6 +905,7 @@ impl Backend { admission, direct_slot: core::sync::atomic::AtomicU32::new(0), pairs: super::pairs::per_owner(), + spare_batch <- kernel::new_mutex!(None, "g17::Backend::spare_batch"), }), GFP_KERNEL, )?, @@ -908,6 +913,17 @@ impl Backend { )) } + /// A publication batch: the one the last publication left, else a new one. + pub(super) fn publication_batch(&self) -> Result> { + // Take the spare first: a new batch is allocated without the lock held. + let spare = self.spare_batch.lock().take(); + let batch = match spare { + Some(batch) => batch, + None => DeferredBatch::publication()?, + }; + Ok(PublicationBatch { batch, spare: &self.spare_batch }) + } + /// The shared aperture has exactly one builder. Other queues sleep without /// holding the device mutex; recovery joins its lease before closing roots. fn shared_compute(&self, admission: &Admission<'_>) -> Result { @@ -1398,6 +1414,26 @@ impl DeferredBatch { batch.render = KVVec::with_capacity(crate::hw::t8140::queues::RENDER_SLOTS, GFP_KERNEL)?; Ok(batch) } + /// No room at all: allocates nothing. + fn empty() -> Self { + Self { + has_source_completions: false, + values: KVVec::new(), + bindings: KVVec::new(), + vacated: KVVec::new(), + render: KVVec::new(), + tvb: KVVec::new(), + } + } + /// Holds nothing: finished, or never used. + fn is_idle(&self) -> bool { + !self.has_source_completions + && self.values.is_empty() + && self.bindings.is_empty() + && self.vacated.is_empty() + && self.render.is_empty() + && self.tvb.is_empty() + } fn with_capacity(capacity: usize, detached: usize) -> Result { let render_slots = if detached != 0 { crate::hw::t8140::queues::RENDER_SLOTS @@ -1530,6 +1566,36 @@ impl DeferredBatch { } } +/// A [`DeferredBatch::publication`] lent by a [`Backend`]: an idle batch goes back to it when +/// the publication ends, so a steady stream of publications allocates none. +pub(super) struct PublicationBatch<'a> { + batch: DeferredBatch, + spare: &'a kernel::sync::Mutex>, +} +impl core::ops::Deref for PublicationBatch<'_> { + type Target = DeferredBatch; + fn deref(&self) -> &DeferredBatch { + &self.batch + } +} +impl core::ops::DerefMut for PublicationBatch<'_> { + fn deref_mut(&mut self) -> &mut DeferredBatch { + &mut self.batch + } +} +impl Drop for PublicationBatch<'_> { + fn drop(&mut self) { + // A batch still holding work drops it here, as an unlent batch would. + let batch = core::mem::replace(&mut self.batch, DeferredBatch::empty()); + if batch.is_idle() { + let mut spare = self.spare.lock(); + if spare.is_none() { + *spare = Some(batch); + } + } + } +} + struct ComputeHost<'a> { shared: &'a Arc, init: &'a super::initdata::InitData, @@ -2299,7 +2365,7 @@ impl Backend { packet.set_early_result(Err(ECANCELED)); return true; } - let mut deferred = match DeferredBatch::publication() { + let mut deferred = match self.publication_batch() { Ok(deferred) => deferred, Err(error) => { if packet.completion.status().get() != 0 { @@ -2968,6 +3034,28 @@ mod shared_capacity_tests { // published identity was cancelled or retyped to achieve the fit. } + #[test] + fn a_publication_batch_comes_back_only_when_idle() { + let spare = KBox::pin_init(kernel::new_mutex!(None::), GFP_KERNEL).unwrap(); + let lend = |batch| PublicationBatch { batch, spare: &spare }; + let first = DeferredBatch::publication().unwrap(); + let kept = first.values.as_ptr(); + drop(lend(first)); + let second = spare.lock().take().unwrap(); + assert_eq!(second.values.as_ptr(), kept); + // Holding work: dropped with it, not kept. + let mut busy = lend(second); + busy.has_source_completions = true; + drop(busy); + assert!(spare.lock().is_none()); + // Two lent at once: the first one back stays. + let (a, b) = (DeferredBatch::publication().unwrap(), DeferredBatch::publication().unwrap()); + let kept = a.values.as_ptr(); + drop(lend(a)); + drop(lend(b)); + assert_eq!(spare.lock().as_ref().unwrap().values.as_ptr(), kept); + } + #[test] fn a_reclaim_has_room_for_the_render_pools_it_gives_back() { assert!(!DeferredBatch::publication().unwrap().render_backing_room()); diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 278534899b570..bd54430a92ed9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -285,7 +285,7 @@ impl job::Backend for Backend { if let Some(result) = packet.early_result() { return result.map(|()| packet.completion.scheduler_fence()); } - let mut deferred = match DeferredBatch::publication() { + let mut deferred = match self.publication_batch() { Ok(batch) => batch, Err(error) => { self.release_backlog(&packet); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 70efc3cbb0f2b..1b00154eafddc 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -583,7 +583,7 @@ impl Backend { packet.set_early_result(Err(ECANCELED)); return true; } - let mut deferred = match DeferredBatch::publication() { + let mut deferred = match self.publication_batch() { Ok(deferred) => deferred, Err(error) => { if packet.completion.status().get() != 0 { From 6408757ed87c961e8069681cd8b81dafa820fbd5 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Tue, 17 Nov 2026 15:57:28 -0300 Subject: [PATCH 2/3] drm/asahi: g17: keep the submit ioctl's command vectors in the queue prepare_submission collected the validated commands and their VM pins in two vectors allocated by every submit ioctl and freed at its end. The queue now keeps both, empty between ioctls, so their room is allocated once. Commands are drained from them in the same order, and whatever an error leaves unsubmitted is released at the same point as before. Neither needs contiguous pages, and `pending` is large: up to 63 commands of over a kilobyte each come to an order-3 block. As KVecs that block was a GFP_KERNEL krealloc() that, on a machine without compaction, ended in the OOM killer during dEQP-VK runs. Keep them in KVVecs, so a large one falls back to vmalloc(), and charge them to the caller's memory cgroup (GFP_KERNEL_ACCOUNT), since each userspace queue keeps its own. They are freed with the queue, which may sleep. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/mod.rs | 46 ++++++++++++++++++-------- 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index d322c2710ab9e..83569aaead0f7 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -105,15 +105,24 @@ pub(crate) struct Queue { /// can tear a whole completion down; that waits until the ioctl has published. finished: KVec, failures: [FailureRecord; 2], + /// 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, // Closing the userspace queue releases admission even if firmware still // retains one of its execution contexts or installed physical graphs. _slot: admission::QueueSlot, } -type ValidatedBatch = ( - KVec<(Validated, Order, Destinations)>, - KVec, -); +/// Up to [`MAX_COMMANDS_PER_SUBMISSION`] commands. A validated command is over a kilobyte, +/// so `pending` would need a high-order block of contiguous pages; neither needs them. Each +/// userspace queue keeps its own, so they are charged to the caller. +/// +/// [`MAX_COMMANDS_PER_SUBMISSION`]: crate::file::MAX_COMMANDS_PER_SUBMISSION +#[derive(Default)] +struct Scratch { + pending: KVVec<(Validated, Order, Destinations)>, + guards: KVVec, +} impl Queue { pub(crate) fn new( @@ -155,6 +164,7 @@ impl Queue { frontiers: core::array::from_fn(|_| KVec::new()), finished: KVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], + scratch: Scratch::default(), _slot: slot, }) } @@ -436,14 +446,16 @@ impl Queue { .map_err(|_| ENOMEM)?; Ok(()) } - /// Finish parsing, validation and VM pinning before entering publication. - /// Keeping this frame separate bounds the scheduler/ioctl stack depth. + /// Finish parsing, validation and VM pinning before entering publication, into the + /// empty `scratch`. Keeping this frame separate bounds the scheduler/ioctl stack depth. #[inline(never)] fn prepare_submission( &mut self, bytes: &[u8], objects: Pin<&xarray::XArray>>, - ) -> Result { + scratch: &mut Scratch, + ) -> Result { + let Scratch { pending, guards } = scratch; // A refused submission reaches userspace as EINVAL alone, so name the step that // refused it: the command's own requirements are only one of several. let refused = |step: &str, error: kernel::error::Error| { @@ -463,7 +475,7 @@ impl Queue { // starts only after the entire ioctl has been validated and pinned. let base = self.sequence; let mut preceding = [0; 2]; - let mut pending = KVec::with_capacity(1, GFP_KERNEL)?; + pending.reserve(1, GFP_KERNEL_ACCOUNT)?; while let Some(command) = parser.next()? { let mut payload = self .proof @@ -506,11 +518,11 @@ impl Queue { } } .map_err(|error| refused("its timestamp destinations", error))?; - pending.push((payload, order, destinations), GFP_KERNEL)?; + pending.push((payload, order, destinations), GFP_KERNEL_ACCOUNT)?; } parser.finish()?; // Every accepted command pins the VM before any command is enqueued. - let mut guards = KVec::with_capacity(pending.len(), GFP_KERNEL)?; + guards.reserve(pending.len(), GFP_KERNEL_ACCOUNT)?; guards .push_within_capacity(parse_guard) .map_err(|_| ENOMEM)?; @@ -519,7 +531,7 @@ impl Queue { .push_within_capacity(self.context.vm().retain_job()?) .map_err(|_| ENOMEM)?; } - Ok((pending, guards)) + Ok(()) } } @@ -577,6 +589,7 @@ impl crate::queue::Queue for Queue { return Err(error); } }; + let mut scratch = core::mem::take(&mut self.scratch); let result = (|| { if !self.backend.supports_submission() { return Err(ENOTSUPP); @@ -584,7 +597,8 @@ impl crate::queue::Queue for Queue { if self.context.status().get() != 0 { return Err(EIO); } - let (mut pending, guards) = self.prepare_submission(bytes, objects)?; + self.prepare_submission(bytes, objects, &mut scratch)?; + let Scratch { pending, guards } = &mut scratch; if pending .iter() .any(|(command, _, _)| matches!(command, Validated::Render { .. })) @@ -596,7 +610,7 @@ impl crate::queue::Queue for Queue { command.allow_long_job(); } } - let mut guards = guards.into_iter(); + let mut guards = guards.drain_all(); // Where a firmware wait reports completion before a weak stream tail's writes are // visible, only a command that declares a visible completion is waited for there. let visible_required = self.backend.firmware_sources_need_visible_completion(); @@ -615,7 +629,7 @@ impl crate::queue::Queue for Queue { 0, Some(&output_fence), ); - for (command, order, destinations) in pending { + for (command, order, destinations) in pending.drain_all() { let guard = guards.next().ok_or(EIO)?; self.enqueue( id, @@ -629,6 +643,10 @@ impl crate::queue::Queue for Queue { } Ok(()) })(); + // What an error left unsubmitted is released here, as before the scratch was kept. + scratch.pending.clear(); + scratch.guards.clear(); + self.scratch = scratch; // Everything this ioctl publishes is visible; release what it pruned. self.finished.clear(); if let Err(error) = result { From 9c73f8ef6beb34a58a8c9a31cf02d76d675dcb0d Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Tue, 17 Nov 2026 16:03:25 -0300 Subject: [PATCH 3/3] drm/asahi: g17: build each packet in its allocation Packet::new built the packet, with its 1.3 KB validated command, on the stack and moved it into the Arc. The compiler kept three stack copies of the command for that, so every submitted command was copied four times here. Allocate the packet first and initialise it in place: the command is copied once. A failed allocation still drops the command unpublished. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/job.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index f5ddc1419361a..e4e5edeeba56c 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -13,7 +13,7 @@ use kernel::{ dma_fence::{Fence, RawDmaFence}, drm::sched, prelude::*, - sync::Arc, + sync::{Arc, UniqueArc}, }; pub(super) const TIMEOUT_MS: kernel::time::Msecs = super::timeout::POLL_MS; @@ -149,8 +149,10 @@ impl Packet { } Validated::Compute { .. } => None, }; - Ok(Arc::new( - Self { + // Allocated first and written in place: built on the stack, the command (about 1.3 KB) + // was copied three more times. + let packet = UniqueArc::new_uninit(GFP_KERNEL)?; + let Ok(packet) = packet.init_with(init!(Self { id, context, command, @@ -164,9 +166,8 @@ impl Packet { early: AtomicI32::new(0), backlog: AtomicBool::new(false), allowance_end: AtomicU64::new(0), - }, - GFP_KERNEL, - )?) + })); + Ok(packet.into()) } /// Its own watchdog still renews the job for the allowance its queue asked for at `now`