Skip to content
Open
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
22 changes: 22 additions & 0 deletions drivers/gpu/drm/asahi/g17/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ const _: () = assert!(super::telemetry::STATISTICS_RING_RECORDS == STATISTICS_SL
static CONTROL_PUBLISHED: AtomicU64 = AtomicU64::new(0);
/// The largest count of published records the firmware is known to have consumed.
static CONTROL_CONSUMED: AtomicU64 = AtomicU64::new(0);
/// The latest scheduler release, as the count of records published up to it.
static RELEASE_PUBLISHED: AtomicU64 = AtomicU64::new(0);
/// The latest scheduler release the firmware is known to have consumed, counted the same way.
static RELEASE_CONSUMED: AtomicU64 = AtomicU64::new(0);

/// Firmware progress fences for host identities and storage that the firmware may still
/// name after their owner let go of them.
Expand All @@ -49,6 +53,20 @@ pub(crate) fn control_witnessed() -> u64 {
CONTROL_CONSUMED.load(Ordering::Acquire)
}

/// The latest scheduler release the firmware is known to have consumed, as a record count
/// like [`control_published`]. The release carries what the older firmware's DestroyContext
/// does (a context page and its bytes 0, 1, 4 and 0x23, here 0x26), and that command also
/// flushes the firmware data cache (`flush_fw_cache` in `gpu.rs`). Once this exceeds the
/// fence of returned firmware-cached storage, a flush ran after the firmware last named it.
pub(crate) fn release_witnessed() -> u64 {
RELEASE_CONSUMED.load(Ordering::Acquire)
}

/// The record just published is a scheduler release. Call under the device mutex.
pub(crate) fn published_release() {
RELEASE_PUBLISHED.store(CONTROL_PUBLISHED.load(Ordering::Acquire), Ordering::Release);
}

/// Records how far the firmware consumed the control ring. Call under the device mutex,
/// which also serializes publication, with cursors read after any publication by the caller.
/// A restarted firmware has nothing pending, so everything published so far counts.
Expand All @@ -59,6 +77,10 @@ pub(crate) fn observe_control(consumer: u32, producer: u32) {
let pending = u64::from(producer.wrapping_sub(consumer) & (DEVICE_CONTROL_SLOTS - 1));
let consumed = CONTROL_PUBLISHED.load(Ordering::Acquire).saturating_sub(pending);
CONTROL_CONSUMED.fetch_max(consumed, Ordering::AcqRel);
let release = RELEASE_PUBLISHED.load(Ordering::Acquire);
if release <= consumed {
RELEASE_CONSUMED.fetch_max(release, Ordering::AcqRel);
}
}

/// Firmware rings whose contents do not affect host scheduling.
Expand Down
6 changes: 4 additions & 2 deletions drivers/gpu/drm/asahi/g17/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -850,18 +850,20 @@ impl WorkStateLease {
/// The render channel of `pair` for a publication. When both channels are bound to other
/// pairs, the least recently used one whose every publication `retired(qids, ordinal)`
/// moves to `pair`; otherwise [`RENDER_CHANNEL_PENDING`]: the caller waits for retirement
/// instead of failing the client.
/// instead of failing the client. `required`: the channel the pair's queue records already
/// carry, the only one it may take.
pub(crate) fn render_channel(
&self,
pair: u8,
required: Option<u32>,
retired: impl Fn([u8; 2], u64) -> bool,
) -> Result<u32> {
let (index, previous) = self
.context
.work
.lock()
.render
.bind(pair, retired)
.bind(pair, required, retired)
.ok_or(RENDER_CHANNEL_PENDING)?;
if let Some(previous) = previous {
static REBINDS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
Expand Down
39 changes: 34 additions & 5 deletions drivers/gpu/drm/asahi/g17/context/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,11 @@ pub(super) struct RenderSlots {
used: [u64; 2],
epoch: u64,
}
/// Whether channel `index` may serve a pair whose queue records carry `required`.
fn allows(required: Option<u32>, index: usize) -> bool {
required.is_none_or(|slot| slot as usize == index)
}

impl RenderSlots {
pub(super) const fn new() -> Self {
Self {
Expand All @@ -231,26 +236,29 @@ impl RenderSlots {
epoch: 0,
}
}
fn get(&mut self, pair: u8) -> Option<u32> {
fn get(&mut self, pair: u8, required: Option<u32>) -> Option<u32> {
if let Some(index) = self.pairs.iter().position(|value| *value == Some(pair)) {
return Some(index as u32);
}
let index = self.pairs.iter().position(Option::is_none)?;
let index = (0..2).find(|&index| allows(required, index) && self.pairs[index].is_none())?;
self.pairs[index] = Some(pair);
Some(index as u32)
}
/// The channel of `pair`, rebinding the least recently used channel whose publications
/// have all retired (`retired(qids, ordinal)`) when both are bound to other pairs. `None`:
/// no channel can move yet.
/// have all retired (`retired(qids, ordinal)`) when both are bound to other pairs. With
/// `required`, the channel the pair's queue records already carry, only that channel may
/// bind to it. `None`: no channel can move yet.
pub(super) fn bind(
&mut self,
pair: u8,
required: Option<u32>,
retired: impl Fn([u8; 2], u64) -> bool,
) -> Option<(u32, Option<u8>)> {
if let Some(index) = self.get(pair) {
if let Some(index) = self.get(pair, required) {
return Some((index, None));
}
let index = (0..2)
.filter(|&index| allows(required, index))
.filter(|index| self.last[*index].is_none_or(|(qids, ordinal)| retired(qids, ordinal)))
.min_by_key(|index| self.used[*index])?;
let previous = self.pairs[index];
Expand Down Expand Up @@ -425,6 +433,27 @@ mod tests {
}
}

#[test]
fn a_pair_takes_only_the_channel_its_records_carry() {
let retired = |_: [u8; 2], _: u64| true;
let mut slots = RenderSlots::new();
// A pair whose records carry channel 1 takes it although channel 0 is free.
assert_eq!(slots.bind(5, Some(1), retired), Some((1, None)));
assert_eq!(slots.bind(6, None, retired), Some((0, None)));
assert!(slots.published(5, [10, 11], 1));
assert!(slots.published(6, [12, 13], 2));
// A third pair takes the least recently used retired channel.
assert_eq!(slots.bind(7, None, retired), Some((1, Some(5))));
assert!(slots.published(7, [14, 15], 3));
// Pair 5's records carry channel 1: while pair 7's publications run it waits, although
// channel 0 has retired, and it takes channel 1 once they retire.
let running = |qids: [u8; 2], _: u64| qids != [14, 15];
assert_eq!(slots.bind(5, Some(1), running), None);
assert_eq!(slots.bind(5, Some(1), retired), Some((1, Some(7))));
// Unconstrained, the same move takes the least recently used retired channel.
assert_eq!(slots.bind(7, None, running), Some((0, Some(6))));
}

#[test]
fn releases_return_nodes_to_their_engine() {
let states = WorkStates::new();
Expand Down
23 changes: 21 additions & 2 deletions drivers/gpu/drm/asahi/g17/fw/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,8 +267,10 @@ pub(crate) struct QueueRecordArgs {
/// Description of one hardware queue, named by its work-ring slots.
///
/// The host writes it whole at queue creation and changes the owner fields of
/// an idle queue with [`QueueRecord::set_compute_owner`] or, for render
/// queues, field by field (`render/memory.rs`).
/// an idle compute queue with [`QueueRecord::set_compute_owner`]. Render
/// queue records are never retargeted: another owner gets new records, and
/// G17P writes the work slot (`unk_38`) only before the records' first kick
/// (`render/memory.rs`).
#[repr(C, packed)]
#[derive(Copy, Clone, Debug)]
pub(crate) struct QueueRecord {
Expand Down Expand Up @@ -327,6 +329,23 @@ impl QueueRecord {
}
}

/// Whether the record names this owner with this profile.
pub(crate) fn names_owner(
&self,
job_list_va: u64,
scheduler_va: u64,
owner_pid: u32,
policy: Policy,
) -> bool {
let (job_list, scheduler, pid, priority, current) =
(self.job_list_va, self.scheduler_va, self.owner_pid, self.priority, self.policy);
job_list == job_list_va
&& scheduler == scheduler_va
&& pid == owner_pid
&& priority == [u32::from(policy.priority()); 2]
&& current == u32::from(policy.policy())
}

/// Hands an idle compute queue to a new owner.
///
/// Replaces the job head, process identity and scheduler page, and clears `unk_38`.
Expand Down
23 changes: 20 additions & 3 deletions drivers/gpu/drm/asahi/g17/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -631,6 +631,15 @@ struct Retained {
/// Firmware progress after which the previous owner's references are gone
/// (see [`super::channel::control_fence`]).
fence: u64,
/// Cached queue records: reused only once a scheduler release published after `fence`
/// is consumed (see [`super::channel::release_witnessed`]).
flush: bool,
}

impl Retained {
fn ready(&self, witnessed: u64, released: u64) -> bool {
if self.flush { released > self.fence } else { self.fence <= witnessed }
}
}

struct PoolInner {
Expand Down Expand Up @@ -806,6 +815,7 @@ impl Pool {
let family_index = family as usize;
let begin = family_index * POOL_SLOTS;
let witnessed = super::channel::control_witnessed();
let released = super::channel::release_witnessed();
self.reap_deferred(witnessed);
// On the A18 Pro a cached work state carries a ReturnMark, allocated before an entry is
// taken so that a failure loses no returned object, and is never reused before its fence.
Expand All @@ -830,7 +840,7 @@ impl Pool {
}) else {
continue;
};
let ready = entry.fence <= witnessed;
let ready = entry.ready(witnessed, released);
if oldest.is_none_or(|(_, order, best_ready)| {
(ready && !best_ready) || (ready == best_ready && entry.order < order)
}) {
Expand Down Expand Up @@ -940,6 +950,10 @@ impl Pool {
let begin = family * POOL_SLOTS;
inner.returns += 1;
let order = inner.returns;
// The firmware writes cached queue records, and meeting their fence does not show that
// it no longer holds their lines. A release published after the fence does: it flushes
// the firmware data cache.
let flush = lease.family == Family::QueueState && lease.prefix != 0;
let fence = match lease.family {
// On the A18 Pro a work state's owner records how far its address reached the
// firmware: one never named needs no fence, and one whose owner's release was
Expand Down Expand Up @@ -967,6 +981,7 @@ impl Pool {
poisoned: lease.poisoned,
order,
fence,
flush,
});
return;
}
Expand Down Expand Up @@ -1137,18 +1152,20 @@ impl Pool {
pub(crate) fn write_capacity(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result {
let inner = self.inner.lock();
let witnessed = super::channel::control_witnessed();
let released = super::channel::release_witnessed();
let waiting = |entry: &&Retained| !entry.ready(witnessed, released);
for family in 0..POOL_FAMILIES {
let entries = &inner.returned[family * POOL_SLOTS..(family + 1) * POOL_SLOTS];
writeln!(f, concat!("cached_objects_{} used={} total={} returned={} poisoned={} ",
"waiting={} overruns={} uncached={}"),
family, inner.reserved[family], POOL_SLOTS, entries.iter().flatten().count(),
entries.iter().flatten().filter(|entry| entry.poisoned).count(),
entries.iter().flatten().filter(|entry| entry.fence > witnessed).count(),
entries.iter().flatten().filter(waiting).count(),
inner.fence_overruns[family], inner.uncached[family])?;
}
writeln!(f, "cached_object_bytes used={} total={}", inner.bytes, POOL_BYTES)?;
writeln!(f, "cached_objects_fenced waiting={} overruns={}",
inner.returned.iter().flatten().filter(|entry| entry.fence > witnessed).count(),
inner.returned.iter().flatten().filter(waiting).count(),
inner.fence_overruns.iter().sum::<u64>())?;
writeln!(f, "workstate_returns unseen={} released={} strict={}",
inner.work_returns[RETURN_UNSEEN], inner.work_returns[RETURN_RELEASED],
Expand Down
36 changes: 17 additions & 19 deletions drivers/gpu/drm/asahi/g17/queue/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -881,8 +881,10 @@ impl Pair {
let parents = self.kicks.each_ref().map(kick::Queue::parent);
let work = packet.completion.work_state()?;
// A channel moves to this pair only after every publication made through it is
// visible on both of its rings (the stamps cover ordinal + 1).
let work_slot = work.render_channel(self.slot, |old, published| {
// visible on both of its rings (the stamps cover ordinal + 1). Once the G17P queue
// records carry a work slot, only that channel serves this graph.
let required = self.memory.graph.work_slot;
let work_slot = work.render_channel(self.slot, required, |old, published| {
host.stamps(old).is_ok_and(|stamps| {
stamps.into_iter().all(|stamp| retirement::stamp_covers(stamp, published))
})
Expand Down Expand Up @@ -3429,14 +3431,10 @@ impl Pair {
return Err(EBUSY);
}
alloc.uat.vm_context_mask(context.vm())?;
// On M5 only the same logical context (a pool rebind) keeps the graph:
// any other context gets its own graph and queue records, and a live
// queue record is never retargeted.
let keep_graph = if self.memory.graph.is_m5() {
Arc::ptr_eq(self.context(), &context)
} else {
Arc::ptr_eq(self.context().status(), context.status())
};
// Only the same logical context (a pool rebind) keeps the graph: any
// other context, even of the same VM, gets its own graph and queue
// records, so a queue record is never retargeted in place.
let keep_graph = Arc::ptr_eq(self.context(), &context);
let (memory, aliases, kicks) = if keep_graph {
if metrics.is_some() || buffer_id.is_some() || pm_generation.is_some() {
return Err(EINVAL);
Expand Down Expand Up @@ -3515,11 +3513,11 @@ impl Pair {
let foreign = binding.memory.is_some();
let same_context = Arc::ptr_eq(self.context(), &binding.context);
if let Some(memory) = binding.memory.as_mut() {
// A VM holds one graph's pool mappings per slot. On M5 a new
// context of the same VM gets its own graph: move the drained
// outgoing graph's mappings out first, and back if the install fails.
// A VM holds one graph's pool mappings per slot. A new context of
// the same VM gets its own graph: move the drained outgoing graph's
// mappings out first, and back if the install fails.
let same_vm = Arc::ptr_eq(self.context().status(), binding.context.status());
let moved = if self.memory.graph.is_m5() && same_vm {
let moved = if same_vm {
self.memory.take_pool_mappings()
} else {
None
Expand Down Expand Up @@ -3551,11 +3549,11 @@ impl Pair {
}
}
}
} else {
// The same logical context keeps its M5 queue records: their host
// words already name it, and a rewrite would store firmware-owned
// words back while the previous kick may still execute.
self.memory.set_owner(self.qids(), &binding.context, !same_context)?;
} else if !self.memory.names_owner(self.qids(), &binding.context)? {
// The same logical context keeps its queue records, which already
// name it. They are never rewritten: a store could revert, or be
// missed by, a firmware-cached line of a queue that ran before.
return Err(EINVAL);
}
let wait_for_pool_release = self.memory.graph.is_m5()
&& same_context
Expand Down
Loading