Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions drivers/gpu/drm/asahi/g17/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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`
Expand Down
46 changes: 32 additions & 14 deletions drivers/gpu/drm/asahi/g17/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,15 +122,24 @@ pub(crate) struct Queue<B: Backend> {
/// a submit on fragmentation.
finished: KVVec<Fences>,
failures: [FailureRecord<Fences>; 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<mmu::VmJobGuard>,
);
/// 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<mmu::VmJobGuard>,
}

impl<B: Backend> Queue<B> {
pub(crate) fn new(
Expand Down Expand Up @@ -174,6 +183,7 @@ impl<B: Backend> Queue<B> {
publishers: [Outstanding::new(failures), Outstanding::new(failures)],
finished: KVVec::new(),
failures: [FailureRecord::new(), FailureRecord::new()],
scratch: Scratch::default(),
_slot: slot,
})
}
Expand Down Expand Up @@ -417,14 +427,16 @@ impl<B: Backend> Queue<B> {
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<KBox<file::Object>>>,
) -> Result<ValidatedBatch> {
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| {
Expand All @@ -444,7 +456,7 @@ impl<B: Backend> Queue<B> {
// 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
Expand Down Expand Up @@ -484,11 +496,11 @@ impl<B: Backend> Queue<B> {
}
}
.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)?;
Expand All @@ -497,7 +509,7 @@ impl<B: Backend> Queue<B> {
.push_within_capacity(self.context.vm().retain_job()?)
.map_err(|_| ENOMEM)?;
}
Ok((pending, guards))
Ok(())
}
}

Expand Down Expand Up @@ -555,14 +567,16 @@ impl<B: Backend> crate::queue::Queue for Queue<B> {
return Err(error);
}
};
let mut scratch = core::mem::take(&mut self.scratch);
let result = (|| {
if !self.backend.supports_submission() {
return Err(ENOTSUPP);
}
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 { .. }));
Expand All @@ -588,7 +602,7 @@ impl<B: Backend> crate::queue::Queue for Queue<B> {
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();
Expand All @@ -608,7 +622,7 @@ impl<B: Backend> crate::queue::Queue for Queue<B> {
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,
Expand All @@ -622,6 +636,10 @@ impl<B: Backend> crate::queue::Queue for Queue<B> {
}
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 {
Expand Down
90 changes: 89 additions & 1 deletion drivers/gpu/drm/asahi/g17/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<DeferredBatch>>,
}

impl Backend {
Expand Down Expand Up @@ -1557,13 +1561,25 @@ 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,
)?,
slot,
))
}

/// A publication batch: the one the last publication left, else a new one.
pub(super) fn publication_batch(&self) -> Result<PublicationBatch<'_>> {
// 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 {
Expand Down Expand Up @@ -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<Self> {
let render_slots = if detached != 0 {
crate::hw::t8140::queues::RENDER_SLOTS
Expand Down Expand Up @@ -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<Option<DeferredBatch>>,
}
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<super::Shared>,
init: &'a super::initdata::InitData,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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::<DeferredBatch>), 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());
Expand Down
2 changes: 1 addition & 1 deletion drivers/gpu/drm/asahi/g17/runtime/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion drivers/gpu/drm/asahi/g17/runtime/render/submit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading