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
178 changes: 178 additions & 0 deletions drivers/gpu/drm/asahi/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ pub(crate) const DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS: u32 =
const DEBUG_CLASS: DebugFlags = DebugFlags::File;

pub(crate) const MAX_COMMANDS_PER_SUBMISSION: u32 = 64;
/// Most input plus output syncs of one SUBMIT, on the GPUs that bound them
/// ([`gpu::Gpu::max_syncs`]).
pub(crate) const MAX_SYNCS_PER_SUBMISSION: usize = 4096;

/// A client instance of an `mmu::Vm` address space.
struct Vm {
Expand Down Expand Up @@ -322,6 +325,7 @@ impl SyncItem {
}
base += chunk as u32;
}
let anchor = Self::coalesce_outputs(&mut vec, in_count as usize, anchor)?;
if let Some(anchor) = anchor {
let bundle = crate::g17::sync_output::SignalBundle::new(
&vec[in_count as usize..],
Expand All @@ -338,6 +342,174 @@ impl SyncItem {

Ok(vec)
}

/// Merges the timeline outputs of `syncs` (outputs from `first` on) that name the same
/// syncobj ([`coalesce_timeline_outputs`]), before any chain node is allocated for them.
/// Returns the index of the cumulative `anchor` after the merge. The anchor never merges,
/// so another output naming its syncobj is still refused.
fn coalesce_outputs(
syncs: &mut KVVec<SyncItem>,
first: usize,
anchor: Option<usize>,
) -> Result<Option<usize>> {
let outputs = |&(index, _): &(usize, &SyncItem)| index >= first && Some(index) != anchor;
let timeline = |(_, sync): &(usize, &SyncItem)| sync.timeline;
let named = syncs.iter().enumerate().filter(outputs);
if named.filter(timeline).count() < 2 {
return Ok(anchor);
}
let mut named = KVVec::with_capacity(syncs.len() - first, GFP_KERNEL_ACCOUNT)?;
for (index, sync) in syncs.iter().enumerate().filter(outputs) {
let point = sync.timeline.then_some(sync.timeline_value);
named.push(
(sync.syncobj.as_raw() as usize, index, point),
GFP_KERNEL_ACCOUNT,
)?;
}
let merged = coalesce_timeline_outputs(&mut named)?;
if merged.is_empty() {
return Ok(anchor);
}
for &(_, index, point) in named.iter() {
if let Some(point) = point {
syncs[index].timeline_value = point;
}
}
let anchor = anchor
.map(|anchor| anchor - merged.iter().take_while(|&&index| index < anchor).count());
let mut index = 0;
let mut next = merged.iter().peekable();
syncs.retain(|_| {
let gone = next.next_if_eq(&&index).is_some();
index += 1;
!gone
});
Ok(anchor)
}
}

/// Timeline outputs of one submission that name the same syncobj all receive the
/// submission's fence. Installing each walks the syncobj's unsignalled fence chain, which
/// every installation lengthens, so N of them would walk it N times. They merge into the
/// last of them, at the highest of their points: a wait for any of those points still
/// resolves to the submission's fence. A binary output of the same syncobj between two of
/// them replaces the chain, points and all, so nothing merges across it.
///
/// `named` holds each output's syncobj, index and point, `None` for a binary output. Leaves
/// each kept output's entry with its merged point and returns the merged-away outputs'
/// indices, in order.
fn coalesce_timeline_outputs(named: &mut [(usize, usize, Option<u64>)]) -> Result<KVec<usize>> {
named.sort_unstable_by_key(|&(syncobj, index, _)| (syncobj, index));
let mut merged = KVec::new();
for group in named.chunk_by_mut(|a, b| a.0 == b.0 && a.2.is_some() && b.2.is_some()) {
let Some(((_, _, point), earlier)) = group.split_last_mut() else {
continue;
};
for &(_, index, earlier_point) in earlier.iter() {
*point = (*point).max(earlier_point);
merged.push(index, GFP_KERNEL)?;
}
}
merged.sort_unstable();
Ok(merged)
}

#[kernel::macros::kunit_tests(asahi_submit_outputs)]
mod output_tests {
use super::*;

fn merge_any(outputs: &[(usize, Option<u64>)]) -> (KVec<usize>, KVec<(usize, Option<u64>)>) {
let mut named = KVec::new();
for (index, &(syncobj, point)) in outputs.iter().enumerate() {
named.push((syncobj, index, point), GFP_KERNEL).unwrap();
}
let merged = coalesce_timeline_outputs(&mut named).unwrap();
let mut kept = KVec::new();
for &(_, index, point) in named.iter() {
if !merged.contains(&index) {
kept.push((index, point), GFP_KERNEL).unwrap();
}
}
kept.sort_unstable();
(merged, kept)
}

/// Timeline outputs only.
fn merge(outputs: &[(usize, u64)]) -> (KVec<usize>, KVec<(usize, u64)>) {
let mut timelines = KVec::new();
for &(syncobj, point) in outputs {
timelines.push((syncobj, Some(point)), GFP_KERNEL).unwrap();
}
let (merged, any) = merge_any(&timelines);
let mut kept = KVec::new();
for &(index, point) in any.iter() {
kept.push((index, point.unwrap()), GFP_KERNEL).unwrap();
}
(merged, kept)
}

#[test]
fn distinct_syncobjs_stay_as_they_are() {
let (merged, kept) = merge(&[(1, 5), (2, 5), (3, 0)]);
assert!(merged.is_empty());
assert_eq!(&kept[..], &[(0, 5), (1, 5), (2, 0)]);
}

#[test]
fn rising_points_keep_the_last_and_highest() {
// Two batches that each signal one timeline, merged into one submission.
let (merged, kept) = merge(&[(1, 5), (2, 9), (1, 6)]);
assert_eq!(&merged[..], &[0]);
assert_eq!(&kept[..], &[(1, 9), (2, 6)]);
}

#[test]
fn falling_points_keep_the_highest_at_the_last() {
let (merged, kept) = merge(&[(4, 9), (4, 3), (4, 7)]);
assert_eq!(&merged[..], &[0, 1]);
assert_eq!(&kept[..], &[(2, 9)]);
}

#[test]
fn a_binary_output_of_the_same_syncobj_ends_a_merge() {
// The binary output replaces the chain: the syncobj ends at 7, not at 9.
let outputs = [(4, Some(9)), (4, None), (4, Some(7))];
let (merged, kept) = merge_any(&outputs);
assert!(merged.is_empty());
assert_eq!(&kept[..], &[(0, Some(9)), (1, None), (2, Some(7))]);
// Either side still merges, around repeated binary outputs too, and another syncobj's
// binary output ends nothing.
let outputs = [
(4, Some(9)),
(4, Some(8)),
(4, None),
(4, None),
(4, Some(3)),
(5, None),
(4, Some(5)),
];
let (merged, kept) = merge_any(&outputs);
assert_eq!(&merged[..], &[0, 4]);
assert_eq!(
&kept[..],
&[(1, Some(9)), (2, None), (3, None), (5, None), (6, Some(5))]
);
}

#[test]
fn repeats_of_one_point_leave_one_output() {
let mut outputs = KVec::new();
for _ in 0..MAX_SYNCS_PER_SUBMISSION {
outputs.push((7, 3), GFP_KERNEL).unwrap();
}
let (merged, kept) = merge(&outputs);
assert_eq!(merged.len(), MAX_SYNCS_PER_SUBMISSION - 1);
assert!(merged
.iter()
.enumerate()
.all(|(order, &index)| order == index));
assert_eq!(&kept[..], &[(MAX_SYNCS_PER_SUBMISSION - 1, 3)]);
}
}

#[derive(Clone)]
Expand Down Expand Up @@ -1892,6 +2064,12 @@ impl File {
if data.cmdbuf_size as usize > gpu.max_cmdbuf_size() {
return Err(E2BIG);
}
// Before anything is allocated for the syncs: each one costs a parsed record, and
// a timeline output a chain node its syncobj keeps.
if data.in_sync_count as usize + data.out_sync_count as usize > gpu.max_syncs() {
cls_pr_debug!(Errors, "submit: Too many syncs\n");
return Err(EINVAL);
}
if let Some(manager) = gpu.manager() {
manager.update_globals();
}
Expand Down
2 changes: 1 addition & 1 deletion drivers/gpu/drm/asahi/g15/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use crate::{file, mmu, timestamp, util::AnyBitPattern, util::Reader};
/// Largest command buffer.
pub(crate) const MAX_CMDBUF: usize = 4 << 20;
/// Most input plus output syncs of one SUBMIT.
pub(crate) const MAX_SYNCS: usize = 4096;
pub(crate) const MAX_SYNCS: usize = crate::file::MAX_SYNCS_PER_SUBMISSION;
/// Hardware commands per SUBMIT.
const MAX_COMMANDS: u32 = crate::file::MAX_COMMANDS_PER_SUBMISSION;

Expand Down
2 changes: 1 addition & 1 deletion drivers/gpu/drm/asahi/g16/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::{file, mmu, util::AnyBitPattern, util::Reader};
/// Largest command buffer.
pub(crate) const MAX_CMDBUF: usize = 4 << 20;
/// Most input plus output syncs of one SUBMIT.
pub(crate) const MAX_SYNCS: usize = 4096;
pub(crate) const MAX_SYNCS: usize = crate::file::MAX_SYNCS_PER_SUBMISSION;
/// Hardware commands per SUBMIT.
pub(crate) const MAX_COMMANDS: u32 = crate::file::MAX_COMMANDS_PER_SUBMISSION;

Expand Down
54 changes: 51 additions & 3 deletions drivers/gpu/drm/asahi/g17/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ impl QosIds {
ids: self.clone(),
id: id as u8,
seen: AtomicBool::new(false),
returned: AtomicBool::new(false),
suppress_notify: AtomicBool::new(false),
},
GFP_KERNEL,
Expand All @@ -105,6 +106,8 @@ pub(super) struct QosLease {
id: u8,
/// The firmware may have seen this ID.
seen: AtomicBool,
/// The ID went back to the device's pool.
returned: AtomicBool,
/// Unpublished rollback: caller wakes via [`super::availability::Availability::notify_own`].
suppress_notify: AtomicBool,
}
Expand All @@ -119,9 +122,12 @@ impl QosLease {
.as_ref()
.map_or(observed, |waiters| waiters.notify_own(observed))
}
}
impl Drop for QosLease {
fn drop(&mut self) {

/// Gives the ID back, once: early ([`Context::release_unpublished`]) or on drop.
fn give_back(&self) {
if self.returned.swap(true, Ordering::AcqRel) {
return;
}
let fence = if self.seen.load(Ordering::Acquire) {
super::channel::control_fence()
} else {
Expand All @@ -142,6 +148,11 @@ impl Drop for QosLease {
}
}
}
impl Drop for QosLease {
fn drop(&mut self) {
self.give_back();
}
}

struct WorkStorage {
object: PooledObject,
Expand Down Expand Up @@ -607,6 +618,19 @@ impl Context {
pub(crate) fn execution_share_id(&self) -> u64 {
self.share.as_ref().map_or(0, |share| share.id())
}
/// Its queue closed before the firmware saw this context, and nothing of the queue can
/// publish any more. Returns the finite identities no firmware record can name: the
/// execution identity, the QoS ID and an unused render identity. A published context
/// returns its own once its scheduler release is consumed. Either way they do not wait
/// for the context's last reference, which a cancelled job keeps until its inputs signal.
pub(crate) fn release_unpublished(&self) {
if self.is_published() {
return;
}
self.release_execution();
self.qos.give_back();
self.release_render_id();
}
/// `other` runs in this context's shared execution context.
pub(crate) fn shares_execution(&self, other: &Context) -> bool {
self.share.is_some() && core::ptr::eq(&*self.execution, &*other.execution)
Expand Down Expand Up @@ -1249,6 +1273,30 @@ mod capacity_tests {
}
}

#[test]
fn an_id_given_back_early_is_given_back_once() {
let ids = QosIds::new().unwrap();
let (early, other) = (ids.acquire().unwrap(), ids.acquire().unwrap());
assert_eq!(ids.used(), 2);
early.give_back();
early.give_back();
assert_eq!(ids.used(), 1);
let clock = ids.state.lock().clock;
// Every free ID is taken while the early holder lives, its own again among them.
let mut rest = KVec::with_capacity(QOS_IDS - 3, GFP_KERNEL).unwrap();
for _ in 0..QOS_IDS - 3 {
rest.push(ids.acquire().unwrap(), GFP_KERNEL).unwrap();
}
assert!(matches!(ids.acquire(), Err(ENOSPC)));
assert!(rest.iter().any(|lease| lease.id == early.id));
// Dropping the early holder gives nothing back: its ID is the new owner's.
drop(early);
assert_eq!(ids.used(), QOS_IDS as u32 - 2);
assert_eq!(ids.state.lock().clock, clock);
drop((other, rest));
assert_eq!(ids.used(), 0);
}

#[test]
fn a_released_qos_row_still_in_use_is_cleared_later() {
let ids = QosIds::new().unwrap();
Expand Down
4 changes: 4 additions & 0 deletions drivers/gpu/drm/asahi/g17/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3103,6 +3103,10 @@ impl gpu::Gpu for Gpu {
command::MAX_STREAM
}

fn max_syncs(&self) -> usize {
crate::file::MAX_SYNCS_PER_SUBMISSION
}

fn syncobj_wait_hint(&self) -> Option<(u32, u32)> {
self.shared.feed.wait_hint()
}
Expand Down
9 changes: 8 additions & 1 deletion drivers/gpu/drm/asahi/g17/runtime/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,10 +142,11 @@ impl Backend {
// may have closed this queue on its client's behalf already (`Firmware::close_failed_owners`),
// and its teardown entry may be released and reclaimed since. Closing it again would
// release its scheduler twice.
let mut retained = false;
if !self.context.is_closed() {
// Retain a published scheduler before a never-kicked physical graph is
// removed. The teardown entry owns its root until control consumption.
firmware
retained = firmware
.queues
.teardown
.close(&self.context, super::now_ns())?;
Expand All @@ -160,6 +161,12 @@ impl Backend {
firmware.queues.admission.release_owner(self.owner);
}
drop(state);
// Both schedulers are gone, so the firmware cannot see a context it has not seen yet.
// Its identities return with the queue's admission, not after the jobs that the
// closing entities cancelled: those wait for their inputs before they are freed.
if !retained {
self.context.release_unpublished();
}
// Its idle channel, or its slot and never-published QID, is free.
self.shared.channels.notify();
self.shared.queue_events();
Expand Down
10 changes: 6 additions & 4 deletions drivers/gpu/drm/asahi/g17/teardown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,20 +173,22 @@ impl Pending {
}

/// No allocation is needed at close. A scheduler page never exposed to firmware requires
/// no release, unless the Registry already retained one of its displaced graphs.
pub(crate) fn close(&mut self, context: &Arc<Context>, now: u64) -> Result {
/// no release, unless the Registry already retained one of its displaced graphs. Returns
/// whether the context waits here for a release.
pub(crate) fn close(&mut self, context: &Arc<Context>, now: u64) -> Result<bool> {
if let Some(index) = self.find(context) {
let entry = &mut self.entries[index];
if entry.phase == Phase::Deferred {
entry.phase = Phase::Draining;
entry.armed = now;
}
return Ok(());
return Ok(true);
}
if context.is_published() {
self.insert(context, Phase::Draining, now)?;
return Ok(true);
}
Ok(())
Ok(false)
}

/// Publish in insertion order. Mandatory control replies and a full control ring stop this
Expand Down
5 changes: 5 additions & 0 deletions drivers/gpu/drm/asahi/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,11 @@ pub(crate) trait Gpu: Send + Sync {
usize::MAX
}

/// Admission bound on a submission's input plus output syncs, checked before parsing them.
fn max_syncs(&self) -> usize {
usize::MAX
}

/// The firmware statistics snapshot of this GPU, if its firmware reports any.
fn stats_snapshot(&self) -> Option<Arc<stats::StatsSnapshot>>;

Expand Down
Loading
Loading