diff --git a/drivers/gpu/drm/asahi/buffer.rs b/drivers/gpu/drm/asahi/buffer.rs index 1680fd05d035..7a19153a9096 100644 --- a/drivers/gpu/drm/asahi/buffer.rs +++ b/drivers/gpu/drm/asahi/buffer.rs @@ -294,6 +294,18 @@ impl SceneG14V13_5 { pub(crate) fn render_addresses(&self) -> (u64, u64) { self.object.with(|raw, _| (raw.user_buffer.or(0).into(), raw.stats.into())) } + + /// Zeroes the first `bytes` of the Tail Pointer Cache, so that a fragment pass run after + /// a firmware recovery stopped its tiler finds no tiles. + /// + /// # Safety + /// + /// The GPU must not access the TPC during the call (its tiler is stopped and no other + /// render using this buffer is in flight), and no CPU reference into it may be live. + pub(crate) unsafe fn clear_tpc(&self, bytes: usize) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.object.tpc.zero_prefix(bytes) } + } } /// Host-owned parameter-buffer inputs that persist across firmware submissions. diff --git a/drivers/gpu/drm/asahi/g14_v27_2.rs b/drivers/gpu/drm/asahi/g14_v27_2.rs index a56f4542d7e0..24a1b9c66e23 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2.rs @@ -40,6 +40,15 @@ use crate::{ m3::m3_submit::{Command, Packet}, }; +/// The recovery handshake is the one G16 answers: share its decisions (which phase the host may +/// answer, how a snapshot entry decodes, the recovery-storm window) instead of restating them. +/// Its FirmwareData offsets are G16's own and unused here. +#[path = "g16/recovery/logic.rs"] +#[allow(dead_code)] +mod recovery_logic; +use recovery_logic::{RecoveryAction, SnapshotEntry}; +use crate::g14_v27_2_abi::{self, Stopped}; + /// RTKit endpoints of the GPU firmware. const EP_FIRMWARE: u8 = 0x20; const EP_DOORBELL: u8 = 0x21; @@ -111,6 +120,20 @@ const RETIRE_WAIT_US: i64 = 2000; const RESOURCE_RETRY_MS: u32 = 10; /// Work item for the poll. Ordinary firmware notifications can still queue immediate work. const RETRY_WORK: u64 = 1; +/// The firmware's recovery handshake (the G16/M3 order and limits): phase 1 follows the error +/// event within 50 ms; the whole handshake within 1 s; then the stopped work leaves its queue. +const PHASE1_WAIT_MS: i64 = 50; +const HANDSHAKE_MS: i64 = 1000; +const RECOVERY_DRAIN_MS: i64 = 1000; +/// Further recoveries answered while the stopped work drains (work behind it can time out in +/// turn) before the runtime gives up. +const FURTHER_RECOVERIES: u32 = 4; +/// Event ring record kinds kept for the logs of a timeout or a recovery. +const EVENT_HISTORY: usize = 8; +/// Rounds start only within this budget; one round takes at most PHASE1_WAIT_MS + +/// HANDSHAKE_MS + RECOVERY_DRAIN_MS, so the lock is released well within the 10 s scheduler +/// job timeout. +const RECOVERY_BUDGET_MS: i64 = 5000; struct FirmwareWait { since: Instant, @@ -498,6 +521,20 @@ pub(crate) fn start<'a>( Ok(Started { backend, drm, binding, resources }) } +/// Whether the packet's VM has failed (`VmStatus` latched): its work is no longer admitted. +fn vm_failed(packet: &Packet) -> bool { + packet.vm.status().is_some_and(|status| status.get() != 0) +} + +/// Latches the VM of work a recovery stopped as guilty, before the work drains: from here on +/// `submit` refuses it and `pump` publishes none of its queued packets. +fn latch_guilty(packet: &Packet, error: Error) { + if let Some(status) = packet.vm.status() { + status.note_recovery_guilty(); + status.record(error); + } +} + struct Inflight { packet: Arc, last: bool, @@ -507,6 +544,8 @@ struct Inflight { /// Queue publications up to and including this command, counted from take-over. ordinal: u64, started: Instant, + /// Set when the firmware stopped this command: it fails its packet when it leaves the queue. + doomed: Option, _bind: mmu::VmBind, } @@ -519,6 +558,17 @@ struct RenderFlight { stamps: [event::EventValue; 2], targets: [u32; 2], started: Instant, + doomed: Option, +} + +/// Who a recovery round blamed, for its log line: the client, and the stopped work's stamps +/// (render: tiler and fragment; compute: the stopped command's and the queue's current one). +struct Blamed { + owner: crate::m3::m3_submit::Owner, + stamps: [u32; 2], + /// The stopped compute command's queue ordinal: the drain waits for this command only. The + /// packet's later commands were not stopped and retire (failed) through the normal path. + stopped: Option, } struct State { @@ -555,6 +605,25 @@ struct State { accepting: bool, submitted: u64, retired: u64, + /// A fault or timeout the firmware reported (error, named slot), answered by `recover`. + firmware_error: Option<(Error, i32)>, + recoveries: u64, + /// Recovery-storm window (`recovery_logic::admit`): its start and the recoveries in it. + recovery_window: u64, + recovery_count: u32, + /// Reports read and rounds answered: tells a stale report from a new one. + ledger: g14_v27_2_abi::RecoveryLedger, + /// Kind words of the last event ring records read, and how many were read in all. + events: [u32; EVENT_HISTORY], + events_read: u64, + /// Packets with a command the firmware stopped (`blame`), with their VM job guard, kept + /// for the rest of the boot: the firmware may still reach that memory. Allocated with + /// `g14_v27_2_abi::QUARANTINE_LIMIT` places at start, so keeping one never allocates. + kept: KVec>, + /// The stopped commands of those packets, with their VM binding and scene, once they left + /// their queue (`Runtime::keep`). Held, never read. + kept_compute: KVec, + kept_renders: KVec, /// Set when a sleep/wake failure may have left the GPU domain unpowered or stopped so /// teardown skips live-hardware MMIO and RTKit operations. hardware_unreachable: bool, @@ -571,20 +640,44 @@ impl State { { last.publication_error = Some(err); } else { - packet.release_guard(); + if g14_v27_2_abi::guard_releasable(false, self.kept(packet)) { + packet.release_guard(); + } packet.finish(Err(err)); } } + /// The kinds of the last event ring records read, oldest first, for a log line. + fn recent_events(&self) -> ([u32; EVENT_HISTORY], usize) { + let count = self.events_read.min(EVENT_HISTORY as u64) as usize; + let mut out = [0; EVENT_HISTORY]; + for (i, kind) in out.iter_mut().take(count).enumerate() { + let at = (self.events_read - count as u64 + i as u64) % EVENT_HISTORY as u64; + *kind = self.events[at as usize]; + } + (out, count) + } + fn running(&self) -> bool { !self.inflight.is_empty() || self.rendering.is_some() } - fn owns(&self, packet: &Arc) -> bool { + /// Whether a queue holds any of the packet's commands. + fn live(&self, packet: &Arc) -> bool { self.inflight.iter().any(|flight| Arc::ptr_eq(&flight.packet, packet)) || self.rendering.as_ref().is_some_and(|flight| Arc::ptr_eq(&flight.packet, packet)) } + /// Whether a recovery stopped a command of the packet: it stays owned for the boot. + fn kept(&self, packet: &Arc) -> bool { + self.kept.iter().any(|kept| Arc::ptr_eq(kept, packet)) + } + + /// Whether the runtime owns the packet's VM job guard (`g14_v27_2_abi::guard_releasable`). + fn owns(&self, packet: &Arc) -> bool { + !g14_v27_2_abi::guard_releasable(self.live(packet), self.kept(packet)) + } + fn pending(&self, packet: &Arc) -> bool { self.pending.iter().any(|(current, _)| Arc::ptr_eq(current, packet)) } @@ -670,6 +763,9 @@ impl Runtime { if packet.commands.is_empty() { return Err(ENOTSUPP); } + // A VM that lost its context (a recovery found it guilty, or its work failed) runs + // nothing more on the GPU. + if vm_failed(&packet) { return Err(EIO); } let mut guard = self.state.lock(); let state = Option::as_mut(&mut *guard).ok_or(ENODEV)?; if !self.healthy() { return Err(EIO); } @@ -776,6 +872,11 @@ impl Runtime { } while state.inflight.len() < POOL_SLOTS - 1 && !state.pending.is_empty() { let (packet, index) = (state.pending[0].0.clone(), state.pending[0].1); + if vm_failed(&packet) { + // Queued before its VM failed: none of it is published from now on. + state.fail_publication(&packet, EIO); + continue; + } let command = packet.commands[index]; let paired = matches!(command, Command::Render { .. }); if paired && state.running() { return; } @@ -841,7 +942,8 @@ impl Runtime { let ordinal = state.published + 1; // Commit ownership before the firmware can see the new work. state.inflight.push(Inflight { packet: packet.clone(), last, stamp, slot, ordinal, - publication_error: None, started: Instant::now(), _bind: bind }, GFP_KERNEL)?; + publication_error: None, started: Instant::now(), doomed: None, _bind: bind }, + GFP_KERNEL)?; packet.mark_published(); submission.publish(); state.pool.mark_published(slot); @@ -898,7 +1000,7 @@ impl Runtime { let fs_post = state.root.stage_render(FRAGMENT, &fs_work)?; state.rendering = Some(RenderFlight { packet: packet.clone(), last, bind, scene, slots, stamps, - targets: [ta_post.target(), fs_post.target()], started: Instant::now(), + targets: [ta_post.target(), fs_post.target()], started: Instant::now(), doomed: None, }); queue.published(); packet.mark_published(); @@ -940,19 +1042,26 @@ impl Runtime { fn retire_render(&self, state: &mut State) -> Result { let Some(flight) = state.rendering.as_ref() else { return Ok(()); }; - let mut ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; - let mut fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + let (targets, stamps, doomed, started) = + (flight.targets, flight.stamps, flight.doomed, flight.started); + let done = |root: &RootV27_2, dm: usize| -> Result { + // A command the firmware stopped leaves its queue without reaching its stamp. + if doomed.is_some() { root.render_retired(dm, targets[dm]) } + else { root.render_done(dm, targets[dm], stamps[dm]) } + }; + let mut ta_done = done(&state.root, TILER)?; + let mut fs_done = done(&state.root, FRAGMENT)?; if !(ta_done && fs_done) - && state.root.render_queue(TILER).1 >= flight.stamps[TILER] - && state.root.render_queue(FRAGMENT).1 >= flight.stamps[FRAGMENT] + && state.root.render_queue(TILER).1 >= stamps[TILER] + && state.root.render_queue(FRAGMENT).1 >= stamps[FRAGMENT] { // As on the compute queue, the final stamp precedes the retired cursor and // there may be no separate notification when the cursor changes. let start = Instant::::now(); while !(ta_done && fs_done) && start.elapsed() < Delta::from_micros(RETIRE_WAIT_US) { fsleep(Delta::from_micros(20)); - ta_done = state.root.render_done(TILER, flight.targets[TILER], flight.stamps[TILER])?; - fs_done = state.root.render_done(FRAGMENT, flight.targets[FRAGMENT], flight.stamps[FRAGMENT])?; + ta_done = done(&state.root, TILER)?; + fs_done = done(&state.root, FRAGMENT)?; } } if ta_done && fs_done { @@ -960,20 +1069,316 @@ impl Runtime { for slot in flight.slots { self.retire_slot(state, slot); } - if flight.last { + if let Some(err) = flight.doomed { + self.fail_doomed(state, &flight.packet, err); + self.keep(&mut state.kept_renders, flight); + } else if flight.last { flight.packet.retired(); } else if !state.pending(&flight.packet) { flight.packet.release_guard(); } - } else if flight.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + } else if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: render timed out: TA retired={} fragment retired={}\n", ta_done, fs_done); - state.root.log_timeout(&self.dev); - state.fault.log(&self.dev); + if g14_v27_2_abi::command_timeout_action(state.root.recovery_phase()?) + == g14_v27_2_abi::TimeoutAction::Recover + { + // The firmware has a round open whose event was not seen. Recovery blames the + // work it stopped and waits until that left its queue. Then retire again, so a + // stopped render's fence is signalled and the queue behind it runs without + // waiting for another message; an innocent render got its clock restarted. + if self.recover(state, ETIMEDOUT, -1)? { + return self.retire_render(state); + } + } + self.log_silent_hang(state, "render"); return Err(ETIMEDOUT); } Ok(()) } + /// Fails a packet the firmware stopped, once none of its commands is in a queue: its + /// unpublished commands are withdrawn, and its VM records the error (the client sees a + /// lost context). Other clients' work is not touched. + /// + /// A stopped command left its queue without a completion stamp: that proves queue progress, + /// not that the GPU no longer reaches its memory (the G16 rule, `Retirement::Aborted`). So + /// its VM job guard is not released: the error completion quarantines it (no mapping + /// changes), the packet stays in `State::kept` (`blame`), and the caller keeps the flight + /// with its VM binding and scene (`keep`), all for the rest of the boot. Pool slots follow + /// the normal rule: reused only after the firmware unregisters them (`free_slots`), and + /// then in the slot's other buffer, so the stopped command stays intact. + fn fail_doomed(&self, state: &mut State, packet: &Arc, err: Error) { + if state.live(packet) { return; } + if let Some(i) = state.pending.iter().position(|(p, _)| Arc::ptr_eq(p, packet)) { + let _ = state.pending.remove(i); + } + // Record it even if a racing scheduler timeout already claimed the fence (as fail_all). + if let Some(status) = packet.vm.status() { status.record(err); } + packet.finish(Err(err)); + } + + /// Keeps a stopped command that left its queue, with its VM binding and scene, for the rest + /// of the boot (`State::kept_compute`, `kept_renders`). Its packet is already in + /// `State::kept`, so ownership does not depend on this allocation. If it fails, the flight + /// is leaked, which keeps it as well; it is never dropped. + fn keep(&self, list: &mut KVec, flight: T) { + if list.reserve(1, GFP_KERNEL).is_err() { + dev_warn!(self.dev, "GPU: no memory to track a stopped command; leaking it\n"); + core::mem::forget(flight); + return; + } + if let Err(kernel::alloc::kvec::PushError(flight)) = list.push_within_capacity(flight) { + core::mem::forget(flight); + } + } + + /// Adds the packet of stopped work to `State::kept` before anything is marked, so it stays + /// owned from here on. Err(EIO) once `g14_v27_2_abi::QUARANTINE_LIMIT` packets are kept: + /// the caller then fails all work, and published work stays owned. + fn reserve_kept(&self, state: &mut State, packet: &Arc) -> Result { + if state.kept(packet) { return Ok(()); } + if !g14_v27_2_abi::quarantine_fits(state.kept.len()) { + dev_err!(self.dev, "GPU: {} clients' stopped work kept this boot; not recovering more\n", + state.kept.len()); + return Err(EIO); + } + // Within the capacity allocated at start: never allocates. + state.kept.push_within_capacity(packet.clone()).map_err(|_| EIO) + } + + /// Marks the work the firmware's snapshot named (`g14_v27_2_abi::Attribution`): the + /// published render pair, or the compute command with that completion stamp and the rest of + /// its packet. Err(EIO) if that work is no longer tracked: the caller then fails all work. + fn blame(&self, state: &mut State, error: Error, work: Stopped) -> Result { + let blamed = match work { + Stopped::Render => { + let Some(packet) = state.rendering.as_ref().map(|f| f.packet.clone()) + else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; + let Some(flight) = state.rendering.as_mut() else { return Err(EIO); }; + flight.doomed = Some(error); + latch_guilty(&flight.packet, error); + Blamed { owner: flight.packet.owner, + stamps: [flight.stamps[TILER].raw(), flight.stamps[FRAGMENT].raw()], + stopped: None } + } + Stopped::Compute(stamp) => { + let flights = state.inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + let Some((packet, stopped)) = g14_v27_2_abi::stopped_compute(flights, state.retired_total, stamp) + .map(|i| (state.inflight[i].packet.clone(), state.inflight[i].ordinal)) + else { return Err(EIO); }; + self.reserve_kept(state, &packet)?; + let owned = |f: &&mut Inflight| Arc::ptr_eq(&f.packet, &packet); + for flight in state.inflight.iter_mut().filter(owned) { + flight.doomed.get_or_insert(error); + } + latch_guilty(&packet, error); + Blamed { owner: packet.owner, stamps: [stamp, state.queue_stamp()], + stopped: Some(stopped) } + } + }; + Ok(blamed) + } + + /// The last resort of a command timeout: the firmware has no recovery round open, so it + /// reported nothing the host can answer. Logs what a row needs to tell a silent hang from a + /// missed report: queue positions and recovery words (`log_timeout`), the MMU fault status, + /// and the last event ring kinds with the report and round counts. + fn log_silent_hang(&self, state: &State, work: &str) { + state.root.log_timeout(&self.dev); + state.fault.log(&self.dev); + let (events, seen) = state.recent_events(); + let (reports, answered) = state.ledger.counts(); + dev_err!(self.dev, "GPU: {} timed out with no recovery round open: last events {:?} ({} read), {} reports, {} rounds answered (last {:?}); failing all work\n", + work, &events[..seen], state.events_read, reports, answered, state.ledger.last()); + } + + /// Whether the stopped work has left its queue: the render pair, or the compute command at + /// `stopped` (its packet's later commands run normally and are failed as they retire). + fn doomed_retired(&self, state: &mut State, stopped: Option) -> Result { + if let Some(flight) = state.rendering.as_ref() { + if flight.doomed.is_some() { + return Ok(state.root.render_retired(TILER, flight.targets[TILER])? + && state.root.render_retired(FRAGMENT, flight.targets[FRAGMENT])?); + } + } + let Some(ordinal) = stopped.or_else(|| + state.inflight.iter().rev().find(|f| f.doomed.is_some()).map(|f| f.ordinal)) + else { return Ok(true); }; + self.advance(state)?; + Ok(state.retired_total >= ordinal) + } + + /// Waits up to `ms` for the firmware's next recovery phase: 1 before the host answered, + /// 3 with the same `generation` after it answered 2. Ok(None) on timeout; Err(EPROTO) on + /// any phase the protocol does not allow (`recovery_logic::action`). + fn wait_recovery(&self, state: &mut State, answered: bool, generation: u64, ms: i64) + -> Result> { + let start = Instant::::now(); + loop { + let phase = state.root.recovery_phase()?; + let same = !answered || state.root.halt_count()? == generation; + match recovery_logic::action(phase, answered, same) { + RecoveryAction::Wait => {} + RecoveryAction::ProtocolError => { + dev_err!(self.dev, "GPU: recovery phase {} (answered {}, same generation {})\n", + phase, answered, same); + return Err(EPROTO); + } + found => return Ok(Some(found)), + } + if start.elapsed() > Delta::from_millis(ms) { return Ok(None); } + if state.peer.is_crashed() { return Err(EIO); } + let _ = state.root.drain(); + fsleep(Delta::from_millis(1)); + } + } + + /// The firmware recovery handshake after a fault or command timeout (the G16/M3 protocol). + /// The firmware stops every queue and publishes phase 1 with a generation and a snapshot of + /// the stopped work; the host marks that work (`blame`), clears the tiler storage of a + /// stopped tiler, answers 2, waits for 3 with the same generation and answers 0. The stopped + /// work then leaves its queue and fails only its own packet and VM; the next recoveries + /// while it drains are answered the same way, a bounded number of times. Errors here fail + /// all work (the runtime is not trusted). Ok(false) if the firmware opened no round within + /// PHASE1_WAIT_MS: the caller decides whether its report was stale. + fn recover(&self, state: &mut State, error: Error, slot: i32) -> Result { + state.root.log_timeout(&self.dev); + let mut rounds = 0; + // A round the host already answered must not be answered again. + let mut previous = state.ledger.last(); + let began = Instant::::now(); + loop { + // The state lock is held throughout: keep the whole recovery, including a last round + // started at the budget, inside the DRM scheduler's job timeout. + if began.elapsed() > Delta::from_millis(RECOVERY_BUDGET_MS) { + dev_err!(self.dev, "GPU: recovery took more than {} ms\n", RECOVERY_BUDGET_MS); + return Err(ETIMEDOUT); + } + if self.wait_recovery(state, false, 0, PHASE1_WAIT_MS)?.is_none() { + // A further round starts at a phase 1 the drain saw: it cannot go missing. + if rounds > 0 { return Err(EPROTO); } + return Ok(false); + } + let now = ::ktime_get() as u64; + if !recovery_logic::admit(now, &mut state.recovery_window, &mut state.recovery_count) { + dev_err!(self.dev, "GPU: {} recoveries in {} s; not answering more\n", + recovery_logic::WINDOW_LIMIT, recovery_logic::WINDOW_NS / 1_000_000_000); + return Err(EIO); + } + let generation = state.root.halt_count()?; + if !g14_v27_2_abi::new_round(previous, generation) { + dev_err!(self.dev, "GPU: recovery generation {} repeated\n", generation); + return Err(EPROTO); + } + previous = Some(generation); + // Retired work must not be blamed: refresh the retired position first. + self.advance(state)?; + let render = state.rendering.as_ref() + .map(|f| [f.stamps[TILER].raw(), f.stamps[FRAGMENT].raw()]); + let mut attribution = g14_v27_2_abi::Attribution::default(); + let mut entries = 0; + let mut first = [(0u32, 0u32); 4]; + let mut stopped_tiler = false; + for i in 0..gpu::RECOVERY_SNAPSHOT_ENTRIES { + let (flags, target) = state.root.recovery_entry(i)?; + let Some(entry) = SnapshotEntry::decode(flags, target) else { break; }; + entries += 1; + stopped_tiler |= gpu::stopped_tiler(entry.flags); + let retired = state.retired_total; + let inflight = &state.inflight; + attribution.add(entry.flags, entry.target, render, |stamp| { + let flights = inflight.iter().map(|f| (f.stamp.raw(), f.ordinal)); + g14_v27_2_abi::stopped_compute(flights, retired, stamp).is_some() + }); + if let Some(at) = first.get_mut(i) { *at = (entry.flags, entry.target); } + } + let shown = &first[..entries.min(first.len())]; + let (events, seen) = state.recent_events(); + // Every round is attributed: work behind the first stopped command can time out in + // turn. Unnamed or ambiguous stopped work keeps the fail-stop. + let Some(work) = attribution.result() else { + dev_err!(self.dev, "GPU: recovery {} ({:?}, slot {}) names no single tracked command: snapshot ({} entries) {:x?}, events {:?}\n", + generation, error, slot, entries, shown, &events[..seen]); + return Err(EIO); + }; + let blamed = self.blame(state, error, work)?; + let (what, second) = match work { + Stopped::Render => ("render, tiler", "fragment"), + Stopped::Compute(_) => ("compute", "queue at"), + }; + dev_warn!(self.dev, "GPU: recovery {} ({:?}, slot {}, events {:?}): snapshot ({} entries) {:x?}; stopped {} {:#x} ({} {:#x}) of {}[{}]\n", + generation, error, slot, &events[..seen], entries, shown, what, + blamed.stamps[0], second, blamed.stamps[1], + blamed.owner.process(), blamed.owner.pid); + if stopped_tiler { + if let Some(flight) = state.rendering.as_ref() { + let ta_left = state.root.render_retired(TILER, flight.targets[TILER])?; + if !ta_left { + // SAFETY: the firmware is in recovery phase 1 with every queue stopped, + // so the GPU does not access the stopped tiler's TPC; the CPU reads it + // nowhere, and the state lock (held) serializes every render flight. + unsafe { flight.scene.clear_tpc()? }; + dev_err!(self.dev, "GPU: cleared the stopped tiler's TPC storage\n"); + } + } + } + let start = Instant::::now(); + state.root.answer_recovery(2)?; + let mut reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + if reached.is_none() { + dev_warn!(self.dev, "GPU: no recovery phase 3 in {} ms; ringing the device-control doorbell\n", + HANDSHAKE_MS / 2); + let _ = state.peer.as_mut().send_message(EP_DOORBELL, gpu::DEVICE_CONTROL_KICK); + reached = self.wait_recovery(state, true, generation, HANDSHAKE_MS / 2)?; + } + if reached != Some(RecoveryAction::Resume) { + return Err(ETIMEDOUT); + } + state.root.answer_recovery(0)?; + state.ledger.answered(generation); + dev_info!(self.dev, "GPU: recovery {} answered in {} ms\n", + generation, start.elapsed().as_millis()); + let start = Instant::::now(); + loop { + let _ = state.root.drain(); + if self.doomed_retired(state, blamed.stopped)? { + state.recoveries += 1; + // Work behind the stopped command waited out the recovery: restart its clocks. + let now = Instant::now(); + for flight in state.inflight.iter_mut() { flight.started = now; } + if let Some(flight) = state.rendering.as_mut() { flight.started = now; } + dev_err!(self.dev, + "GPU: recovered ({} so far): stopped work left the queue after {} ms\n", + state.recoveries, start.elapsed().as_millis()); + return Ok(true); + } + if state.peer.is_crashed() { return Err(EIO); } + // Phase 0 = still draining; 1 = a new recovery (a new generation is checked + // at the next round); the host's own phases mean the handshake was misread. + match recovery_logic::action(state.root.recovery_phase()?, false, true) { + RecoveryAction::Wait => {} + RecoveryAction::MarkAndAcknowledge => break, + _ => { + dev_err!(self.dev, "GPU: recovery phase {} while the stopped work drained\n", + state.root.recovery_phase()?); + return Err(EPROTO); + } + } + if start.elapsed() > Delta::from_millis(RECOVERY_DRAIN_MS) { + dev_err!(self.dev, "GPU: stopped work did not leave the queue\n"); + state.root.log_timeout(&self.dev); + return Err(ETIMEDOUT); + } + fsleep(Delta::from_millis(1)); + } + rounds += 1; + dev_err!(self.dev, "GPU: firmware entered recovery again while the stopped work drained ({})\n", + rounds); + if rounds > FURTHER_RECOVERIES { return Err(EIO); } + } + } + /// Reads the queue's retired position into `retired_total`. fn advance(&self, state: &mut State) -> Result { let (_, raw) = state.root.progress()?; @@ -996,9 +1401,13 @@ impl Runtime { } fn process_events(&self, state: &mut State) -> Result { + // A fault and a timeout read in one pass are one report (`RecoveryLedger`). + let mut reported = false; // Limit one pass to the ring capacity. Further arrivals notify the worker again. for _ in 0..256 { - let Some((cursor, event)) = state.root.peek_event()? else { break; }; + let Some((cursor, kind, event)) = state.root.peek_event()? else { break; }; + state.events[(state.events_read % EVENT_HISTORY as u64) as usize] = kind; + state.events_read += 1; match event { FirmwareEvent::Grow(request) if request.halt_count == state.root.halt_count()? => { let Some(reply) = state.root.reserve_control_reply()? else { @@ -1024,6 +1433,17 @@ impl Runtime { state.root.consume_event(cursor)?; return Err(EIO); } + FirmwareEvent::Timeout { slot } => { + dev_err!(self.dev, "GPU firmware timed out a command (slot {})\n", slot); + state.firmware_error.get_or_insert((ETIMEDOUT, slot)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } + } + FirmwareEvent::Fault => { + dev_err!(self.dev, "GPU firmware reported a GPU fault\n"); + state.fault.log(&self.dev); + state.firmware_error.get_or_insert((EIO, -1)); + if !core::mem::replace(&mut reported, true) { state.ledger.report(); } + } FirmwareEvent::Grow(_) | FirmwareEvent::Notification => {} } state.waiting_control = None; @@ -1046,6 +1466,28 @@ impl Runtime { self.fail_all(state, err); return; } + if let Some((error, slot)) = state.firmware_error.take() { + match self.recover(state, error, slot) { + Ok(true) => {} + // The host answered this report's round before it read the report (a round + // opened while stopped work drained, or found at a command timeout). + Ok(false) if state.ledger.report_answered() => { + dev_warn!(self.dev, "GPU: firmware report {:?} (slot {}) is for recovery {:?}, already answered\n", + error, slot, state.ledger.last()); + } + Ok(false) => { + dev_err!(self.dev, "GPU: firmware reported {:?} (slot {}) but did not enter recovery\n", + error, slot); + self.fail_all(state, ETIMEDOUT); + return; + } + Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } + } + } if let Err(err) = self.retire_render(state) { self.fail_all(state, err); return; } if let Err(e) = self.advance(state) { self.fail_all(state, e); return; } // The completion stamp is written before the firmware's post-processing advances the @@ -1064,10 +1506,14 @@ impl Runtime { } while !state.inflight.is_empty() { let front = &state.inflight[0]; - if state.retired_total >= front.ordinal { + let (ordinal, started, expected) = (front.ordinal, front.started, front.stamp.raw()); + if state.retired_total >= ordinal { if let Ok(done) = state.inflight.remove(0) { self.retire_slot(state, done.slot); - if let Some(err) = done.publication_error { + if let Some(err) = done.doomed { + self.fail_doomed(state, &done.packet, err); + self.keep(&mut state.kept_compute, done); + } else if let Some(err) = done.publication_error { done.packet.release_guard(); done.packet.finish(Err(err)); } else if done.last { @@ -1078,11 +1524,25 @@ impl Runtime { } continue; } - if front.started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { + if started.elapsed() > Delta::from_millis(COMMAND_TIMEOUT_MS) { dev_err!(self.dev, "GPU: compute command timed out: stamp={:#x} expected={:#x} submitted={} completed={}\n", - state.queue_stamp(), front.stamp.raw(), state.submitted, state.retired); - state.root.log_timeout(&self.dev); - state.fault.log(&self.dev); + state.queue_stamp(), expected, state.submitted, state.retired); + let phase = state.root.recovery_phase().unwrap_or(0); + if g14_v27_2_abi::command_timeout_action(phase) == g14_v27_2_abi::TimeoutAction::Recover { + // The firmware has a round open whose event was not seen. Recovery blames + // the command it names by stamp, which need not be this front one, and + // fails only that client; the others' work resumes after phase 0. + match self.recover(state, ETIMEDOUT, -1) { + Ok(true) => continue, + Ok(false) => {} + Err(err) => { + dev_err!(self.dev, "GPU: recovery failed ({:?}); failing all work\n", err); + self.fail_all(state, err); + return; + } + } + } + self.log_silent_hang(state, "compute"); self.fail_all(state, ETIMEDOUT); return; } @@ -1140,6 +1600,16 @@ impl Runtime { let Some(state) = Option::as_mut(&mut *guard) else { return Ok(()); }; if !self.healthy() { return Ok(()); } if !state.running() { + // No recovery round crosses a sleep: a round open now (the firmware stopped + // without anything of ours running) is answered by the service first. + let phase = state.root.recovery_phase().unwrap_or(0); + if phase != 0 { + dev_err!(self.dev, "GPU: sleep refused, firmware recovery phase {}\n", phase); + self.asleep.store(false, Ordering::Release); + self.pump(state); + self.notify.wake(); + return Err(EBUSY); + } break; } if remaining == 0 { @@ -1326,6 +1796,9 @@ impl Runtime { state.waiting_control = None; match restart { Ok(()) => { + // No round crosses a sleep (sleep_prepare refuses one), and the restarted + // firmware may count generations again from its start: forget old rounds. + state.ledger = g14_v27_2_abi::RecoveryLedger::default(); dev_info!(self.dev, "GPU firmware 27.2 back in {} us (commit idle={} {} us, pending={})\n", started.elapsed().as_micros_ceil(), commit.idle_ret, commit.idle_us, state.pending.len()); @@ -1477,12 +1950,13 @@ impl Backend { } }; let (queue, last) = root.queue(); - let checked = (|| -> Result<(u32, u32)> { + let checked = (|| -> Result<(u32, u32, KVec>)> { let (head, retired) = root.progress()?; if head != retired { return Err(EBUSY); } - Ok((head, root.capacity()?)) + let kept = KVec::with_capacity(g14_v27_2_abi::QUARANTINE_LIMIT, GFP_KERNEL)?; + Ok((head, root.capacity()?, kept)) })(); - let (head, capacity) = match checked { + let (head, capacity, kept) = match checked { Ok(v) => v, Err(e) => { halt_unowned(dev, peer, root, asc, true); @@ -1512,6 +1986,16 @@ impl Backend { accepting: true, submitted: 0, retired: 0, + firmware_error: None, + recoveries: 0, + recovery_window: 0, + recovery_count: 0, + ledger: g14_v27_2_abi::RecoveryLedger::default(), + events: [0; EVENT_HISTORY], + events_read: 0, + kept, + kept_compute: KVec::new(), + kept_renders: KVec::new(), hardware_unreachable: false, #[cfg(CONFIG_APPLE_SOC_SLEEP)] commit_stop: None, diff --git a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs index 7bc9e72337b9..96d4992845d6 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_abi.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_abi.rs @@ -71,6 +71,211 @@ impl GrowRequest { } } +/// Control-object recovery words (the recovery block G16 and M3 answer in their FirmwareData): +/// the u64 recovery generation, which growth requests also carry; 0x10 on, the recovery phase +/// (firmware 1 -> host 2 -> firmware 3 -> host 0); the snapshot of the work the firmware +/// stopped, {flags u32, target u32} pairs, at the same offset as in the M3 object, up to the +/// next recovery field. Seen on the J473: a stopped tiler {0x1f, its next stamp}, a stopped +/// compute {0x7, its next stamp}. +pub(crate) const RECOVERY_GENERATION: usize = 0x4bf0; +pub(crate) const RECOVERY_PHASE: usize = 0x4c00; +pub(crate) const RECOVERY_SNAPSHOT: usize = 0x4298; +const RECOVERY_SNAPSHOT_END: usize = 0x4b20; +pub(crate) const RECOVERY_SNAPSHOT_ENTRIES: usize = (RECOVERY_SNAPSHOT_END - RECOVERY_SNAPSHOT) / 8; + +/// A snapshot entry of a stopped tiler (valid + tiler bits): its TPC storage must be cleared +/// before the host answers phase 2, as G16 does. +pub(crate) const fn stopped_tiler(flags: u32) -> bool { + flags & 9 == 9 +} + +/// The tracked work a recovery snapshot names. A snapshot entry's target is the completion +/// stamp the stopped command would have written (J473: compute stamp 0x7900 written, entry +/// {0x7, 0x7a00}; tiler stamp 0x2156500 written, entry {0x1f, 0x2156600}). +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum Stopped { + /// The published render pair (either of its completion stamps). + Render, + /// The published compute command with this completion stamp. + Compute(u32), +} + +/// Attribution of one recovery round: every valid snapshot entry must name the same tracked, +/// unretired work, else the round is ambiguous and the caller fails all work (fail-stop). +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct Attribution { + work: Option, + ambiguous: bool, +} + +impl Attribution { + /// Adds a valid entry. `render` holds the published render pair's completion stamps; + /// `compute(stamp)` says whether an unretired compute command carries that stamp. + pub(crate) fn add(&mut self, flags: u32, target: u32, render: Option<[u32; 2]>, + compute: impl Fn(u32) -> bool) { + let as_render = render.is_some_and(|stamps| stamps.contains(&target)); + // A stopped tiler can only be the render pair. + let as_compute = !stopped_tiler(flags) && compute(target); + let work = match (as_render, as_compute) { + (true, false) => Stopped::Render, + (false, true) => Stopped::Compute(target), + _ => { + self.ambiguous = true; + return; + } + }; + match self.work { + None => self.work = Some(work), + Some(seen) if seen == work => {} + Some(_) => self.ambiguous = true, + } + } + + /// The stopped work, if the round named exactly one tracked command. + pub(crate) fn result(self) -> Option { + if self.ambiguous { None } else { self.work } + } +} + +/// The published compute command a snapshot target names: the one, among commands the queue +/// has not retired (`ordinal > retired`), whose completion stamp is `stamp`. `flights` yields +/// each published command's (completion stamp, ordinal) in publication order. A command that +/// already retired is never blamed, even before the host has taken it off its list. +pub(crate) fn stopped_compute( + flights: impl IntoIterator, + retired: u64, + stamp: u32, +) -> Option { + flights.into_iter().position(|(s, ordinal)| s == stamp && ordinal > retired) +} + +/// What the host does when a command ran past the driver's command timeout. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TimeoutAction { + /// The firmware has a recovery round open (phase 1): answer it, which blames the work it + /// stopped by stamp and fails only that client. + Recover, + /// No round open: the firmware reported nothing and stopped nothing that the host can + /// answer (a silent hang), or the handshake is in a state the host does not own. Failing + /// all work is the last resort. + FailAll, +} + +/// The driver's command timeout is only a backstop for the firmware's own recovery: it fails +/// every client only when the firmware has no round open. +pub(crate) const fn command_timeout_action(phase: u32) -> TimeoutAction { + match phase { + 1 => TimeoutAction::Recover, + _ => TimeoutAction::FailAll, + } +} + +/// A further recovery round while stopped work drains must carry a new generation; the same +/// generation again means the host misread the handshake. +pub(crate) const fn new_round(previous: Option, generation: u64) -> bool { + match previous { + None => true, + Some(p) => generation != p, + } +} + +/// Tells a fault or timeout report on the event ring that needs a recovery from one whose round +/// the host already answered. +/// +/// The firmware posts the report, then opens the round (phase 1). The host can answer a round +/// before it reads its report: a further round opened while stopped work drains, or a round +/// found at a command timeout. That report is then still in the ring, and the next service pass +/// reads it after the firmware is back at phase 0. It must be consumed, not answered with a +/// wait for a phase 1 that never comes, which would fail all work. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(crate) struct RecoveryLedger { + /// Service passes that read fault or timeout records. One pass counts once, so a fault and + /// a timeout posted for the same stop are one report. + reports: u64, + /// Rounds the host answered. + answered: u64, + /// Generation of the last round answered. + last: Option, +} + +impl RecoveryLedger { + /// A service pass read fault or timeout records. + pub(crate) fn report(&mut self) { + self.reports = self.reports.saturating_add(1); + } + + /// The host answered round `generation` (wrote phase 0). + pub(crate) fn answered(&mut self, generation: u64) { + self.answered = self.answered.saturating_add(1); + self.last = Some(generation); + } + + /// Generation of the last round answered: a round at phase 1 must carry another one + /// (`new_round`). + pub(crate) const fn last(&self) -> Option { + self.last + } + + /// With no new round open after a report: whether every report read so far has a round the + /// host already answered. Then the report is stale and is consumed. Otherwise the firmware + /// reported a stop without entering recovery. + pub(crate) const fn report_answered(&self) -> bool { + self.reports <= self.answered + } + + /// Reports read and rounds answered so far, for a log line. + pub(crate) const fn counts(&self) -> (u64, u64) { + (self.reports, self.answered) + } +} + +/// Packets with stopped work one boot may keep (`Runtime::keep`). A kept packet pins its VM, +/// and with it one user UAT context, and a render one also pins its scene. The limit is half +/// the user contexts, so innocent clients keep the rest. +pub(crate) const QUARANTINE_LIMIT: usize = 31; + +/// Whether one more packet with stopped work fits next to the `kept` ones. When it does not, +/// the caller fails all work, and everything published stays owned. +pub(crate) const fn quarantine_fits(kept: usize) -> bool { + kept < QUARANTINE_LIMIT +} + +/// Whether a packet's VM job guard may be released, so its mappings may change. That needs +/// none of its commands in a queue (`live`) and no stopped command of it kept (`kept`). The +/// firmware may still reach a stopped command's memory, so a kept packet stays owned for the +/// rest of the boot, whoever asks: retirement, `withdraw` or `fail_all`. +pub(crate) const fn guard_releasable(live: bool, kept: bool) -> bool { + !live && !kept +} + +/// Event ring record kinds. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum EventKind { + /// 0: the firmware stopped on a GPU fault and entered recovery. + Fault, + /// 4: the firmware timed out a command (slot at `TIMEOUT_SLOT_OFFSET`) and entered recovery. + Timeout, + /// 6: a buffer growth request. + Grow, + /// 7: the firmware rejected a channel record. + ChannelError, + /// Anything else (stage flags, statistics): nothing for the host to answer. + Notification, +} + +/// Byte offset of the slot a timeout record names. +pub(crate) const TIMEOUT_SLOT_OFFSET: usize = 0x0c; + +pub(crate) const fn event_kind(kind: u32) -> EventKind { + match kind { + 0 => EventKind::Fault, + 4 => EventKind::Timeout, + 6 => EventKind::Grow, + 7 => EventKind::ChannelError, + _ => EventKind::Notification, + } +} + /// Globals words of the firmware's per-pipe progress checks and compute watchdog, which the /// shared 0xe48-byte 27.2 Globals hold at the same offsets as the M3 and M4 27.2 runtimes write /// them (`m3_power_26`, `g16/fw/initdata`), with the 13.5 names: 0x24 relaxed compute kill @@ -293,6 +498,183 @@ mod tests { ); } + #[test] + fn recovery_events_are_decoded_and_others_stay_notifications() { + assert_eq!(event_kind(0), EventKind::Fault); + assert_eq!(event_kind(4), EventKind::Timeout); + assert_eq!(event_kind(6), EventKind::Grow); + assert_eq!(event_kind(7), EventKind::ChannelError); + for kind in [1, 2, 3, 5, 8, u32::MAX] { + assert_eq!(event_kind(kind), EventKind::Notification); + } + // The H1 record [4, 0, 0, 1, ...]: slot in the fourth word. + assert_eq!(TIMEOUT_SLOT_OFFSET / 4, 3); + } + + #[test] + fn recovery_block_geometry_matches_the_g16_order() { + // Phase 0x10 above the u64 generation, as in the G16/M3 FirmwareData. + assert_eq!(RECOVERY_PHASE - RECOVERY_GENERATION, 0x10); + assert_eq!(RECOVERY_SNAPSHOT_ENTRIES, 273); + assert!(RECOVERY_SNAPSHOT + 8 * RECOVERY_SNAPSHOT_ENTRIES <= RECOVERY_SNAPSHOT_END); + assert!(RECOVERY_SNAPSHOT_END <= RECOVERY_GENERATION); + } + + #[test] + fn only_a_valid_tiler_entry_clears_tiler_storage() { + // J473 snapshots: stopped tiler {0x1f, ..}, stopped compute {0x7, ..}. + assert!(stopped_tiler(0x1f)); + assert!(!stopped_tiler(0x7)); + assert!(!stopped_tiler(0x8)); + assert!(stopped_tiler(0x9 | (0x70 << 4))); + } + + #[test] + fn a_completed_front_entry_is_not_blamed_for_a_later_stop() { + // Host list: 0x7900 completed but not yet retired by the host, 0x7a00 stopped. + let unretired = [0x7900u32, 0x7a00, 0x7b00]; + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| unretired.contains(&s)); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + } + + #[test] + fn render_entries_name_the_published_pair() { + let pair = Some([0x2156600, 0x3156600]); + let mut a = Attribution::default(); + a.add(0x1f, 0x2156600, pair, |_| false); + a.add(0x7, 0x3156600, pair, |_| false); + assert_eq!(a.result(), Some(Stopped::Render)); + // A stopped tiler that matches no published pair is not pinned on compute. + let mut a = Attribution::default(); + a.add(0x1f, 0x7a00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + } + + #[test] + fn untracked_mixed_or_colliding_entries_fail_stop() { + let mut a = Attribution::default(); + assert_eq!(a.result(), None); + a.add(0x7, 0x7c00, None, |s| s == 0x7a00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, |s| s == 0x7a00 || s == 0x7b00); + a.add(0x7, 0x7b00, None, |s| s == 0x7a00 || s == 0x7b00); + assert_eq!(a.result(), None); + let mut a = Attribution::default(); + a.add(0x7, 0x3156600, Some([0x2156600, 0x3156600]), |s| s == 0x3156600); + assert_eq!(a.result(), None); + } + + #[test] + fn recovery_rounds_while_draining_need_a_new_generation() { + assert!(new_round(None, 1)); + assert!(new_round(Some(1), 2)); + assert!(!new_round(Some(2), 2)); + assert!(new_round(Some(u64::MAX), 0)); + } + + #[test] + fn a_report_read_before_its_round_is_answered_once() { + // Report, then its round: balanced, nothing left over. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + assert!(ledger.report_answered()); + assert_eq!(ledger.last(), Some(7)); + // A later report with no round open is a stop without recovery: not consumed. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_drain_round_is_consumed() { + // Round 7 from its report; round 8 opened while 7's work drained, answered before its + // report was read. Round 8's report then comes on the next pass, at phase 0. + let mut ledger = RecoveryLedger::default(); + ledger.report(); + ledger.answered(7); + ledger.answered(8); + ledger.report(); + assert!(ledger.report_answered()); + // Round 8 is answered: phase 1 with generation 8 again is not a new round. + assert!(!new_round(ledger.last(), 8)); + assert!(new_round(ledger.last(), 9)); + // Its credit is spent: a further report without a round is not stale. + ledger.report(); + assert!(!ledger.report_answered()); + } + + #[test] + fn a_stale_report_after_a_timeout_round_is_consumed() { + // The command timeout found phase 1 and answered round 3 before the event was read. + let mut ledger = RecoveryLedger::default(); + ledger.answered(3); + ledger.report(); + assert!(ledger.report_answered()); + } + + #[test] + fn a_timed_out_compute_is_blamed_by_stamp_and_spares_its_neighbours() { + // Compute list in publication order: (owner, completion stamp, ordinal). Client A's + // command completed and retired, but the host has not taken it off its list yet; B's + // command is the one the firmware timed out (event 4); C's command was published after + // it and waits behind it. + let flights = [('A', 0x7900u32, 1u64), ('B', 0x7a00, 2), ('C', 0x7b00, 3)]; + let retired = 1; + let unretired = |stamp| stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, stamp) + .is_some(); + // The J473 compute snapshot: one entry {0x7, next stamp of the stopped command}. + let mut a = Attribution::default(); + a.add(0x7, 0x7a00, None, unretired); + assert_eq!(a.result(), Some(Stopped::Compute(0x7a00))); + let stopped = stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7a00); + assert_eq!(stopped, Some(1)); + // blame() dooms every listed command of the stopped command's packet, and only those. + let guilty = flights[stopped.unwrap()].0; + let doomed: [bool; 3] = core::array::from_fn(|i| flights[i].0 == guilty); + assert_eq!(doomed, [false, true, false]); + // A target naming the retired front is not blamed on it. + assert_eq!(stopped_compute(flights.iter().map(|f| (f.1, f.2)), retired, 0x7900), None); + let mut a = Attribution::default(); + a.add(0x7, 0x7900, None, unretired); + assert_eq!(a.result(), None); + } + + #[test] + fn the_command_timeout_fails_all_only_without_a_recovery_round() { + assert_eq!(command_timeout_action(1), TimeoutAction::Recover); + // Silent hang: no round open. + assert_eq!(command_timeout_action(0), TimeoutAction::FailAll); + // The host's own phases or anything else: the handshake is not the firmware's to + // continue, so the host does not answer it from a timeout. + for phase in [2, 3, 4, u32::MAX] { + assert_eq!(command_timeout_action(phase), TimeoutAction::FailAll); + } + } + + #[test] + fn a_withdrawn_stopped_packet_keeps_its_guard() { + // The scheduler withdraws a packet whose stopped command left the queue: it is no + // longer live, but it is kept, so its guard stays. + assert!(!guard_releasable(false, true)); + // Still in a queue, kept or not. + assert!(!guard_releasable(true, false)); + assert!(!guard_releasable(true, true)); + // Retired innocent work. + assert!(guard_releasable(false, false)); + } + + #[test] + fn kept_packets_are_bounded_per_boot() { + assert!(quarantine_fits(0)); + assert!(quarantine_fits(QUARANTINE_LIMIT - 1)); + assert!(!quarantine_fits(QUARANTINE_LIMIT)); + assert!(!quarantine_fits(usize::MAX)); + // Innocent clients keep at least half of the 63 user UAT contexts. + assert!(2 * QUARANTINE_LIMIT <= 63); + } + #[test] fn progress_words_fit_the_globals_and_leave_power_words_alone() { let power = [0x58usize, 0x5a, 0x5c, 0x6e, 0x84, 0x88, 0x8c, 0x98]; diff --git a/drivers/gpu/drm/asahi/g14_v27_2_render.rs b/drivers/gpu/drm/asahi/g14_v27_2_render.rs index c389ab009a9b..dbe95b5bd203 100644 --- a/drivers/gpu/drm/asahi/g14_v27_2_render.rs +++ b/drivers/gpu/drm/asahi/g14_v27_2_render.rs @@ -83,6 +83,17 @@ impl Prep { pub(crate) fn slot(&self) -> u32 { self.scene.slot() } + + /// Clears the tiler's TPC storage after a firmware recovery stopped the tiler. + /// Zeroes the scene's TPC after a firmware recovery stopped its tiler. + /// + /// # Safety + /// + /// As [`crate::buffer::Scene::clear_tpc`]. + pub(crate) unsafe fn clear_tpc(&self) -> Result { + // SAFETY: forwarded from the caller. + unsafe { self.scene.clear_tpc(self.tile.tpc_size) } + } } fn to_cmdbuf(r: &UapiRenderCommand) -> kernel::uapi::drm_asahi_cmd_render { diff --git a/drivers/gpu/drm/asahi/gpu/v27_2.rs b/drivers/gpu/drm/asahi/gpu/v27_2.rs index ae793a221140..78046f9abb07 100644 --- a/drivers/gpu/drm/asahi/gpu/v27_2.rs +++ b/drivers/gpu/drm/asahi/gpu/v27_2.rs @@ -10,7 +10,7 @@ use super::*; use kernel::device; -use crate::g14_v27_2_abi::{self, GrowRequest, QueueError}; +use crate::g14_v27_2_abi::{self, EventKind, GrowRequest, QueueError}; use crate::g17::fw::m5::initdata as abi; use crate::hw::{RegisterBaseV27_2, RegisterV27_2}; use crate::m3::m3_init_26 as directory26; @@ -40,6 +40,11 @@ const STATISTICS_RING: usize = 16; /// Ring geometries: the trace ring has 512 records of 0x48 bytes, the others 256. const TRACE_RECORDS: u32 = 512; const RING_RECORDS: u32 = 256; +use crate::g14_v27_2_abi::{ + RECOVERY_GENERATION as CONTROL_RECOVERY_GENERATION, RECOVERY_PHASE as CONTROL_RECOVERY_PHASE, + RECOVERY_SNAPSHOT as CONTROL_RECOVERY_SNAPSHOT, +}; +pub(crate) use crate::g14_v27_2_abi::{stopped_tiler, RECOVERY_SNAPSHOT_ENTRIES}; /// Queue capacity at position block +0x50 (16 x the 0x50 channels). const QUEUE_CAPACITY: u32 = 0x500; /// Globals offsets of the 13.5 shared power tables (HwDataShared1 and HwDataShared2): the 27.2 @@ -604,6 +609,11 @@ impl CommandPool { } pub(crate) enum FirmwareEvent { + /// Kind 0: the firmware stopped on a GPU fault and halted for recovery. + Fault, + /// Kind 4: the firmware timed out a command (the slot it names at +0xc) and halted for + /// recovery. + Timeout { slot: i32 }, Grow(GrowRequest), ChannelError, Notification, @@ -695,6 +705,15 @@ impl RootV27_2 { (queue.info(self.render_states[dm]), queue.event.current_noncoherent()) } + /// Whether the render queue's retired position reached `target`, stamp or not: a command + /// the firmware stopped for recovery leaves the queue without writing its stamp. + pub(crate) fn render_retired(&self, dm: usize, target: u32) -> Result { + let queue = &self.render_queues[dm]; + crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); + crate::pgtable::poc_barrier(); + Ok(Self::word(&queue.positions, 0)? == target) + } + pub(crate) fn render_done(&self, dm: usize, target: u32, stamp: event::EventValue) -> Result { let queue = &self.render_queues[dm]; crate::pgtable::clean_invalidate_poc(queue.positions.as_slice().as_ptr(), 0x60); @@ -719,6 +738,27 @@ impl RootV27_2 { for (name, queue) in ["tiler", "fragment"].into_iter().zip(&self.render_queues) { Self::log_queue(dev, name, &queue.positions, &queue.queue, &queue.event); } + let (generation, phase) = (self.halt_count(), self.recovery_phase()); + let (snapshot, entries) = self.recovery_snapshot(); + dev_err!(dev, "GPU: recovery generation={:?} phase={:?} snapshot ({} entries) {:x?}\n", + generation, phase, entries, &snapshot[..entries.min(snapshot.len())]); + } + + /// The first valid recovery snapshot entries, {flags, target} in hex, and how many valid + /// entries there are in all (the first invalid entry ends the snapshot). Logging only. + pub(crate) fn recovery_snapshot(&self) -> ([(u32, u32); 4], usize) { + let mut first = [(0, 0); 4]; + let mut entries = 0; + for i in 0..RECOVERY_SNAPSHOT_ENTRIES { + match self.recovery_entry(i) { + Ok((flags, target)) if flags & 1 != 0 => { + if let Some(slot) = first.get_mut(entries) { *slot = (flags, target); } + entries += 1; + } + _ => break, + } + } + (first, entries) } pub(crate) fn render_kick(dm: usize) -> u64 { @@ -831,7 +871,8 @@ impl RootV27_2 { && job.event.current_noncoherent().raw() == job.expected_stamp) } - pub(crate) fn peek_event(&self) -> Result> { + /// The record at the head of the event ring: its cursor, its raw kind word and its decoding. + pub(crate) fn peek_event(&self) -> Result> { use crate::m3::m3_channel_format::RECEIVE_BYTES; let state = &self.channels[2 * EVENT_RING]; let ring = &self.channels[2 * EVENT_RING + 1]; @@ -844,14 +885,48 @@ impl RootV27_2 { crate::pgtable::clean_invalidate_poc(ring.as_slice()[at..].as_ptr(), RECEIVE_BYTES); crate::pgtable::poc_barrier(); let word = |offset| Self::word(ring, at + offset); - let event = match word(0)? { - 6 => FirmwareEvent::Grow(GrowRequest::decode([ + let kind = word(0)?; + let event = match g14_v27_2_abi::event_kind(kind) { + EventKind::Grow => FirmwareEvent::Grow(GrowRequest::decode([ word(4)?, word(8)?, word(0x0c)?, word(0x10)?, word(0x14)?, word(0x18)?, ])), - 7 => FirmwareEvent::ChannelError, - _ => FirmwareEvent::Notification, + EventKind::Fault => FirmwareEvent::Fault, + EventKind::Timeout => FirmwareEvent::Timeout { + slot: word(g14_v27_2_abi::TIMEOUT_SLOT_OFFSET)? as i32, + }, + EventKind::ChannelError => FirmwareEvent::ChannelError, + EventKind::Notification => FirmwareEvent::Notification, }; - Ok(Some((read, event))) + Ok(Some((read, kind, event))) + } + + /// Validates a byte range of the control object before it is sliced or cache-maintained. + fn control_range(control: &fw::types::GpuArray, from: usize, bytes: usize) -> Result { + match from.checked_add(bytes) { + Some(end) if end <= control.as_slice().len() && from % 4 == 0 => Ok(()), + _ => Err(EINVAL), + } + } + + /// Reads control words from `from` into `out`. + pub(crate) fn control_snapshot(&self, from: usize, out: &mut [u32]) -> Result { + Self::control_range(&self.control, from, out.len() * 4)?; + let at = self.control.as_slice()[from..].as_ptr(); + crate::pgtable::clean_invalidate_poc(at, out.len() * 4); + crate::pgtable::poc_barrier(); + for (i, w) in out.iter_mut().enumerate() { + *w = Self::word(&self.control, from + 4 * i)?; + } + Ok(()) + } + + /// Writes one control word and makes it visible to the firmware. + pub(crate) fn control_store(&self, at: usize, value: u32) -> Result { + Self::control_range(&self.control, at, 4)?; + self.control.shared_index(at)?.store(value, Ordering::Release); + crate::pgtable::clean_poc(self.control.as_slice()[at..].as_ptr(), 4); + crate::pgtable::poc_barrier(); + Ok(()) } pub(crate) fn consume_event(&self, cursor: u32) -> Result { @@ -862,8 +937,31 @@ impl RootV27_2 { Ok(()) } + /// The recovery phase. The firmware publishes 1 after it reported a fault or a command + /// timeout and stopped every queue; it runs nothing until the host's answers. + pub(crate) fn recovery_phase(&self) -> Result { + let mut word = [0u32]; + self.control_snapshot(CONTROL_RECOVERY_PHASE, &mut word)?; + Ok(word[0]) + } + + /// Answers a recovery phase (2 at phase 1, 0 at phase 3). + pub(crate) fn answer_recovery(&self, phase: u32) -> Result { + self.control_store(CONTROL_RECOVERY_PHASE, phase) + } + + /// Snapshot entry `i` of the stopped work: (flags, target). Bit 0 of flags marks a valid + /// entry; the first invalid one ends the snapshot. + pub(crate) fn recovery_entry(&self, i: usize) -> Result<(u32, u32)> { + if i >= RECOVERY_SNAPSHOT_ENTRIES { return Err(EINVAL); } + let mut words = [0u32; 2]; + self.control_snapshot(CONTROL_RECOVERY_SNAPSHOT + 8 * i, &mut words)?; + Ok((words[0], words[1])) + } + + /// The recovery generation (u64). Growth requests carry the value current when sent. pub(crate) fn halt_count(&self) -> Result { - const OFFSET: usize = 0x4bf0; + const OFFSET: usize = CONTROL_RECOVERY_GENERATION; crate::pgtable::clean_invalidate_poc(self.control.as_slice()[OFFSET..].as_ptr(), 8); crate::pgtable::poc_barrier(); Ok(u64::from(Self::word(&self.control, OFFSET)?) diff --git a/drivers/gpu/drm/asahi/object.rs b/drivers/gpu/drm/asahi/object.rs index d3cf86aa89a1..620014c6f63b 100644 --- a/drivers/gpu/drm/asahi/object.rs +++ b/drivers/gpu/drm/asahi/object.rs @@ -711,6 +711,24 @@ impl> GpuArray { // this word only in aligned 32-bit transactions while the ring is live. Ok(unsafe { core::sync::atomic::AtomicU32::from_ptr(ptr) }) } + + /// Zeroes the first `bytes` through the raw CPU mapping, without creating a Rust reference + /// to the payload, and cleans them to the point of coherency for the GPU. + /// + /// # Safety + /// + /// No CPU reference into the range may be live, and no device may access it during the call. + pub(crate) unsafe fn zero_prefix(&self, bytes: usize) -> Result { + if bytes > self.len { + return Err(ERANGE); + } + // SAFETY: `raw` is valid for `len` bytes (type invariant) and `bytes <= len`; the caller + // guarantees that nothing else accesses the range meanwhile. + unsafe { core::ptr::write_bytes(self.raw, 0, bytes) }; + crate::pgtable::clean_poc(self.raw.cast_const(), bytes); + crate::pgtable::poc_barrier(); + Ok(()) + } } impl> Deref for GpuArray { diff --git a/tools/asahi/g14-v27-2-abi-tests.rs b/tools/asahi/g14-v27-2-abi-tests.rs new file mode 100644 index 000000000000..04ae20680f7c --- /dev/null +++ b/tools/asahi/g14-v27-2-abi-tests.rs @@ -0,0 +1,5 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +//! Host tests of the production G14 firmware 27.2 queue, event and recovery records. +#![allow(dead_code)] +#[path = "../../drivers/gpu/drm/asahi/g14_v27_2_abi.rs"] +mod g14_v27_2_abi; diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a3c33382e0fb..687b9531250e 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -464,6 +464,8 @@ def mutations(flag, names, base, expect=KILL): # Production G17 decoder vectors also build directly with rustc --test. ASAHI_RUST += ['g17-telemetry-tests.rs', 'legacy-frequency-tests.rs'] ASAHI_RUST.append('m3-firmware-tests.rs') +# G14 firmware 27.2 queue, event and recovery records (its KUnit suite, run on the host). +ASAHI_RUST.append('g14-v27-2-abi-tests.rs') ASAHI_RUST.append('pmp-alloc-tests.rs') # Python that runs on the host but imports its neighbours, so it keeps the