diff --git a/Documentation/gpu/asahi-g17-recovery-safety.rst b/Documentation/gpu/asahi-g17-recovery-safety.rst index 37a5f0a9b0ab0..06e4e29d01772 100644 --- a/Documentation/gpu/asahi-g17-recovery-safety.rst +++ b/Documentation/gpu/asahi-g17-recovery-safety.rst @@ -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. @@ -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 diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index f5ddc1419361a..b6536c07b443f 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -358,7 +358,9 @@ pub(crate) trait Backend: Send + Sync { /// packet lacks. Called again once it signals. fn prepare(&self, packet: &Arc) -> Option; fn publish(&self, packet: Arc) -> Result; - fn timed_out(&self, packet: Arc) -> 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, again: bool) -> sched::Status; fn cancel(&self, packet: Arc); /// 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` @@ -395,9 +397,27 @@ struct Timeout { 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, } +/// 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 Drop for Job { fn drop(&mut self) { // Entity teardown can free a queued job without invoking cancel. @@ -422,6 +442,7 @@ impl sched::JobImpl for Job { execution_renewals: 0, shared_renewals: 0, allowance: super::timeout::Allowance::new(self.allowance_ms), + published_expiry: PublishedExpiry::default(), packet: self.packet.clone(), } } @@ -499,7 +520,8 @@ impl sched::JobImpl for Job { // 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 } @@ -647,3 +669,22 @@ impl Scheduler { 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)); + } +} diff --git a/drivers/gpu/drm/asahi/g17/recovery.rs b/drivers/gpu/drm/asahi/g17/recovery.rs index f6decfd7f630e..3e89095e56c2c 100644 --- a/drivers/gpu/drm/asahi/g17/recovery.rs +++ b/drivers/gpu/drm/asahi/g17/recovery.rs @@ -158,6 +158,10 @@ pub(super) struct ServiceResult { pub(super) target_error: Option, /// 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 { @@ -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()) } @@ -309,7 +314,8 @@ pub(super) fn service( 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. @@ -341,7 +347,7 @@ pub(super) fn service( } 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 @@ -383,9 +389,13 @@ fn read_entries(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(queues: &mut Q, entries: Entries, blamed: Option, 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(queues: &mut Q, entries: Entries, blamed: Option, 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 { @@ -396,7 +406,7 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, 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>; MAX_GUILTY_VMS] = Default::default(); let mut count = 0; @@ -432,7 +442,7 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, att } } if unresolved || (count == 0 && collateral == 0 && !no_culprit) { - return (0, blame, false); + return (0, blame, false, false); } let known = |status: &Arc| guilty[..count].iter().flatten().any(|known| Arc::ptr_eq(known, status)); let mut dropped = false; @@ -441,20 +451,27 @@ fn classify(queues: &mut Q, entries: Entries, blamed: Option, 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; 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) } @@ -676,7 +693,7 @@ 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)); @@ -684,6 +701,29 @@ mod tests { 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(); diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index d193f7d64ee93..da80a9b1d676e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -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) -> 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, 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())) diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 278534899b570..f9d2999a4e1d5 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -314,7 +314,7 @@ impl job::Backend for Backend { self.finish_publication(&packet, result, &mut deferred) } - fn timed_out(&self, packet: Arc) -> sched::Status { + fn timed_out(&self, packet: Arc, 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 @@ -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), diff --git a/drivers/gpu/drm/asahi/g17/runtime/events.rs b/drivers/gpu/drm/asahi/g17/runtime/events.rs index 1eca0cc036fc7..6b85d1f5a729d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/events.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/events.rs @@ -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, @@ -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!( diff --git a/drivers/gpu/drm/asahi/g17/status.rs b/drivers/gpu/drm/asahi/g17/status.rs index 54f5160f32f11..cf19488f20f59 100644 --- a/drivers/gpu/drm/asahi/g17/status.rs +++ b/drivers/gpu/drm/asahi/g17/status.rs @@ -4,13 +4,16 @@ use crate::debug::*; use crate::gem; -use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering}; use kernel::{new_mutex, prelude::*, str::BStr, sync::Mutex, task::Pid}; const DEBUG_CLASS: DebugFlags = DebugFlags::Errors; const MIRROR_MAX_SIZE: usize = 64 * 1024; +/// [`VmStatus::restarts_left`] of a VM no restart has been charged to. +const UNCHARGED: u32 = u32::MAX; + /// A VM and its accepted jobs share this status, including after queue destruction. /// Client failure is separate from hardware admission: recovery may preserve the /// VM while failed accepted work must still be reported before signalling fences. @@ -27,6 +30,9 @@ pub(crate) struct VmStatus { warned: AtomicBool, /// A GPU recovery found this VM's work guilty. recovery_guilty: AtomicBool, + /// Further restarts that may find this VM guilty and still be charged to it + /// ([`Self::charge_restart`]), or [`UNCHARGED`] before the first. + restarts_left: AtomicU32, /// The process that created the VM, named in the failure report. tgid: Pid, comm: [u8; 16], @@ -62,6 +68,7 @@ impl VmStatus { teardown_expired: AtomicBool::new(false), warned: AtomicBool::new(false), recovery_guilty: AtomicBool::new(false), + restarts_left: AtomicU32::new(UNCHARGED), tgid, comm, mirror <- new_mutex!(None, "Asahi VM status mirror"), @@ -82,6 +89,22 @@ impl VmStatus { self.recovery_guilty.load(Ordering::Acquire) } + /// Charges a firmware restart that found this VM guilty to it, with `in_flight` of its + /// commands still held then. The first such restart costs its client the device. After it the + /// VM publishes nothing new, but each command it had in flight may still hang or fault the + /// GPU once as it runs. Returns false once restarts have found the VM guilty more often than + /// that: the firmware keeps blaming it for something it no longer runs. Called only from a + /// recovery, under the device mutex. + pub(crate) fn charge_restart(&self, in_flight: u32) -> bool { + let left = match self.restarts_left.load(Ordering::Relaxed) { + UNCHARGED => in_flight.min(UNCHARGED - 1), + 0 => return false, + left => left - 1, + }; + self.restarts_left.store(left, Ordering::Relaxed); + true + } + /// The client's VM handle is gone (`release_mirror`): the client submits nothing more. pub(crate) fn client_closed(&self) -> bool { self.client_closed.load(Ordering::Acquire) @@ -286,6 +309,25 @@ mod tests { assert!(status.warned.load(Ordering::Acquire)); } + #[test] + fn restarts_are_charged_to_a_vm_only_for_the_work_it_had_in_flight() { + let Ok(status) = KBox::pin_init(VmStatus::new(), GFP_KERNEL) else { + panic!("allocation failed"); + }; + // The first restart is charged whatever the VM holds, then one per command it held. + assert!(status.charge_restart(3)); + for _ in 0..3 { + assert!(status.charge_restart(5)); + } + assert!(!status.charge_restart(5)); + assert!(!status.charge_restart(0)); + let Ok(status) = KBox::pin_init(VmStatus::new(), GFP_KERNEL) else { + panic!("allocation failed"); + }; + assert!(status.charge_restart(0)); + assert!(!status.charge_restart(1)); + } + #[test] fn an_open_client_warns_on_its_first_error_only() { let Ok(status) = KBox::pin_init(VmStatus::new(), GFP_KERNEL) else { diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index ad83a154d7b7b..560f15a9b92da 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -315,7 +315,7 @@ def watchdog_publication_guard_tests(source): at = text.index(' fn timed_out(') body = text[at:text.index('\n }\n', at)] guard = body.index('if !packet.is_published() {\n return sched::Status::NoHang;') - assert guard < body.index('self.release_backlog(&packet);') < body.index('self.shared.watchdog_timeout()'), 'timed_out' + assert guard < body.index('self.release_backlog(&packet);') < body.index('self.shared.watchdog_timeout('), 'timed_out' for path, name in [('g17/runtime/render/settle.rs', 'pub(in crate::g17) fn timeout_render('), ('g17/runtime/compute_control.rs', 'pub(super) fn timeout_compute(')]: text = (source / path).read_text()