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
28 changes: 19 additions & 9 deletions Documentation/gpu/asahi-g17-recovery-safety.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,23 @@ reproduction is claimed here.
render replays similarly expire after 10 s rather than polling forever when
admission or publication cannot proceed. Wakes/new clients do not refresh
either transaction timestamp; exact completion clears it.
* A per-device burst limit stops the runtime on the eighth actual scheduler
* A per-device burst limit stops the runtime on the eighth repeated scheduler
timeout in a 30 s window or the eighth restart handshake in a 30 s window.
VM changes, new publications, recovery generations and replay do not reset
those counters; terminal loss latches. The 30 s window contains eight
two-second expirations, including a stalled deferred timeout that cannot
complete its normal per-client settlement. This limits host recovery load even
when each individual handshake succeeds. Legitimate long jobs only consume
this budget after their independent bounded execution allowance expires.
A command's first expiry is charged to its own client, whose work it fails
(or spares behind another VM's), and does not count: otherwise one process
could spend the budget with one hung command per queue. Only an expiry of a
command whose earlier settlement did not end it counts. Likewise a restart
is counted only once it is classified, and not when it is charged to the VMs
it finds guilty: each found guilty for the first time, which costs its client
the device, or blamed again for no more restarts than the commands it held
then. A restart without a guilty VM, or one that keeps blaming a VM beyond
that, counts. VM changes, new publications, recovery generations and replay
do not reset those counters; terminal loss latches. The 30 s window holds
the nine two-second expirations of a stalled deferred timeout that cannot
complete its normal per-client settlement: its first, then the eight that
count. This limits host recovery load even when each individual handshake
succeeds. Legitimate long jobs only consume this budget after their
independent bounded execution allowance expires.

Lock order remains stop -> state and state -> preparation wait/reclaim. All
preparation joins and deferred fence completion/destruction run outside state.
Expand All @@ -63,13 +72,14 @@ EVENT_SLOTS; trace/statistics consume a snapshot producer. Render retirement
loops remove one retained tracker per successful iteration (or mark one as
accounted); compute replay consumes a retained replay per iteration. Shared
capacity deadlines remain absolute and failed fences do not release mappings
or return physical reservations. The new storm limits additionally bound
or return physical reservations. The storm limits additionally bound
repeated recoveries and timeouts across those paths.

KUnit exercises 64 consecutive watchdog timeouts with recovery pending under
real state/preparation mutexes, a retained lease that must time out rather
than be freed, late lease return with failed admission still closed, restart
storms and nonblocking replay status checks. The mailbox tests use normal RAM
storms, the published-expiry record and nonblocking replay status checks.
The mailbox tests use normal RAM
as never-empty RX and never-draining TX registers, invoking the production
poll/send functions for 64 RX passes and eight atomic TX timeouts plus a
sleeping TX timeout/removal control. The isolated Asahi scenario runs with
Expand Down
45 changes: 43 additions & 2 deletions drivers/gpu/drm/asahi/g17/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,9 @@ pub(crate) trait Backend: Send + Sync {
/// packet lacks. Called again once it signals.
fn prepare(&self, packet: &Arc<Packet>) -> Option<Fence>;
fn publish(&self, packet: Arc<Packet>) -> Result<Fence>;
fn timed_out(&self, packet: Arc<Packet>) -> sched::Status;
/// `again`: the watchdog already gave up on `packet` once while it was published, and
/// settling it then did not end it.
fn timed_out(&self, packet: Arc<Packet>, again: bool) -> sched::Status;
fn cancel(&self, packet: Arc<Packet>);
/// Transfer a timeout to an outstanding off-lock graph transaction, if any, or decide it
/// against other VMs' older work ([`super::timeout::decide`]). `renewals` and `excused`
Expand Down Expand Up @@ -395,9 +397,27 @@ struct Timeout<B: Backend> {
execution_renewals: u8,
shared_renewals: u8,
allowance: super::timeout::Allowance,
/// Whether the watchdog already expired the job while it was published.
published_expiry: PublishedExpiry,
packet: Arc<Packet>,
}

/// Whether a job's watchdog already expired while it was published: then settling it did not
/// end it, and the next expiry is passed to [`Backend::timed_out`] as `again`.
#[derive(Default)]
struct PublishedExpiry(bool);

impl PublishedExpiry {
/// An expiry of a job that was `published` before [`Backend::timed_out`] saw it; returns
/// `again` for that call. A publication racing the call is read as unpublished, so it gets
/// one more expiry of its own.
fn expire(&mut self, published: bool) -> bool {
let again = self.0;
self.0 |= published;
again
}
}

impl<B: Backend> Drop for Job<B> {
fn drop(&mut self) {
// Entity teardown can free a queued job without invoking cancel.
Expand All @@ -422,6 +442,7 @@ impl<B: Backend> sched::JobImpl for Job<B> {
execution_renewals: 0,
shared_renewals: 0,
allowance: super::timeout::Allowance::new(self.allowance_ms),
published_expiry: PublishedExpiry::default(),
packet: self.packet.clone(),
}
}
Expand Down Expand Up @@ -499,7 +520,8 @@ impl<B: Backend> sched::JobImpl for Job<B> {
// its parent callback intact while the driver settles the exact owner;
// reinsertion also handles completion racing with timeout observation.
if !finished {
job.backend.timed_out(job.packet.clone());
let again = job.published_expiry.expire(job.packet.is_published());
job.backend.timed_out(job.packet.clone(), again);
}
sched::Status::NoHang
}
Expand Down Expand Up @@ -647,3 +669,22 @@ impl<B: Backend> Scheduler<B> {
Ok(Fences { ready, completed, publication: host_publication, owner: packet.completion.clone() })
}
}

#[kernel::macros::kunit_tests(asahi_g17_job_expiry)]
mod tests {
use super::PublishedExpiry;

#[test]
fn only_an_expiry_after_a_published_one_is_again() {
let mut expiry = PublishedExpiry::default();
// Expiries before publication (capacity or graph waits) are never again.
assert!(!expiry.expire(false));
assert!(!expiry.expire(false));
// The first published expiry is the command's own; every later one is again.
assert!(!expiry.expire(true));
assert!(expiry.expire(true));
assert!(expiry.expire(true));
// Published at the read stays published: a later unpublished read cannot reset it.
assert!(expiry.expire(false));
}
}
74 changes: 57 additions & 17 deletions drivers/gpu/drm/asahi/g17/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ pub(super) struct ServiceResult {
pub(super) target_error: Option<Error>,
/// Every VM found guilty had failed before, and the restart dropped one of its commands.
pub(super) leftover: bool,
/// The restart found guilty VMs and is charged to them ([`VmStatus::charge_restart`]): each
/// was found guilty for the first time, which costs its client the device, or still held
/// work from then. It does not count toward the device's storm limit.
pub(super) charged: bool,
}

impl State {
Expand All @@ -174,6 +178,7 @@ impl State {
}
/// Like timeouts, restarts with work retired between them start a new window: each one
/// still costs the guilty client its device, but only restarts without progress stop the GPU.
/// Restarts charged to their guilty clients (`ServiceResult::charged`) are not counted.
pub(super) fn restart_limit(&mut self, now: u64) -> bool {
self.restarts.note_unless_progress(now, safety::retired())
}
Expand Down Expand Up @@ -309,7 +314,8 @@ pub(super) fn service<H: Host>(
host.recovery_mut().pending = None;

let (listed, exact, fallback) = (entries.listed, entries.exact, entries.fallback);
let (cancelled, blame, leftover) = classify(host, entries, request.blamed, attribution);
let (cancelled, blame, leftover, charged) =
classify(host, entries, request.blamed, attribution);
if listed != 0 && host.is_m5() {
// The M5 table only classifies (read_entries): each command is retired from its own
// queue's records, replayed when it never ran.
Expand Down Expand Up @@ -341,7 +347,7 @@ pub(super) fn service<H: Host>(
}
let scan_error = host.rescan_compute().err();
host.release_retired_compute();
Ok(ServiceResult { scan_error, target_error, leftover })
Ok(ServiceResult { scan_error, target_error, leftover, charged })
}

/// Walks the recovery table. G17P's is a packed list: records after its first invalid one are
Expand Down Expand Up @@ -383,9 +389,13 @@ fn read_entries<H: Host>(host: &mut H) -> Entries {
/// Also returns whether the firmware's blamed QID is still guilty after attribution: a blamed
/// render that had not started while others had (or with no culprit at all) is innocent, and its
/// work is spared like that of every other innocent VM instead of failing with EIO.
/// Last, whether every guilty VM had failed before this restart and it dropped one of their
/// Then whether every guilty VM had failed before this restart and it dropped one of their
/// commands: a failed VM publishes nothing new, so such restarts end with its queued work.
fn classify<Q: Queues>(queues: &mut Q, entries: Entries, blamed: Option<u8>, attribution: Attribution) -> (u128, bool, bool) {
/// Last, whether the restart is charged to the guilty VMs ([`VmStatus::charge_restart`], with
/// the commands each holds): one client's faults or hangs then cost only that client, however
/// many VMs it opens. A restart without a guilty VM, or one that keeps blaming a VM for more
/// than the work it held, is the device's.
fn classify<Q: Queues>(queues: &mut Q, entries: Entries, blamed: Option<u8>, attribution: Attribution) -> (u128, bool, bool, bool) {
let mut guilty_qids = entries.guilty | blamed.map_or(0, |qid| 1u128 << qid);
let cancelled = entries.cancelled;
match attribution {
Expand All @@ -396,7 +406,7 @@ fn classify<Q: Queues>(queues: &mut Q, entries: Entries, blamed: Option<u8>, att
let no_culprit = attribution == Attribution::NoCulprit;
let blame = blamed.is_some_and(|qid| guilty_qids & (1u128 << qid) != 0);
if guilty_qids == 0 && !no_culprit {
return (0, blame, false);
return (0, blame, false, false);
}
let mut guilty: [Option<Arc<VmStatus>>; MAX_GUILTY_VMS] = Default::default();
let mut count = 0;
Expand Down Expand Up @@ -432,7 +442,7 @@ fn classify<Q: Queues>(queues: &mut Q, entries: Entries, blamed: Option<u8>, att
}
}
if unresolved || (count == 0 && collateral == 0 && !no_culprit) {
return (0, blame, false);
return (0, blame, false, false);
}
let known = |status: &Arc<VmStatus>| guilty[..count].iter().flatten().any(|known| Arc::ptr_eq(known, status));
let mut dropped = false;
Expand All @@ -441,20 +451,27 @@ fn classify<Q: Queues>(queues: &mut Q, entries: Entries, blamed: Option<u8>, att
}
let leftover = count != 0 && dropped && guilty[..count].iter().flatten().all(|status| status.get() != 0);
guilty[..count].iter().flatten().for_each(|status| status.note_recovery_guilty());
// Commands each guilty VM holds, counted as they are classified.
let held: [core::cell::Cell<u32>; MAX_GUILTY_VMS] = Default::default();
let spared = queues.classify_work(&|status| {
guilty[..count]
.iter()
.find_map(|known| {
known
.as_ref()
.filter(|known| Arc::ptr_eq(known, status))
.map(|_| Class::Guilty)
})
let known = guilty[..count].iter()
.position(|known| known.as_ref().is_some_and(|known| Arc::ptr_eq(known, status)));
match known {
Some(index) => {
held[index].set(held[index].get().saturating_add(1));
Class::Guilty
}
// A VM an earlier recovery found guilty stays guilty. Spared, its leftover work would
// make the next blame on it collateral, and that restart would count as a storm.
.unwrap_or(if status.recovery_guilty() { Class::Guilty } else { Class::Spared })
None if status.recovery_guilty() => Class::Guilty,
None => Class::Spared,
}
});
// Every guilty VM is charged, even once one of them is over its count.
let charged = count != 0 && guilty[..count].iter().zip(&held).fold(true, |charged, (status, held)| {
status.as_ref().is_some_and(|status| status.charge_restart(held.get())) && charged
});
(cancelled & !(guilty_qids & !collateral) & spared, blame, leftover)
(cancelled & !(guilty_qids & !collateral) & spared, blame, leftover, charged)
}


Expand Down Expand Up @@ -676,14 +693,37 @@ mod tests {
#[test]
fn only_dropped_work_of_an_already_failed_vm_is_leftover() {
let mut queues = owners();
// A first failure counts toward the storm.
// A VM's first failure is not leftover work.
assert!(!leftover(&mut queues, 60));
queues.0[2].1.record(EIO);
assert!(leftover(&mut queues, 60));
// The restart dropped nothing of the failed VM.
assert!(!leftover(&mut queues, 40));
}

#[test]
fn restarts_are_charged_to_their_guilty_clients_and_only_unblamed_ones_to_the_device() {
let mut queues = owners();
let charged = |queues: &mut Owners, attribution| {
classify(queues, Entries::default(), None, attribution).3
};
// Nobody to blame: the device's.
assert!(!charged(&mut queues, Attribution::NoCulprit));
assert!(!charged(&mut queues, Attribution::Firmware));
// Each VM pays for its first restart, then for one more per command it held then (two
// each here).
assert!(charged(&mut queues, Attribution::Queues(1u128 << 60)));
for _ in 0..3 {
assert!(charged(&mut queues, Attribution::Queues(1u128 << 40)));
}
// A firmware that keeps blaming a for work it no longer holds stops the GPU as before,
// even with b, still within its count, blamed beside it.
assert!(!charged(&mut queues, Attribution::Queues(1u128 << 40)));
assert!(!charged(&mut queues, Attribution::Queues((1u128 << 40) | (1u128 << 60))));
assert!(charged(&mut queues, Attribution::Queues(1u128 << 60)));
assert!(!charged(&mut queues, Attribution::Queues(1u128 << 60)));
}

#[test]
fn a_guilty_vm_is_not_spared_by_another_vms_recovery() {
let mut queues = owners();
Expand Down
12 changes: 9 additions & 3 deletions drivers/gpu/drm/asahi/g17/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2641,10 +2641,16 @@ impl super::Firmware {
}

impl super::Shared {
/// Charge only real watchdog expirations, after the per-job allowance. A
/// changing client or recovery generation cannot mint a fresh storm budget.
pub(super) fn watchdog_timeout(self: &Arc<Self>) -> bool {
/// Charge only real watchdog expirations, after the per-job allowance. A command's first
/// expiry is its own client's: settling it fails that client's work, or spares it behind
/// another VM's, and the client can do that once per command it submits. Counted for the
/// device, one process's hung commands, one per queue, stopped the GPU for every client
/// until reboot. Only an expiry that settling the command did not end (`again`) counts
/// toward the storm limit; a changing client or recovery generation cannot mint a fresh
/// storm budget for those.
pub(super) fn watchdog_timeout(self: &Arc<Self>, again: bool) -> bool {
if self.crashed.load(Ordering::Acquire) { return true; }
if !again { return false; }
let stop = {
let mut state = self.state.lock();
state.as_deref_mut().is_none_or(|firmware| firmware.recovery.timeout_limit(now_ns()))
Expand Down
4 changes: 2 additions & 2 deletions drivers/gpu/drm/asahi/g17/runtime/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ impl job::Backend for Backend {
self.finish_publication(&packet, result, &mut deferred)
}

fn timed_out(&self, packet: Arc<Packet>) -> sched::Status {
fn timed_out(&self, packet: Arc<Packet>, again: bool) -> sched::Status {
// A packet still in publication, for example waiting for capacity or
// for its render pair's graph, has nothing visible to firmware and may
// not even have an installed pair. Its publisher owns its bounded wait
Expand All @@ -325,7 +325,7 @@ impl job::Backend for Backend {
return sched::Status::NoHang;
}
self.release_backlog(&packet);
if self.shared.watchdog_timeout() { return sched::Status::NoHang; }
if self.shared.watchdog_timeout(again) { return sched::Status::NoHang; }
let result = match packet.engine() {
Engine::Compute => self.timeout_compute(&packet),
Engine::Render => self.timeout_render(&packet),
Expand Down
19 changes: 13 additions & 6 deletions drivers/gpu/drm/asahi/g17/runtime/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -431,10 +431,6 @@ impl Firmware {
/// Preparation admission is already closed and all builders have joined.
pub(super) fn service_runtime_recovery(&mut self, deferred: &mut DeferredBatch) -> Result {
self.rings.invalidate_statistics();
if self.recovery.restart_limit(super::now_ns()) {
pr_warn!("G17: restart storm limit reached\n");
return Err(ETIMEDOUT);
}
let shared = self.primary.state.shared.clone();
let mut service = Service {
firmware: self,
Expand All @@ -453,8 +449,19 @@ impl Firmware {
.set_generation(service.firmware.recovery.generation());
service.firmware.rings.invalidate_statistics();
let result = result?;
if result.leftover && service.firmware.recovery.forgive_restart() {
pr_warn!("G17: recovery dropped queued work of an already failed VM; not counted as a restart storm\n");
// Counted once the restart is classified, so the restart that reaches the limit has
// still been serviced. One charged to its guilty clients costs them their devices and
// nobody else anything; counted for the device, a program that faulted the GPU eight
// times, opening it again each time, or that had queued eight faulting renders, stopped
// it for every client until reboot.
if !result.charged {
if service.firmware.recovery.restart_limit(super::now_ns()) {
pr_warn!("G17: restart storm limit reached\n");
return Err(ETIMEDOUT);
}
if result.leftover && service.firmware.recovery.forgive_restart() {
pr_warn!("G17: recovery dropped queued work of an already failed VM; not counted as a restart storm\n");
}
}
if let Some(error) = result.target_error {
dev_warn!(
Expand Down
Loading
Loading