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
76 changes: 76 additions & 0 deletions drivers/gpu/drm/asahi/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ use kernel::{

pub(crate) use crate::fw::channels::PipeType;

#[derive(Default)]
struct PowerTransitionBatch {
final_powered: Option<bool>,
}

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<T: RxChannelState, U: Copy + Default>
where
Expand Down Expand Up @@ -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<Arc<dyn gpu::GpuManager>>,
}

#[versions(AGX)]
Expand All @@ -618,16 +638,24 @@ 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<dyn gpu::GpuManager>) {
self.gpu = Some(gpu);
}

/// Returns the raw `ChannelRing` structure to pass to firmware.
pub(crate) fn to_raw(&self) -> raw::ChannelRing<ChannelState, RawStatsMsg::ver> {
self.ch.ring.to_raw()
}

/// 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 };
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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());
}
}
62 changes: 57 additions & 5 deletions drivers/gpu/drm/asahi/gpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,9 @@ pub(crate) struct GpuManager {
ids: SequenceIDs,
#[pin]
garbage_contexts: Mutex<KVec<workqueue::RetiredContext>>,
/// Queue structures of invalidated contexts that a running data master may still read.
#[pin]
powered_contexts: Mutex<KVec<KVec<workqueue::RetainedObject>>>,
#[pin]
fault_log: SpinLock<FaultLogState>,
}
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
}
}

Expand Down
13 changes: 8 additions & 5 deletions drivers/gpu/drm/asahi/workqueue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,20 +117,23 @@ pub(crate) type RetainedObject = KBox<dyn Any + Send>;
/// 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<GpuObject<fw::workqueue::GpuContextData>>,
/// 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<RetainedObject>,
}

/// 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<KBox<GpuObject<fw::workqueue::GpuContextData>>>,
Expand Down
Loading