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
2 changes: 2 additions & 0 deletions drivers/gpu/drm/asahi/g17/initdata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1074,6 +1074,8 @@ impl InitData {
// The word recovery_state() reads: the status block moves with the firmware build.
recovery: self.object(self.cluster)?.word(self.recovery_state_offset())?,
mailbox,
m5_credits: self.outer_credits.clone(),
m5_history: self.m5_history_view()?,
})
}

Expand Down
26 changes: 26 additions & 0 deletions drivers/gpu/drm/asahi/g17/initdata/m5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,32 @@ impl InitData {
ring(0), ring(1), ring(2), ring(3), page(canonical.start)]
}

/// Direct-port view of the M5 submission-history table (none off M5 or on common 26A428).
pub(super) fn m5_history_view(&self) -> Result<Option<crate::g17::port::M5HistoryView>> {
if !self.m5 || self.graph.is_common26() {
return Ok(None);
}
let private = self.object(self.cluster)?;
let base = self.graph.private.status_config;
let field = |offset| {
self.m5_status_config
.relocate(offset)
.map(|at| base + at)
.ok_or(EINVAL)
};
let history = field(m::M5_STATUS_CONFIG_HISTORY)?;
Ok(Some(crate::g17::port::M5HistoryView {
generation: private.word(field(m::M5_STATUS_CONFIG_HISTORY_GENERATION)?)?,
config: [
private.word(history)?,
private.word(history + 4)?,
private.word(history + 8)?,
private.word(history + 12)?,
],
slots: private.pointer(field(m::M5_STATUS_CONFIG_HISTORY_SLOTS)?, 256)?,
}))
}

