diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 2d6e2dd3b2bf3..2ef081524ebfe 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; @@ -156,8 +156,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, @@ -171,9 +173,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` diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index f480b7cda3dec..52a4cc27ca552 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -122,15 +122,24 @@ pub(crate) struct Queue { /// a submit on fragmentation. finished: KVVec, 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( @@ -174,6 +183,7 @@ impl Queue { publishers: [Outstanding::new(failures), Outstanding::new(failures)], finished: KVVec::new(), failures: [FailureRecord::new(), FailureRecord::new()], + scratch: Scratch::default(), _slot: slot, }) } @@ -417,14 +427,16 @@ impl Queue { self.frontiers[index].push_within_capacity(order.sequence, fences)?; 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| { @@ -444,7 +456,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 @@ -484,11 +496,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)?; @@ -497,7 +509,7 @@ impl Queue { .push_within_capacity(self.context.vm().retain_job()?) .map_err(|_| ENOMEM)?; } - Ok((pending, guards)) + Ok(()) } } @@ -555,6 +567,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); @@ -562,7 +575,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; let has_render = pending .iter() .any(|(command, _, _)| matches!(command, Validated::Render { .. })); @@ -588,7 +602,7 @@ impl crate::queue::Queue for Queue { for (publishers, room) in self.publishers.iter_mut().zip(room) { publishers.reserve(room)?; } - 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(); @@ -608,7 +622,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, @@ -622,6 +636,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 { diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index e64a10eb7d945..4ad94f28759db 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1360,6 +1360,10 @@ pub(super) struct Backend { pairs: u8, /// Physical compute channels this owner may hold (up to three on M5 Pro, one elsewhere). compute_channels: 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 { @@ -1557,6 +1561,7 @@ impl Backend { direct_slot: core::sync::atomic::AtomicU32::new(0), pairs: super::pairs::per_owner(), compute_channels: super::pairs::compute_channels_per_owner(), + spare_batch <- kernel::new_mutex!(None, "g17::Backend::spare_batch"), }), GFP_KERNEL, )?, @@ -1564,6 +1569,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 { @@ -2266,6 +2282,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 @@ -2402,6 +2438,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, @@ -3699,7 +3765,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 { @@ -4486,6 +4552,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 eb271e87a3289..51db503255fc1 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -320,7 +320,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 d06e91c804f98..a4f1e442c0fc4 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -594,7 +594,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 {