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
4 changes: 4 additions & 0 deletions drivers/gpu/drm/asahi/g17/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,10 @@ impl Context {
None => self.execution.release(),
}
}
/// Non-zero identity shared by contexts in the same `exec_share`, or `0` when unshared.
pub(crate) fn execution_share_id(&self) -> u64 {
self.share.as_ref().map_or(0, |share| share.id())
}
/// `other` runs in this context's shared execution context.
pub(crate) fn shares_execution(&self, other: &Context) -> bool {
self.share.is_some() && core::ptr::eq(&*self.execution, &*other.execution)
Expand Down
15 changes: 15 additions & 0 deletions drivers/gpu/drm/asahi/g17/exec_share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,15 @@ use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use kernel::{prelude::*, sync::Arc};

struct Entry {
id: u64,
vm: u64,
execution: Arc<ExecutionContext>,
claims: Arc<AtomicU64>,
users: u32,
}

static NEXT_SHARE_ID: AtomicU64 = AtomicU64::new(1);

kernel::sync::global_lock! {
// SAFETY: Module initialization initializes this lock before registering adapters.
unsafe(uninit) static SHARES: Mutex<KVec<Entry>> = KVec::new();
Expand All @@ -39,13 +42,18 @@ pub(crate) unsafe fn init() {

/// One logical queue's use of a shared execution context.
pub(crate) struct Use {
id: u64,
vm: u64,
execution: Arc<ExecutionContext>,
claims: Arc<AtomicU64>,
done: AtomicBool,
}

impl Use {
/// Non-zero identity shared by every logical queue in this execution context.
pub(crate) fn id(&self) -> u64 {
self.id
}
/// The work-state index claims of the sharers.
pub(crate) fn claims(&self) -> &Arc<AtomicU64> {
&self.claims
Expand Down Expand Up @@ -93,6 +101,7 @@ pub(crate) fn join(vm: &Vm) -> Option<(Arc<ExecutionContext>, Use)> {
Some((
entry.execution.clone(),
Use {
id: entry.id,
vm: entry.vm,
execution: entry.execution.clone(),
claims: entry.claims.clone(),
Expand All @@ -104,9 +113,14 @@ pub(crate) fn join(vm: &Vm) -> Option<(Arc<ExecutionContext>, Use)> {
/// Offers a new context of `vm` for sharing.
pub(crate) fn offer(vm: &Vm, execution: &Arc<ExecutionContext>) -> Result<Use> {
let claims = Arc::new(AtomicU64::new(0), GFP_KERNEL)?;
let id = NEXT_SHARE_ID.fetch_add(1, Ordering::Relaxed);
if id == 0 {
return Err(EOVERFLOW);
}
let mut shares = SHARES.lock();
shares.push(
Entry {
id,
vm: vm.id(),
execution: execution.clone(),
claims: claims.clone(),
Expand All @@ -115,6 +129,7 @@ pub(crate) fn offer(vm: &Vm, execution: &Arc<ExecutionContext>) -> Result<Use> {
GFP_KERNEL,
)?;
Ok(Use {
id,
vm: vm.id(),
execution: execution.clone(),
claims,
Expand Down
212 changes: 212 additions & 0 deletions drivers/gpu/drm/asahi/g17/fence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,8 @@ pub(crate) struct PublishedSource {
pub(crate) epoch: u64,
pub(crate) published: u64,
pub(crate) dependency: super::fw::kick::KickDependency,
pub(crate) stamp_va: u64,
pub(crate) execution_share: u64,
pub(crate) readers: Arc<core::sync::atomic::AtomicU32>,
}

Expand Down Expand Up @@ -265,15 +267,27 @@ pub(crate) struct Submission {
/// Non-zero encoded recovery epoch (`epoch.wrapping_add(1)`) while `state.published` holds a
/// live `PublishedSource` snapshot, or `0` when unpublished.
published_epoch: AtomicU64,
/// Packed `(qid << 56) | published_seq` written before `published_epoch` (Release), so
/// `Backend::input_sources()` can collapse same-QID firmware wait barriers without locking
/// `state` while retaining earlier submissions for error checking in `Sources::check()`.
published_order: AtomicU64,
/// Set atomically when a firmware kick depends on this source so replay/retirement
/// observes consumers without scanning producer queues under the device mutex.
firmware_consumer: AtomicBool,
}

impl Submission {
const PUBLISHED_SEQ_MASK: u64 = (1u64 << 56) - 1;

fn encode_epoch(epoch: u64) -> u64 {
epoch.wrapping_add(1)
}
fn encode_order(qid: u8, published: u64) -> u64 {
if published == 0 || published > Self::PUBLISHED_SEQ_MASK {
return 0;
}
(u64::from(qid) << 56) | published
}
fn with_work(work: Option<Arc<WorkStateLease>>, firmware_source: bool) -> Result<Arc<Self>> {
let vm_status = work.as_ref().map(|work| work.status().clone());
Self::with_work_and_status(work, vm_status, firmware_source)
Expand All @@ -296,6 +310,7 @@ impl Submission {
firmware_source,
retired: AtomicBool::new(false),
published_epoch: AtomicU64::new(0),
published_order: AtomicU64::new(0),
firmware_consumer: AtomicBool::new(false),
}),
GFP_KERNEL,
Expand Down Expand Up @@ -323,12 +338,14 @@ impl Submission {
return;
}
let tag = Self::encode_epoch(source.epoch);
let order = Self::encode_order(source.dependency.qid(), source.published);
let mut state = self.state.lock();
if state.work.is_some()
&& self.error.load(Ordering::Acquire) == 0
&& !self.retired.load(Ordering::Acquire)
{
state.published = Some(source);
self.published_order.store(order, Ordering::Relaxed);
self.published_epoch.store(tag, Ordering::Release);
}
}
Expand All @@ -354,6 +371,39 @@ impl Submission {
let tag = Self::encode_epoch(epoch);
self.firmware_source && tag != 0 && self.published_epoch.load(Ordering::Acquire) == tag
}
/// Lock-free `(coalesce_key, published_seq)` for a healthy, currently published compute source.
/// Returns `None` when unpublished, retired, errored, or out of packing range.
pub(super) fn published_order_key(&self) -> Option<(u64, u64)> {
if !self.firmware_source {
return None;
}
let epoch_tag = self.published_epoch.load(Ordering::Acquire);
if epoch_tag == 0 || epoch_tag > Self::PUBLISHED_SEQ_MASK {
return None;
}
if self.error.load(Ordering::Acquire) != 0 || self.retired.load(Ordering::Acquire) {
return None;
}
let order = self.published_order.load(Ordering::Relaxed);
core::sync::atomic::fence(Ordering::Acquire);
if self.published_epoch.load(Ordering::Relaxed) != epoch_tag {
return None;
}
let seq = order & Self::PUBLISHED_SEQ_MASK;
if seq == 0 {
return None;
}
let qid = order >> 56;
Some(((epoch_tag << 8) | qid, seq))
}
pub(super) fn published_order_key_for(&self, epoch: u64) -> Option<(u64, u64)> {
let tag = Self::encode_epoch(epoch);
if tag == 0 || tag > Self::PUBLISHED_SEQ_MASK {
return None;
}
let (key, seq) = self.published_order_key()?;
((key >> 8) == tag).then_some((key, seq))
}
pub(super) fn note_firmware_consumer(&self) {
self.firmware_consumer.store(true, Ordering::Release);
}
Expand Down Expand Up @@ -661,6 +711,168 @@ mod tests {
assert_eq!(source.owners.load(Ordering::Acquire), 0);
}

#[test]
fn published_export_coalesce_key_tracks_epoch_qid_and_invalidation() {
use crate::g17::fw::kick::{KickDependency, KickTimestamp};
use crate::g17::sync_input::{coalesce_source, Coalesce, Source, Sources};

let contexts = contexts();
let a = aggregate(&contexts);
let b = aggregate(&contexts);
let c = aggregate(&contexts);
let readers = Arc::new(AtomicU32::new(0), GFP_KERNEL).unwrap();
let dep_q5_1 = KickDependency::new(5, KickTimestamp::new(10).unwrap()).unwrap();
let dep_q5_2 = KickDependency::new(5, KickTimestamp::new(11).unwrap()).unwrap();
let dep_q6_1 = KickDependency::new(6, KickTimestamp::new(12).unwrap()).unwrap();

// Unpublished submissions expose no coalesce key.
assert_eq!(a.source().published_order_key(), None);

// Simulate published snapshots (set_published requires state.work.is_some() in production;
// test the atomic publication contract directly here without a GPU Context).
let publish_direct = |sub: &Submission, epoch: u64, seq: u64, dep: KickDependency| {
let tag = Submission::encode_epoch(epoch);
let order = Submission::encode_order(dep.qid(), seq);
sub.state.lock().published = Some(PublishedSource {
epoch,
published: seq,
dependency: dep,
stamp_va: 0x1000,
execution_share: 1,
readers: readers.clone(),
});
sub.published_order.store(order, Ordering::Relaxed);
sub.published_epoch.store(tag, Ordering::Release);
};

publish_direct(a.source(), 7, 100, dep_q5_1);
publish_direct(b.source(), 7, 101, dep_q5_2);
publish_direct(c.source(), 7, 102, dep_q6_1);

let (ka, sa) = a.source().published_order_key().unwrap();
let (kb, sb) = b.source().published_order_key().unwrap();
let (kc, sc) = c.source().published_order_key().unwrap();
assert_eq!(ka, kb);
assert!(sb > sa);
assert_ne!(ka, kc);
assert_eq!(a.source().published_order_key_for(7), Some((ka, sa)));
assert_eq!(a.source().published_order_key_for(8), None);

// Distinct-context ExportFences are all preserved by collect_coalesced() so
// Backend::input_sources() retains error dependencies for every earlier export.
let merged = super::super::sync_input::merge(&[a.fence(), b.fence(), c.fence()]).unwrap();
let leaves = super::super::sync_input::collect_coalesced(&merged).unwrap();
assert_eq!(leaves.len(), 3);

// Coalescing two same-(epoch, qid) exports keeps only the newest wait source while
// retaining the earlier submission in coalesced_errors (both arrival orders).
let build_sources = |order: [&Aggregate; 3]| -> Arc<Sources> {
let mut wait_sources: KVec<Source> = KVec::new();
let mut keys: KVec<Option<(u64, u64)>> = KVec::new();
let mut coalesced_errors: KVec<Arc<Submission>> = KVec::new();
for agg in order {
let sub = agg.source().clone();
let key = sub.published_order_key_for(7);
let _ = coalesce_source(
&mut wait_sources,
&mut keys,
&mut coalesced_errors,
sub,
key,
)
.unwrap();
}
assert_eq!(wait_sources.len(), 2);
assert!(wait_sources.iter().any(|s| Arc::ptr_eq(&s.submission, b.source())));
assert!(wait_sources.iter().any(|s| Arc::ptr_eq(&s.submission, c.source())));
assert_eq!(coalesced_errors.len(), 1);
assert!(Arc::ptr_eq(&coalesced_errors[0], a.source()));
Sources::new(KVec::new(), wait_sources, coalesced_errors, KVec::new()).unwrap()
};
let consumer_fwd = build_sources([&a, &b, &c]);
let consumer_rev = build_sources([&b, &a, &c]);
assert!(consumer_fwd.check().is_ok());
assert!(consumer_rev.check().is_ok());

// Duplicate leaf after coalescing is recognized cleanly without duplicating error entries.
{
let mut wait_sources: KVec<Source> = KVec::new();
let mut keys: KVec<Option<(u64, u64)>> = KVec::new();
let mut coalesced_errors: KVec<Arc<Submission>> = KVec::new();
assert!(matches!(
coalesce_source(
&mut wait_sources,
&mut keys,
&mut coalesced_errors,
b.source().clone(),
Some((kb, sb)),
),
Ok(Coalesce::Insert)
));
assert!(matches!(
coalesce_source(
&mut wait_sources,
&mut keys,
&mut coalesced_errors,
a.source().clone(),
Some((ka, sa)),
),
Ok(Coalesce::Coalesced)
));
assert!(matches!(
coalesce_source(
&mut wait_sources,
&mut keys,
&mut coalesced_errors,
a.source().clone(),
Some((ka, sa)),
),
Ok(Coalesce::Duplicate)
));
assert_eq!(coalesced_errors.len(), 1);
}

// Late error after collection: retained later export `b` (and `c`) complete cleanly,
// while earlier coalesced export `a` fails later. Consumer check MUST observe the error.
b.finish_enqueue(Ok(()));
c.finish_enqueue(Ok(()));
assert_eq!(b.source().source_status(), Ok(true));
assert_eq!(c.source().source_status(), Ok(true));
assert!(consumer_fwd.check().is_ok());
assert!(consumer_rev.check().is_ok());

a.finish_enqueue(Err(EIO));
assert_eq!(a.source().published_order_key(), None);
assert_eq!(
consumer_fwd.check(),
Err(crate::g17::dependency::PRODUCER_FAILED)
);
assert_eq!(
consumer_rev.check(),
Err(crate::g17::dependency::PRODUCER_FAILED)
);

b.source().clear_published();
assert_eq!(b.source().published_order_key(), None);
}

#[test]
fn lockless_fence_status_tracks_unsignaled_success_and_error() {
let contexts = contexts();
let ok_fence = independent(&contexts).unwrap();
let ok_handle = Fence::from_fence(&ok_fence);
assert_eq!(super::super::job::fence_status(&ok_handle), 0);
ok_fence.signal();
assert_eq!(super::super::job::fence_status(&ok_handle), 1);

let err_fence = independent(&contexts).unwrap();
let err_handle = Fence::from_fence(&err_fence);
assert_eq!(super::super::job::fence_status(&err_handle), 0);
err_fence.set_error(EIO);
err_fence.signal();
assert_eq!(super::super::job::fence_status(&err_handle), EIO.to_errno());
}

#[cfg(CONFIG_KUNIT = "y")]
fn timeline_item(syncobj: kernel::drm::syncobj::SyncObj, point: u64) -> Result<SyncItem> {
Ok(SyncItem {
Expand Down
3 changes: 1 addition & 2 deletions drivers/gpu/drm/asahi/g17/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,7 @@ impl Packet {
}

pub(crate) fn fence_status(fence: &Fence) -> i32 {
// SAFETY: The owned fence keeps the raw DMA fence alive for this read.
unsafe { bindings::dma_fence_get_status(fence.raw()) }
super::sync_input::fence_status(fence)
}

fn check_status(fence: &Fence) -> Result {
Expand Down
2 changes: 2 additions & 0 deletions drivers/gpu/drm/asahi/g17/queue/compute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3389,6 +3389,8 @@ impl Queue {
epoch,
published,
dependency,
stamp_va: self.graph.support.gpu_va() + STAMP as u64,
execution_share: packet.context.execution_share_id(),
readers: self.source_readers.clone(),
},
);
Expand Down
12 changes: 6 additions & 6 deletions drivers/gpu/drm/asahi/g17/queue/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -406,19 +406,19 @@ impl<B: Backend> Queue<B> {
// either order and must each consume an input's error status before running.
for sync in inputs {
if let Some(fence) = &sync.fence {
if sources
.as_ref()
.is_some_and(|sources| sources.contains_input(fence))
{
continue;
}
// An input that already signalled without error orders nothing and has no status
// left to consume (like a completed frontier producer above). Keeping it would
// send the render through the scheduler thread instead of inline publication:
// most compositor and client renders carry such already-signalled buffer fences.
if job::fence_status(fence) > 0 {
continue;
}
if sources
.as_ref()
.is_some_and(|sources| sources.contains_input(fence))
{
continue;
}
dependencies.push(fence.clone(), GFP_KERNEL)?;
checked_inputs.push(fence.clone(), GFP_KERNEL)?;
}
Expand Down
Loading
Loading