/// Selects the power-policy layout of the M5 firmware build `build_m5` encodes for.
pub(in crate::g17) fn set_m5_policy_layouts(
&mut self,
Expand Down
127 changes: 123 additions & 4 deletions drivers/gpu/drm/asahi/g17/initdata/outer_credit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use kernel::{prelude::*, sync::Arc};

const PRIORITIES: usize = 4;

pub(super) struct Credits {
pub(crate) struct Credits {
reserved: [AtomicU32; PRIORITIES],
published: [AtomicU64; PRIORITIES],
consumers: [AtomicU64; PRIORITIES],
Expand Down Expand Up @@ -53,15 +53,19 @@ impl Credits {

pub(super) fn waiting(&self) -> bool { self.available.has_waiters() }

pub(super) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result<u32> {
pub(crate) fn is_scoped(&self) -> bool {
self.scoped.load(Ordering::Acquire)
}

pub(crate) fn capacity(&self, priority: u8, cursors: [u32; 3]) -> Result<u32> {
let pending = self.reserved.get(usize::from(priority)).ok_or(EINVAL)?
.load(Ordering::Acquire);
Ok(free(cursors)?.saturating_sub(pending))
}

/// Reserve under the sole publisher mutex. Off-lock cancellation may only
/// Reserve under the outer-ring lock. Off-lock cancellation may only
/// reduce reserved counts, so the sampled capacity is conservative.
pub(super) fn reserve(self: &Arc<Self>, priority: u8, count: u32,
pub(crate) fn reserve(self: &Arc<Self>, priority: u8, count: u32,
cursors: [u32; 3]) -> Result<OuterClaim>
{
if count == 0 || count >= WORK_RING_SLOTS { return Err(EINVAL); }
Expand All @@ -75,6 +79,20 @@ impl Credits {
Ok(OuterClaim { domain: self.clone(), priority: index, remaining: count })
}

/// Consumes one reserved slot for a direct M5 compute publication without touching
/// `published[]`, so an enclosing device-mutex `OuterScope` never debits a direct slot.
pub(crate) fn consume_direct(&self, claim: &mut OuterClaim) -> Result {
if !core::ptr::eq(self, &*claim.domain) {
return Err(EINVAL);
}
if claim.remaining == 0 {
return Err(EIO);
}
claim.remaining -= 1;
self.reserved[claim.priority].fetch_sub(1, Ordering::AcqRel);
Ok(())
}

pub(super) fn scope<'a>(self: &Arc<Self>, claim: &'a mut OuterClaim) -> Result<OuterScope<'a>> {
if !Arc::ptr_eq(self, &claim.domain) { return Err(EINVAL); }
if self.scoped.swap(true, Ordering::AcqRel) { return Err(EBUSY); }
Expand Down Expand Up @@ -128,3 +146,104 @@ impl Drop for OuterClaim {
}
}
}

#[kernel::macros::kunit_tests(asahi_g17_outer_credit)]
mod tests {
use super::*;

#[test]
fn direct_consumption_does_not_debit_outer_scope() {
let credits = Credits::new().unwrap();
let cursors = [0, 0, 0];
let full = free(cursors).unwrap();
let mut scoped_claim = credits.reserve(1, 2, cursors).unwrap();
let mut direct_claim = credits.reserve(1, 1, cursors).unwrap();
assert_eq!(credits.capacity(1, cursors).unwrap(), full - 3);

// Direct publish consumes only its own reserved slot and leaves published[] untouched.
assert!(!credits.is_scoped());
credits.consume_direct(&mut direct_claim).unwrap();
assert_eq!(direct_claim.remaining(), 0);
assert_eq!(credits.capacity(1, cursors).unwrap(), full - 2);
assert_eq!(credits.counter(1).unwrap().load(Ordering::Acquire), 0);

// An OuterScope taken afterward keeps its full 2 credits when nothing published via it.
{
let _scope = credits.scope(&mut scoped_claim).unwrap();
assert!(credits.is_scoped());
assert!(credits.reserve(1, 1, cursors).is_err());
}
assert!(!credits.is_scoped());
assert_eq!(scoped_claim.remaining(), 2);
drop(direct_claim);
drop(scoped_claim);
assert_eq!(credits.capacity(1, cursors).unwrap(), full);
}

#[test]
fn mixed_render_compute_wrap_and_generation_change_with_queued_claim() {
let credits = Credits::new().unwrap();
let n = WORK_RING_SLOTS;
// Producer sits two slots before wrap while both consumers lag 4 slots behind
// (free = WORK_RING_SLOTS - 5).
let mut consumer_a = n - 6;
let mut consumer_b = n - 6;
let mut producer = n - 2;
let cursors = [consumer_a, consumer_b, producer];
let initial_free = free(cursors).unwrap();
assert_eq!(initial_free, n - 5);

// Interleave a queued 2-slot render claim with 1-slot compute claims across ring wrap.
let mut queued_render = credits.reserve(2, 2, cursors).unwrap();
let mut compute_a = credits.reserve(2, 1, cursors).unwrap();
credits.consume_direct(&mut compute_a).unwrap();
producer = (producer + 1) % n; // n - 1
assert_eq!(
credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(),
initial_free - 3,
);

let mut compute_b = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap();
credits.consume_direct(&mut compute_b).unwrap();
producer = (producer + 1) % n; // 0 (wrapped!)
assert_eq!(producer, 0);

// Fill remaining capacity so exactly 1 free slot remains; 2-slot render must fail EBUSY
// while 1-slot compute still succeeds across the wrap boundary.
let rem = credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap();
let filler = credits.reserve(2, rem - 1, [consumer_a, consumer_b, producer]).unwrap();
assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 1);
assert_eq!(credits.reserve(2, 2, [consumer_a, consumer_b, producer]).err(), Some(EBUSY));
let mut edge_compute = credits.reserve(2, 1, [consumer_a, consumer_b, producer]).unwrap();
credits.consume_direct(&mut edge_compute).unwrap();
producer = (producer + 1) % n; // 1
assert_eq!(credits.capacity(2, [consumer_a, consumer_b, producer]).unwrap(), 0);
drop(filler);

// Consumers advance across the wrap boundary and report progress.
consumer_a = 1;
consumer_b = 1;
let wrapped = [consumer_a, consumer_b, producer];
assert!(credits.progressed(2, wrapped).unwrap());
assert_eq!(credits.capacity(2, wrapped).unwrap(), (n - 1) - 2);

// Simulate locked render / recovery entering OuterScope while a queued compute claim
// waits across a generation change: new reserves fail EBUSY and direct consumption never
// debits OuterScope's published counter; dropping the queued claim after the generation
// change releases its reserved credits cleanly.
let queued_compute = credits.reserve(2, 1, wrapped).unwrap();
{
let _scope = credits.scope(&mut queued_render).unwrap();
assert!(credits.is_scoped());
assert_eq!(credits.reserve(2, 1, wrapped).err(), Some(EBUSY));
credits.counter(2).unwrap().fetch_add(2, Ordering::AcqRel);
}
assert!(!credits.is_scoped());
assert_eq!(queued_render.remaining(), 0);
// Generation changed before queued_compute published: dropping it returns its credit.
assert_eq!(queued_compute.remaining(), 1);
drop(queued_compute);
drop(queued_render);
assert_eq!(credits.capacity(2, wrapped).unwrap(), n - 1);
}
}
152 changes: 149 additions & 3 deletions drivers/gpu/drm/asahi/g17/port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
//! through a preparation lease ([`super::Shared::port`]): shutdown and device loss join every
//! lease before they detach the session. Each piece below is atomic or has its own lock.
//!
//! Lock order: device mutex -> compute queue cell -> the locks of this port. The render
//! publication lock comes first among the port's locks: device mutex -> render publication
//! lock -> admission pool, QoS, mailbox. Its holder never takes the device mutex.
//! Lock order: device mutex -> compute queue cell -> the locks of this port. Among the port's
//! locks: render publication lock -> M5 outer-ring lock -> admission pool, QoS, mailbox. None
//! of their holders ever takes the device mutex.

use super::{
fw::{
Expand Down Expand Up @@ -73,6 +73,14 @@ impl RingView {
}
}

/// Raw pointers to the M5 submission-history table in firmware-shared memory.
#[derive(Clone, Copy)]
pub(super) struct M5HistoryView {
pub(super) generation: *const AtomicU32,
pub(super) config: [*const AtomicU32; 4],
pub(super) slots: *mut u8,
}

/// Raw views of the session's firmware-shared memory, fixed once the firmware is built.
pub(super) struct Views {
pub(super) compute: [RingView; PRIORITIES],
Expand All @@ -83,6 +91,8 @@ pub(super) struct Views {
pub(super) qos: *mut u8,
pub(super) recovery: *const AtomicU32,
pub(super) mailbox: *const super::Mailbox,
pub(super) m5_credits: Option<Arc<super::initdata::outer_credit::Credits>>,
pub(super) m5_history: Option<M5HistoryView>,
}

// SAFETY: The views only name memory and a mailbox owned by the firmware session, which outlives
Expand Down Expand Up @@ -114,6 +124,10 @@ pub(super) struct Port {
/// overlaps are ordered by publication order (see hazard.rs).
#[pin]
render: Mutex<()>,
/// Serializes M5 shared outer-ring writes, host-port gating transactions, and submission
/// history geometry/updates across direct compute publishers and device-mutex publishers.
#[pin]
m5_outer: Mutex<Option<(u32, u64, u64)>>,
/// The accepted recovery generation, mirrored for publishers without the device mutex.
generation: AtomicU64,
/// Device publication order shared by compute and render commands.
Expand Down Expand Up @@ -183,6 +197,7 @@ impl Port {
rx_applied <- new_spinlock!(None, "g17::Port::rx_applied"),
rx_state: AtomicU8::new(RX_STATE_UNSET),
render <- new_mutex!((), "g17::Port::render"),
m5_outer <- new_mutex!(None, "g17::Port::m5_outer"),
generation: AtomicU64::new(0),
publications: AtomicU64::new(0),
effort_full: AtomicBool::new(false),
Expand Down Expand Up @@ -313,6 +328,137 @@ impl Port {
self.render.lock()
}

/// Serializes M5 shared outer-ring and host-port updates with direct M5 compute publishers.
pub(super) fn m5_outer_lock(&self) -> MutexGuard<'_, Option<(u32, u64, u64)>> {
self.m5_outer.lock()
}

/// Clears the cached M5 submission-history geometry after firmware recovery restarts.
pub(super) fn reset_m5_history(&self) {
*self.m5_outer.lock() = None;
}

/// Reserves one slot on M5's shared outer ring for a direct compute publisher without
/// taking the device mutex. Returns EBUSY if a device-mutex OuterScope is active or full.
pub(super) fn reserve_m5_compute(&self, priority: u8) -> Result<super::initdata::OuterClaim> {
let views = self.views()?;
let credits = views.m5_credits.as_ref().ok_or(EINVAL)?;
let (_, ring) = self.ring(priority)?;
let _guard = self.m5_outer.lock();
if credits.is_scoped() {
return Err(EBUSY);
}
let cursors = ring.cursors()?;
credits.reserve(priority, 1, cursors)
}

/// Publishes one compute slot on M5's shared outer ring under the port's M5 outer lock
/// and consumes the caller's direct reservation.
pub(super) fn publish_m5_compute(
&self,
priority: u8,
claim: &mut super::initdata::OuterClaim,
record: &WorkSlot,
) -> Result<u32> {
if record.data_master != DataMaster::Compute as u32 {
return Err(EINVAL);
}
let views = self.views()?;
let credits = views.m5_credits.as_ref().ok_or(EINVAL)?;
let (_, ring) = self.ring(priority)?;
let _guard = self.m5_outer.lock();
let [first, second, producer] = ring.cursors()?;
let next = (producer + 1) % WORK_RING_SLOTS;
if next == first || next == second {
return Err(EIO);
}
// SAFETY: The ring view spans WORK_RING_SLOTS records, checked when the session built
// it; `producer` is in range. The reservation proves firmware does not own this slot and
// `m5_outer` excludes every other host writer on M5's shared outer ring.
unsafe {
core::ptr::copy_nonoverlapping(
core::ptr::from_ref(record).cast::<u8>(),
ring.slots
.add(producer as usize * core::mem::size_of::<WorkSlot>()),
core::mem::size_of::<WorkSlot>(),
);
}
fence(Ordering::SeqCst);
// SAFETY: As for `RingView::cursors`.
unsafe { (*ring.producer).store(next, Ordering::Relaxed) };
fence(Ordering::SeqCst);
credits.consume_direct(claim)?;
Ok(next)
}

/// Issues an M5 host-port compute submission with gating held off, serialized by `m5_outer`.
pub(super) fn submit_m5_work_held(
&self,
submission: &super::fw::m5::queue::HardwareSubmission,
) -> Result {
let regs = self.regs.as_ref().ok_or(ENODEV)?;
let _guard = self.m5_outer.lock();
regs.submit_m5_work_held(submission)
}

/// Counts `submissions` in the M5 submission-history table without taking the device mutex.
pub(super) fn note_m5_submission_history(&self, submissions: u8) -> Result {
let Some(history) = self.views()?.m5_history else {
return Ok(());
};
let mut geometry = self.m5_outer.lock();
for _ in 0..64 {
// SAFETY: Pointers name retained, bounds-checked firmware-shared words.
let generation = unsafe { (*history.generation).load(Ordering::Acquire) };
if generation & 1 != 0 {
core::hint::spin_loop();
continue;
}
let (period, count) = match *geometry {
Some((seen, period, count)) if seen == generation => (period, count),
_ => {
// SAFETY: As above; seqlock generation recheck validates consistency.
let c = unsafe {
[
(*history.config[0]).load(Ordering::Relaxed),
(*history.config[1]).load(Ordering::Relaxed),
(*history.config[2]).load(Ordering::Relaxed),
(*history.config[3]).load(Ordering::Relaxed),
]
};
fence(Ordering::Acquire);
// SAFETY: As above.
if generation != unsafe { (*history.generation).load(Ordering::Acquire) } {
core::hint::spin_loop();
continue;
}
let period = u64::from(c[0]) | (u64::from(c[1]) << 32);
let count = u64::from(c[2]) | (u64::from(c[3]) << 32);
*geometry = Some((generation, period, count));
(period, count)
}
};
if period == 0 || count == 0 || count > 256 {
return Err(EINVAL);
}
let (counter, frequency) = qos::clock();
let ticks = qos::time_from_host(counter, frequency)?;
let index = (ticks % period) / 25_000;
if index >= count {
return Err(ERANGE);
}
// SAFETY: `slots` spans 256 WC bytes and `index < count <= 256`.
unsafe {
let byte = history.slots.add(index as usize);
let value = core::ptr::read_volatile(byte).wrapping_add(submissions);
core::ptr::write_volatile(byte, value);
}
fence(Ordering::SeqCst);
return Ok(());
}
Err(EBUSY)
}

fn render_rings(&self, priority: u8) -> Result<(RingView, RingView)> {
let views = self.views()?;
let index = usize::from(priority);
Expand Down
Loading
Loading