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
84 changes: 71 additions & 13 deletions drivers/gpu/drm/asahi/g17/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,9 @@ pub(crate) struct Context {
/// The kill of this context, through a compute queue or on its render pairs' behalf. Shared
/// with the [`FirmwarePages`] a queue keeps after its owner exited.
kill: Arc<Kill>,
/// A stampless-retired render group of this context was later released through pair-wide
/// drain instead of observing post-maintenance completion stamps.
stampless_drained: AtomicBool,
/// The host's recovery generation when it first saw the kill of this context done (its
/// scheduler page's killed state), `u64::MAX` before ([`Self::restarted_since_kill`]).
kill_seen: AtomicU64,
Expand Down Expand Up @@ -370,18 +373,23 @@ impl Context {
let scheduler_generation = super::ids::OBJECTS.object()?;
let scheduler = Arc::new(scheduler, GFP_KERNEL)?;
// Both firmware and host write work nodes (reused every 63 submissions
// and zeroed on pool reuse). M5 keeps the whole work-state object
// uncached. G17P maps the node page firmware-cached: the host rewrites
// a node only after `WorkStorage::drained` has read the firmware's
// final `completed` count from memory, and zeroes a returned object
// only once its pool fence is met, so it never rewrites a node the
// firmware is still updating. The counter page, which the host writes
// on every kick, stays uncached.
// and zeroed on pool reuse). Map the node page firmware-cached on all
// G17 (G17P and M5): within a context a node slot is rewritten only
// after every command holding its `WorkStateLease` has retired with
// post-maintenance completion stamps (including stampless render, where
// `Active` retains `WorkStateLease` until those stamps arrive; any
// unstamped drain pins the slot via `WorkStateLease::pin_until_stop` so
// later submissions in the same context never acquire it). Across
// contexts, `Pool::allocate` never overruns a pool fence for
// firmware-cached objects, and `retain_linked_work` keeps a killed,
// failed, stampless-drained, or still-linked context's work storage
// out of pool reuse until firmware stop. The counter page, which the
// host writes on every kick, stays uncached.
let mut object = pool.allocate(
alloc,
Family::WorkState,
2 * UAT_PGSZ,
if alloc.uat.is_m5() { 0 } else { UAT_PGSZ },
UAT_PGSZ,
mmu::PROT_FW_SHARED_RW,
CpuMap::WriteCombined,
)?;
Expand Down Expand Up @@ -427,6 +435,7 @@ impl Context {
scheduler_generation,
published: AtomicBool::new(false),
kill,
stampless_drained: AtomicBool::new(false),
kill_seen: AtomicU64::new(u64::MAX),
closed_generation: AtomicU64::new(u64::MAX),
closed_for_open_client: AtomicBool::new(false),
Expand Down Expand Up @@ -612,12 +621,23 @@ impl Context {
/// cursor snapshot that proved the release consumed, so the witness already covers it.
pub(crate) fn retain_linked_work(&self, pool: &Arc<Pool>) -> bool {
// An unreadable head counts as linked: retaining is the safe side.
// A killed context, stampless-drained render context, or failed VM may
// leave firmware-cached work nodes dirty without a normal stamped
// completion: keep the storage out of reuse until firmware stop even if
// the list head is empty.
let linked = self.work_head().map_or(true, |head| head != [0, self.work_head_address()]);
if linked {
self.work.lock().object.retain_until_stop(pool);
} else if let Some(mark) = &self.work_mark {
mark.released(super::channel::control_witnessed());
let dirty = self.kill_published()
|| self.stampless_drained()
|| self.status.get() != 0;
let mut work = self.work.lock();
if linked || (dirty && work.object.cached_prefix() != 0) {
work.object.retain_until_stop(pool);
} else if !dirty {
if let Some(mark) = &self.work_mark {
mark.released(super::channel::control_witnessed());
}
}
drop(work);
linked
}

Expand Down Expand Up @@ -685,6 +705,16 @@ impl Context {
self.kill.finished()
}

/// Record that a stampless-retired render group was released via pair-wide drain.
pub(crate) fn note_stampless_drain(&self) {
self.stampless_drained.store(true, Ordering::Release);
}

/// A stampless-retired render group of this context was released via pair-wide drain.
pub(crate) fn stampless_drained(&self) -> bool {
self.stampless_drained.load(Ordering::Acquire)
}

/// This context's queue closed at the host's recovery `generation`, under the device mutex:
/// by its client (`release_queue`), or on its behalf once a GPU recovery failed its VM as
/// guilty (`Firmware::close_failed_owners`). Only the first close counts. A close notes it
Expand Down Expand Up @@ -910,6 +940,9 @@ pub(crate) struct WorkStateLease {
word: AtomicU32,
/// Index of the engine whose admission took the node, valid once `word` is set.
engine: AtomicU8,
/// Retired through an unstamped drain: keep the slot out of same-context
/// reuse when this lease drops instead of returning it to `WorkStates`.
pinned: AtomicBool,
/// The ioctl's place in its context's submission order.
ordinal: u64,
}
Expand All @@ -925,6 +958,7 @@ impl WorkStateLease {
context,
word: AtomicU32::new(FREE),
engine: AtomicU8::new(0),
pinned: AtomicBool::new(false),
ordinal,
})
}
Expand All @@ -936,6 +970,7 @@ impl WorkStateLease {
context,
word: AtomicU32::new(FREE),
engine: AtomicU8::new(0),
pinned: AtomicBool::new(false),
ordinal,
})
}
Expand All @@ -958,6 +993,9 @@ impl WorkStateLease {
if !order.admits(self.ordinal) {
return Err(EBUSY);
}
if self.context.states.exhausted() {
return Err(EIO);
}
let engine = engine.index();
let candidate = self.context.states.allocate(engine).ok_or(EBUSY)?;
if let Err(error) = work.initialize(candidate) {
Expand Down Expand Up @@ -1060,12 +1098,25 @@ impl WorkStateLease {
.payload(pair, ordinal)
.ok_or(EINVAL)
}
/// Keeps this lease's work-state slot out of reuse within its context and
/// retains the context's work storage out of pool reuse until firmware stop.
/// Used on unstamped drain paths whose cached work node may still hold dirty
/// firmware cache lines.
pub(crate) fn pin_until_stop(&self) {
self.pinned.store(true, Ordering::Release);
self.context.note_stampless_drain();
}
}
impl Drop for WorkStateLease {
fn drop(&mut self) {
let word = self.word();
if word != FREE {
self.context.release_state(word, usize::from(self.engine.load(Ordering::Relaxed)));
let engine = usize::from(self.engine.load(Ordering::Relaxed));
if self.pinned.load(Ordering::Acquire) {
self.context.pin_state(word, engine);
} else {
self.context.release_state(word, engine);
}
} else {
let wake = self.context.order.lock().leave(self.ordinal);
self.context.notify_turn(wake);
Expand All @@ -1081,6 +1132,13 @@ impl Context {
self.state_returns.notify();
}
}
/// Retires a slot without returning its index to `allocate`: decrementing
/// `held[engine]` may still satisfy `may_take(1, 0)` for a waiting engine.
fn pin_state(&self, word: u32, engine: usize) {
if self.states.pin(word, engine) {
self.state_returns.notify();
}
}
/// A refused publisher waits on its engine's domain. Bumping both once the turn moved past a
/// refusal means one that sampled before its refused acquire() never sleeps through it.
fn pass_turn(&self) {
Expand Down
93 changes: 91 additions & 2 deletions drivers/gpu/drm/asahi/g17/context/identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ pub(super) const fn may_take(free: usize, held: u32) -> bool {
pub(super) struct WorkStates {
next: AtomicU32,
live: [AtomicU32; 64],
/// Slots retired without post-maintenance completion stamps (for example
/// stampless render groups released via pair-wide drain or recovery-dropped
/// groups). A pinned slot stays out of `allocate` for the rest of this
/// context's life so the host never rewrites a cached work node the firmware
/// may still hold dirty; `live[index]` returns to `FREE` so `older_live`
/// never stalls behind it.
pinned: AtomicU64,
/// Nodes taken by each engine's admissions and not yet released.
held: [AtomicU32; ENGINES],
/// Indices claimed by every context sharing this one's execution context
Expand All @@ -43,6 +50,7 @@ impl WorkStates {
// 0x17c8.. 0x17ea on the J813).
next: AtomicU32::new(0x40),
live: [const { AtomicU32::new(FREE) }; 64],
pinned: AtomicU64::new(0),
held: [const { AtomicU32::new(0) }; ENGINES],
claims: None,
}
Expand All @@ -51,21 +59,33 @@ impl WorkStates {
pub(super) fn shared(claims: Arc<AtomicU64>) -> Self {
Self { claims: Some(claims), ..Self::new() }
}
/// Every slot of this context is pinned out of reuse, so no future release
/// can ever free one.
pub(super) fn exhausted(&self) -> bool {
let mask = (1u64 << STATE_COUNT) - 1;
(self.pinned.load(Ordering::Acquire) & mask).count_ones() as usize >= STATE_COUNT
}
/// Takes a node for `engine`, or none when [`may_take`] refuses. Callers serialize
/// allocations of one context; releases may run concurrently.
pub(super) fn allocate(&self, engine: usize) -> Option<u32> {
let held = self.held.get(engine)?;
if !may_take(STATE_COUNT.saturating_sub(self.used()), held.load(Ordering::Acquire)) {
return None;
}
let pinned = self.pinned.load(Ordering::Acquire);
for _ in 0..64 {
let word = self.next.fetch_add(1, Ordering::Relaxed);
let index = (word & 63) as usize;
if index != STATE_COUNT
&& (pinned & (1u64 << index)) == 0
&& self.live[index]
.compare_exchange(FREE, word, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
{
if (self.pinned.load(Ordering::Acquire) & (1u64 << index)) != 0 {
self.live[index].store(FREE, Ordering::Release);
continue;
}
if let Some(claims) = &self.claims {
if claims.fetch_or(1 << index, Ordering::AcqRel) & (1 << index) != 0 {
self.live[index].store(FREE, Ordering::Release);
Expand Down Expand Up @@ -94,6 +114,31 @@ impl WorkStates {
}
released
}
/// Retires `word` while keeping its slot index out of reuse for the rest of
/// this context's life (cross-context pool reuse is separately prevented by
/// `Context::retain_linked_work`).
pub(super) fn pin(&self, word: u32, engine: usize) -> bool {
let index = (word & 63) as usize;
if index == STATE_COUNT || self.live[index].load(Ordering::Acquire) != word {
return false;
}
let mask = 1u64 << index;
// Set `pinned` before clearing `live[index]` so a concurrent `allocate`
// cannot observe `FREE` without also observing the pin bit.
self.pinned.fetch_or(mask, Ordering::AcqRel);
let pinned = self.live[index]
.compare_exchange(word, FREE, Ordering::AcqRel, Ordering::Acquire)
.is_ok();
if pinned {
if let Some(claims) = &self.claims {
claims.fetch_and(!mask, Ordering::AcqRel);
}
if let Some(held) = self.held.get(engine) {
held.fetch_sub(1, Ordering::AcqRel);
}
}
pinned
}
}

/// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the
Expand Down Expand Up @@ -316,11 +361,22 @@ impl WorkStates {
.min_by_key(|&live| live.wrapping_sub(word) as i32)
}

/// Slots in use, pinned ones included. The live words (or the shared claims) are read
/// before the pin mask: `pin` sets its bit before it clears the slot's live word and
/// claim, so a slot a concurrent `pin` has just freed is seen pinned here, never free.
pub(super) fn used(&self) -> usize {
if let Some(claims) = &self.claims {
return claims.load(Ordering::Acquire).count_ones() as usize;
let claimed = claims.load(Ordering::Acquire);
return (claimed | self.pinned.load(Ordering::Acquire)).count_ones() as usize;
}
self.live.iter().filter(|word| word.load(Ordering::Acquire) != FREE).count()
let live = self
.live
.iter()
.enumerate()
.filter(|&(i, word)| i != STATE_COUNT && word.load(Ordering::Acquire) != FREE)
.fold(0u64, |mask, (i, _)| mask | (1u64 << i));
let pinned = self.pinned.load(Ordering::Acquire) & !(1u64 << STATE_COUNT);
(live | pinned).count_ones() as usize
}
}
impl RenderSlots {
Expand Down Expand Up @@ -480,4 +536,37 @@ mod tests {
// An engine outside the table takes nothing.
assert!(states.allocate(ENGINES).is_none());
}

#[test]
fn pinned_slot_is_never_reused_and_never_stalls_older_live() {
let states = WorkStates::new();
let first = states.allocate(0).unwrap();
let pinned_index = first & 63;
let second = states.allocate(0).unwrap();
assert_eq!(states.older_live(second), Some(first));
assert!(states.pin(first, 0));
assert!(!states.pin(first, 0));
assert_eq!(states.older_live(second), None);
assert_eq!(states.used(), 2);
assert_eq!(states.held[0].load(Ordering::Acquire), 1);
assert!(states.release(second, 0));
assert_eq!(states.used(), 1);
assert_eq!(states.held[0].load(Ordering::Acquire), 0);
// Cycling well past STATE_COUNT never hands back the pinned slot.
for _ in 0..(STATE_COUNT * 3) {
let word = states.allocate(0).unwrap();
assert_ne!(word & 63, pinned_index);
assert!(states.release(word, 0));
}
assert!(!states.exhausted());
// Pinning the remaining slots exhausts the context cleanly.
for _ in 1..STATE_COUNT {
let word = states.allocate(0).unwrap();
assert!(states.pin(word, 0));
}
assert!(states.exhausted());
assert_eq!(states.used(), STATE_COUNT);
assert!(states.allocate(0).is_none());
assert!(states.allocate(1).is_none());
}
}
5 changes: 5 additions & 0 deletions drivers/gpu/drm/asahi/g17/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -759,6 +759,11 @@ impl PooledObject {
pub(crate) fn return_mark(&self) -> Option<kernel::sync::Arc<ReturnMark>> {
self.lease.as_ref().and_then(|lease| lease.mark.clone())
}

/// Length of the firmware-cached prefix of this object's mapping, or 0 when uncached.
pub(crate) fn cached_prefix(&self) -> usize {
self.lease.as_ref().map_or(0, |lease| lease.prefix)
}
}

impl Drop for PooledObject {
Expand Down
23 changes: 18 additions & 5 deletions drivers/gpu/drm/asahi/g17/queue/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,17 @@ impl DescriptorRing {
/// Both firmware and host write compute descriptors: the firmware updates
/// an accounting word near the end of each descriptor (`+0xfac` on M5),
/// and the host rewrites each slot every 32 kicks. M5 keeps them uncached
/// against the dirty-line writeback hazard of linux#3170, while retaining
/// against the dirty-line writeback hazard of linux#3170 (and because cached
/// M5 descriptors did not help light compute in linux#3389), while retaining
/// their VA and fence in the pool. G17P maps them firmware-cached, as it
/// does render descriptors: the host rewrites a slot only after the kick
/// that last used it retired (at most `DESCRIPTORS` kicks are in flight),
/// by when that kick's accounting store is in memory. The hardware reads
/// the same pages through an uncached canonical low alias; the kernel
/// mapping, in the upper half every execution context includes, is
/// firmware-only.
/// by when that kick's accounting store is in memory. A queue recycled after
/// a kill or quarantine retains a firmware-cached descriptor ring until
/// firmware stop (`Queue::retain_ring_until_stop`) instead of returning it
/// to the reuse pool. The hardware reads the same pages through an uncached
/// canonical low alias; the kernel mapping, in the upper half every execution
/// context includes, is firmware-only.
pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc<Pool>) -> Result<Self> {
let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE;
let object = objects.allocate(
Expand Down Expand Up @@ -2365,6 +2368,16 @@ impl Queue {
self.recycle_settled()?;
Ok(true)
}
/// Keeps this queue's descriptor ring mapped and out of pool reuse until
/// firmware stop, for queues recycled after a kill or quarantine where
/// aborted commands did not complete with post-maintenance stamps.
pub(crate) fn retain_ring_until_stop(&mut self, pool: &Arc<Pool>) {
if let Some(ring) = self.graph.ring.as_mut() {
if ring.object.cached_prefix() != 0 {
ring.object.retain_until_stop(pool);
}
}
}
fn recycle_settled(&mut self) -> Result {
self.graph.reset_items()?;
self.config_cache = None;
Expand Down
Loading
Loading