From be4ddeb4ffa95dd8898fdd866adca606264e21d1 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Sat, 21 Nov 2026 02:26:34 +1100 Subject: [PATCH] drm/asahi: free retired queue structures after firmware poweroff DestroyContext completion removes a context from firmware lookup, but it does not mean the running data masters have stopped reading the queue structures of that context. On G13S (M1 Pro) a load that creates and destroys rendering contexts quickly crashes the GPU firmware in about one of five runs: the firmware follows queue structures that were freed, and reused, right after the invalidation was acknowledged. Free the context data right after the acknowledged invalidation, as before, but keep the queue structures of each invalidated context until the firmware reports the next PowerOff on the statistics channel, and free them then. The statistics ring is drained under its lock before a context is queued, so a PowerOff that was already pending before the invalidation cannot release it, and only the last power transition of a batch counts, so an old PowerOff followed by PowerOn releases nothing. Only the queue structures are held. Holding the context data as well keeps its TVB buffer alive, and under heavy context churn the firmware powers off too rarely for that: the M1 Pro ran out of GPU memory within seconds. If the invalidation times out, or the bookkeeping allocation fails, leak the objects instead of freeing memory the firmware may still use. Link: https://github.com/aurora-silicon/linux/issues/2506 Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/channel.rs | 76 ++++++++++++++++++++++++++++++ drivers/gpu/drm/asahi/gpu.rs | 62 ++++++++++++++++++++++-- drivers/gpu/drm/asahi/workqueue.rs | 13 +++-- 3 files changed, 141 insertions(+), 10 deletions(-) diff --git a/drivers/gpu/drm/asahi/channel.rs b/drivers/gpu/drm/asahi/channel.rs index dbb84f288087b..1a68469911a19 100644 --- a/drivers/gpu/drm/asahi/channel.rs +++ b/drivers/gpu/drm/asahi/channel.rs @@ -45,6 +45,25 @@ use kernel::{ pub(crate) use crate::fw::channels::PipeType; +#[derive(Default)] +struct PowerTransitionBatch { + final_powered: Option, +} + +impl PowerTransitionBatch { + fn power_on(&mut self) { + self.final_powered = Some(true); + } + + fn power_off(&mut self) { + self.final_powered = Some(false); + } + + fn ends_powered_off(&self) -> bool { + self.final_powered == Some(false) + } +} + /// A receive (FW->driver) channel. pub(crate) struct RxChannel where @@ -600,6 +619,7 @@ pub(crate) struct StatsChannel { /// (`HwConfig::base_clock_hz`, 24 MHz on every supported SoC), not /// nanoseconds. busy: crate::stats_busy::BusyIntegrator, + gpu: Option>, } #[versions(AGX)] @@ -618,9 +638,15 @@ impl StatsChannel::ver { snap, raw, busy: crate::stats_busy::BusyIntegrator::new(ts_hz), + gpu: None, }) } + /// Registers the manager that owns firmware objects retired by power events. + pub(crate) fn set_manager(&mut self, gpu: Arc) { + self.gpu = Some(gpu); + } + /// Returns the raw `ChannelRing` structure to pass to firmware. pub(crate) fn to_raw(&self) -> raw::ChannelRing { self.ch.ring.to_raw() @@ -628,6 +654,8 @@ impl StatsChannel::ver { /// Polls for new statistics messages on this ring. pub(crate) fn poll(&mut self) { + let mut power = PowerTransitionBatch::default(); + while let Some(msg) = self.ch.get(0) { // SAFETY: The raw view is always valid for all bit patterns. let tag = unsafe { msg.raw.0 }; @@ -638,6 +666,13 @@ impl StatsChannel::ver { let msg = unsafe { msg.msg }; cls_dev_dbg!(StatsCh, self.dev, "Stats: {:?}\n", msg); self.record_raw(&msg); + + match &msg { + StatsMsg::ver::PowerOn { .. } => power.power_on(), + StatsMsg::ver::PowerOff { .. } => power.power_off(), + _ => {} + } + if module_parameters::stats_export.value() != 0 { // Retain the latest values for /sys/class/drm/card*/ // device/agx_stats. Read-only with respect to @@ -702,6 +737,19 @@ impl StatsChannel::ver { } } } + + // Only the final transition in this batch is a release boundary. In + // particular, an old PowerOff followed by PowerOn must not release + // objects retired while the GPU is live again. + if power.ends_powered_off() { + match self.gpu.as_ref() { + Some(gpu) => gpu.fw_power_off(), + None => dev_crit!( + self.dev.as_ref(), + "StatsChannel: No GPU manager available!\n" + ), + } + } } /// Record one statistics message in the raw per-device snapshot. @@ -780,3 +828,31 @@ impl StatsChannel::ver { } } } + +#[kunit_tests(asahi_agx_context_release)] +mod tests { + use super::PowerTransitionBatch; + + #[test] + fn power_off_is_release_boundary() { + let mut batch = PowerTransitionBatch::default(); + batch.power_off(); + assert!(batch.ends_powered_off()); + } + + #[test] + fn later_power_on_cancels_release() { + let mut batch = PowerTransitionBatch::default(); + batch.power_off(); + batch.power_on(); + assert!(!batch.ends_powered_off()); + } + + #[test] + fn final_power_off_wins() { + let mut batch = PowerTransitionBatch::default(); + batch.power_on(); + batch.power_off(); + assert!(batch.ends_powered_off()); + } +} diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 588f95f087a49..d462ecbd1a7ae 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -296,6 +296,9 @@ pub(crate) struct GpuManager { ids: SequenceIDs, #[pin] garbage_contexts: Mutex>, + /// Queue structures of invalidated contexts that a running data master may still read. + #[pin] + powered_contexts: Mutex>>, #[pin] fault_log: SpinLock, } @@ -507,6 +510,9 @@ pub(crate) trait GpuManager: Send + Sync { fn get_dyncfg(&self) -> &hw::DynConfig; /// Register an unused context, with the objects it retains, for invalidation. fn free_context(&self, ctx: workqueue::RetiredContext); + /// Release the queue structures of invalidated contexts after firmware reports that all data + /// masters are powered off. + fn fw_power_off(&self); } /// Private generic trait for functions that don't need to escape this module. @@ -842,6 +848,7 @@ impl GpuManager::ver { { let mut rxc = mgr.rx_channels.lock(); rxc.event.set_manager(mgr.clone()); + rxc.stats.set_manager(mgr.clone()); } Ok(mgr) @@ -1043,6 +1050,7 @@ impl GpuManager::ver { buffer_mgr, ids: Default::default(), garbage_contexts <- new_mutex!(KVec::new(), "garbage_contexts"), + powered_contexts <- new_mutex!(KVec::new(), "powered_contexts"), fault_log <- new_spinlock!(FaultLogState::default(), "fault_log"), }), GFP_KERNEL, @@ -1714,10 +1722,38 @@ impl GpuManager for GpuManager::ver { if debug_enabled(DebugFlags::OopsOnGpuCrash) { panic!("GPU firmware timed out"); } + // The invalidation did not complete, so firmware may still use every object in + // the context. Leaking it is the only safe recovery from this fatal condition. + core::mem::forget(ctx); + continue; + } + + // Only the queue structures can still be read after the invalidation. The context data, + // with the TVB buffer it holds, goes now, so a retired context costs only its queues. + let workqueue::RetiredContext { data, retained } = ctx; + core::mem::drop(data); + + // Device-control completion and statistics use separate receive rings. Drain the + // latter under its lock before publishing this context, so a PowerOff that was + // already pending before invalidation cannot release it. A concurrent later + // PowerOff cannot be handled until after the context has been queued here. + let mut rxc = self.rx_channels.lock(); + rxc.stats.poll(); + + let mut powered = self.powered_contexts.lock(); + if powered.reserve(1, GFP_KERNEL).is_err() { + dev_err!( + self.dev.as_ref(), + "Failed to reserve invalidated context, leaking it for safety.\n" + ); + core::mem::forget(retained); + continue; + } + // This cannot fail after the successful reservation. Preserve the object even if + // the vector implementation ever violates that contract. + if let Err(err) = powered.push_within_capacity(retained) { + core::mem::forget(err.0); } - // The firmware no longer knows the context's queues, so their structures may go now, - // ahead of the context data they point to. - core::mem::drop(ctx.retained); } let mut guard = self.alloc.lock(); @@ -2019,12 +2055,28 @@ impl GpuManager for GpuManager::ver { fn free_context(&self, ctx: workqueue::RetiredContext) { let mut garbage = self.garbage_contexts.lock(); - if garbage.push(ctx, GFP_KERNEL).is_err() { + if garbage.reserve(1, GFP_KERNEL).is_err() { dev_err!( self.dev.as_ref(), - "Failed to reserve space for freed context, deadlock possible.\n" + "Failed to reserve freed context, leaking it for safety.\n" ); + core::mem::forget(ctx); + return; } + if let Err(err) = garbage.push_within_capacity(ctx) { + core::mem::forget(err.0); + } + } + + fn fw_power_off(&self) { + let mut released = KVec::new(); + core::mem::swap(&mut *self.powered_contexts.lock(), &mut released); + mod_dev_dbg!( + self.dev, + "Releasing {} invalidated GPU contexts after firmware PowerOff\n", + released.len() + ); + core::mem::drop(released); } } diff --git a/drivers/gpu/drm/asahi/workqueue.rs b/drivers/gpu/drm/asahi/workqueue.rs index 81262edc87e2a..2e84269e7ec62 100644 --- a/drivers/gpu/drm/asahi/workqueue.rs +++ b/drivers/gpu/drm/asahi/workqueue.rs @@ -117,20 +117,23 @@ pub(crate) type RetainedObject = KBox; /// queues of the owning queue. const CONTEXT_RETAINED_OBJECTS: usize = 4; -/// A dropped GPU context waiting for the firmware to invalidate it. +/// A dropped GPU context waiting for invalidation. Its queue structures are then kept until the +/// following firmware power-off boundary. pub(crate) struct RetiredContext { /// The context data named in the invalidation request. pub(crate) data: KBox>, /// Firmware structures of the context's queues. They must not be freed, and so must not be - /// reused, until the invalidation has completed. + /// reused, until firmware has powered off after the invalidation completed. pub(crate) retained: KVec, } /// A GPU context tracking structure, which must be explicitly invalidated when dropped. /// -/// The firmware learns about the work queues of a context as they are run, and only forgets them -/// when the context is invalidated. Their firmware structures are therefore handed to the context -/// when their owner drops them, and freed after the invalidation. +/// The firmware learns about the work queues of a context as they are run. Invalidation removes the +/// context from firmware lookup, but data masters may retain queue references until they power off. +/// The queue structures are therefore handed to the context when their owner drops them, and freed +/// only after invalidation and a following firmware power-off report. The context data itself is +/// freed right after the invalidation. pub(crate) struct GpuContext { dev: driver::AsahiDevice, data: Option>>,