Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
290 changes: 249 additions & 41 deletions drivers/gpu/drm/asahi/g17/completion/publication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,75 @@

use super::Output;
use crate::g17::{dependency::PRODUCER_FAILED, status::VmStatus};
use core::sync::atomic::{AtomicBool, Ordering};
use core::{
cell::UnsafeCell,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
};
use kernel::{new_mutex, prelude::*, sync::{Arc, Mutex}};

type Links = Option<KBox<Link>>;
type Links = Option<NonNull<Link>>;

/// One wait of a successor on a predecessor. All of a successor's links live in one
/// [`LinkBlock`] that its publication owns; a predecessor's list only points into it.
struct Link {
target: Arc<Publication>,
/// The successor, held from setup until the link has been consumed, so that the block the
/// link lives in stays allocated while a list or a traversal can reach it.
target: Option<Arc<Publication>>,
/// The predecessor to install in, held only between setup and activation.
predecessor: Option<Arc<Publication>>,
result: Result,
next: Links,
// Reuse an already-consumed link as a traversal frame instead of recursing
// or allocating when publication unlocks a long chain of ready successors.
resume: Links,
}

/// Releases a consumed link's hold on its successor.
///
/// # Safety
///
/// `link` must be reachable from no list and no traversal any more. It may be freed on return.
unsafe fn release(link: NonNull<Link>) {
// SAFETY: Per the contract the caller is its only user, and the held successor keeps its
// block allocated until this drop.
drop(unsafe { (*link.as_ptr()).target.take() });
}

/// The flags of a successor's link block: per-job state sized by the commands it covers, so
/// charged to the client like the job's fence vectors.
const LINK_FLAGS: kernel::alloc::Flags = GFP_KERNEL_ACCOUNT;

#[cfg(CONFIG_KUNIT = "y")]
static BLOCKS: [core::sync::atomic::AtomicUsize; 2] =
[core::sync::atomic::AtomicUsize::new(0), core::sync::atomic::AtomicUsize::new(0)];

/// Counts link blocks allocated (`false`) and freed (`true`) for KUnit.
#[cfg(CONFIG_KUNIT = "y")]
fn note_block(freed: bool) {
BLOCKS[usize::from(freed)].fetch_add(1, Ordering::Relaxed);
}
#[cfg(not(CONFIG_KUNIT = "y"))]
fn note_block(_freed: bool) {}

/// One successor's links, in a single allocation.
struct LinkBlock(KVVec<UnsafeCell<Link>>);

// SAFETY: A link is reached through exactly one predecessor list, under that predecessor's
// lock, or through the one traversal that detached it, so no two threads use it at once.
unsafe impl Send for LinkBlock {}

impl Drop for LinkBlock {
fn drop(&mut self) {
if self.0.capacity() != 0 {
// A large block may come from vmalloc, and vfree() may sleep: every place that can
// drop the last reference to a publication must be able to.
kernel::task::might_sleep();
note_block(true);
}
}
}

struct State {
remaining: usize,
result: Option<Result<[u64; 4]>>,
Expand All @@ -33,6 +88,26 @@ struct State {
// still has no result of its own; successors have already been released.
upstream_released: bool,
successors: Links,
/// This publication's own links, owned from activation on.
block: Option<LinkBlock>,
}

// SAFETY: See `LinkBlock`: the links in `successors` are used only under this lock or by the
// traversal that took them out of it.
unsafe impl Send for State {}

impl Drop for State {
/// A publication dropped before it published releases the links still waiting on it.
fn drop(&mut self) {
let mut next = self.successors.take();
while let Some(link) = next {
// SAFETY: The list owned these links; each is released after its successor is read.
unsafe {
next = (*link.as_ptr()).next.take();
release(link);
}
}
}
}

impl State {
Expand Down Expand Up @@ -83,6 +158,7 @@ impl Publication {
published: None,
upstream_released: false,
successors: None,
block: None,
}, "G17 host timestamp publication"),
}),
GFP_KERNEL,
Expand Down Expand Up @@ -129,7 +205,7 @@ impl Publication {
}
self.output.publish(result, &self.status);
let result = result.map(|_| ());
let mut links = {
let links = {
let mut state = self.state.lock();
// A late link is acknowledged only after timestamp writes, the public
// fence and aggregate membership have all been published off this lock.
Expand All @@ -139,10 +215,13 @@ impl Publication {
}
state.successors.take()
};
let mut next = links.as_mut();
let mut next = links;
while let Some(link) = next {
link.result = result;
next = link.next.as_mut();
// SAFETY: These links were taken out of the list and belong to this caller.
unsafe {
(*link.as_ptr()).result = result;
next = (*link.as_ptr()).next;
}
}
links
}
Expand Down Expand Up @@ -175,91 +254,140 @@ impl Publication {
if let Some(result) = ready {
return self.publish(result);
}
let mut links = settled;
let mut next = links.as_mut();
let links = settled;
let mut next = links;
while let Some(link) = next {
link.result = Ok(());
next = link.next.as_mut();
// SAFETY: These links were taken out of the list and belong to this caller.
unsafe {
(*link.as_ptr()).result = Ok(());
next = (*link.as_ptr()).next;
}
}
links
}

fn add_successor(&self, mut link: KBox<Link>) {
/// # Safety
///
/// `link` must be a set-up link that no list or traversal reaches yet.
unsafe fn add_successor(&self, link: NonNull<Link>) {
let immediate = {
let mut state = self.state.lock();
if let Some(result) = state.published {
result
} else if state.upstream_released {
Ok(())
} else {
link.next = state.successors.take();
// SAFETY: The caller still owns the link; the list owns it from here.
unsafe { (*link.as_ptr()).next = state.successors.take() };
state.successors = Some(link);
return;
}
};
Self::drain(link.target.predecessor_done(immediate));
// SAFETY: The caller still owns the link, whose successor is held.
let children = unsafe { link.as_ref() }
.target
.as_ref()
.and_then(|target| target.predecessor_done(immediate));
// SAFETY: Nothing else reaches the link.
unsafe { release(link) };
Self::drain(children);
}

/// Iterative depth-first notification, O(nodes + links), with no stack growth.
fn drain(mut pending: Links) {
let mut frames: Links = None;
loop {
if let Some(mut link) = pending.take() {
pending = link.next.take();
let children = link.target.predecessor_done(link.result);
if let Some(link) = pending.take() {
// SAFETY: This traversal owns every link in `pending` and `frames`; a link's
// held successor keeps its block allocated until `release()`.
let node = unsafe { &mut *link.as_ptr() };
pending = node.next.take();
let children = node.target.as_ref().and_then(|t| t.predecessor_done(node.result));
if children.is_some() {
link.resume = pending.take();
link.next = frames.take();
node.resume = pending.take();
node.next = frames.take();
frames = Some(link);
pending = children;
} else {
// SAFETY: Done with: no list or frame holds it.
unsafe { release(link) };
}
} else if let Some(mut frame) = frames.take() {
frames = frame.next.take();
pending = frame.resume.take();
} else if let Some(frame) = frames.take() {
// SAFETY: As above.
let node = unsafe { &mut *frame.as_ptr() };
frames = node.next.take();
pending = node.resume.take();
// SAFETY: Popped: no list or frame holds it.
unsafe { release(frame) };
} else {
break;
}
}
}
}

/// Temporary backwards references exist only during fallible setup. Installed
/// links retain the successor only, so closing a queue cannot form an Arc cycle.
/// A successor's links between setup and activation. Each link holds the successor, and
/// until activation its predecessor. Installed links point back into the successor's own
/// block, so the only reference cycle, successor -> block -> link -> successor, ends when the
/// predecessor publishes, settles or is dropped (`State::drop`).
pub(crate) struct Prepared {
target: Arc<Publication>,
links: KVec<(Arc<Publication>, KBox<Link>)>,
block: LinkBlock,
}

impl Prepared {
pub(crate) fn new<'a>(
target: Arc<Publication>,
predecessors: impl Iterator<Item = &'a Arc<Publication>> + Clone,
) -> Result<Self> {
let mut links = KVec::with_capacity(predecessors.clone().count(), GFP_KERNEL)?;
// One link per covered unfinished predecessor, all in one allocation that the target
// owns once active: it publishes only after every predecessor has consumed its link,
// so the block outlives each of them, and one charge per job keeps memcg's per-object
// hooks off the submit and event paths.
let count = predecessors.clone().count();
let mut block = LinkBlock(KVVec::with_capacity(count, LINK_FLAGS)?);
if count != 0 {
note_block(false);
}
for predecessor in predecessors {
let link = KBox::new(Link {
target: target.clone(),
result: Ok(()),
next: None,
resume: None,
}, GFP_KERNEL)?;
links.push((predecessor.clone(), link), GFP_KERNEL)?;
block
.0
.push_within_capacity(UnsafeCell::new(Link {
target: Some(target.clone()),
predecessor: Some(predecessor.clone()),
result: Ok(()),
next: None,
resume: None,
}))
.map_err(|_| ENOMEM)?;
}
Ok(Self { target, links })
Ok(Self { target, block })
}

/// Called after all fallible scheduler setup and before any GPU publication.
pub(crate) fn activate(self) {
let Self { target, mut block } = self;
let count = block.0.len();
let links = block.0.as_mut_ptr();
{
let mut state = self.target.state.lock();
debug_assert!(state.remaining == 1 && !state.claimed);
// The fully allocated link vector bounds this count below usize::MAX.
state.remaining += self.links.len();
let mut state = target.state.lock();
debug_assert!(state.remaining == 1 && !state.claimed && state.block.is_none());
// The fully allocated link block bounds this count below usize::MAX.
state.remaining += count;
// Moving the vector leaves its buffer, and so every link, in place.
state.block = Some(block);
}
for (predecessor, link) in self.links {
predecessor.add_successor(link);
for index in 0..count {
// SAFETY: `index` is within the block that `target`, held here, now owns, and
// setup has handed no link out yet.
let link = unsafe { NonNull::new_unchecked(UnsafeCell::raw_get(links.add(index))) };
// SAFETY: As above; the link is still this caller's alone.
if let Some(predecessor) = unsafe { (*link.as_ptr()).predecessor.take() } {
// SAFETY: A set-up link that nothing else reaches.
unsafe { predecessor.add_successor(link) };
}
}
Publication::drain(self.target.predecessor_done(Ok(())));
Publication::drain(target.predecessor_done(Ok(())));
}
}

Expand Down Expand Up @@ -403,4 +531,84 @@ mod tests {
late.finish(Ok([5, 6, 0, 0]));
assert_eq!(fence_status(&late_fence), PRODUCER_FAILED.to_errno());
}

fn blocks() -> (usize, usize) {
(BLOCKS[0].load(Ordering::Relaxed), BLOCKS[1].load(Ordering::Relaxed))
}

#[test]
fn consumer_links_are_one_charged_allocation() {
assert!(LINK_FLAGS.contains(GFP_KERNEL_ACCOUNT));
let contexts = FenceContexts::new(1, c_str!("asahi_pub_block"), KEY).unwrap();
let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap();
let (a, _) = make_pub(&contexts, &status, true);
let (b, _) = make_pub(&contexts, &status, true);
let (c, _) = make_pub(&contexts, &status, true);
for producer in [&a, &b, &c] {
Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate();
}
let (consumer, cons_fence) = make_pub(&contexts, &status, false);
let start = blocks();
Prepared::new(consumer.clone(), [&a, &b, &c].into_iter()).unwrap().activate();
assert_eq!(blocks().0 - start.0, 1);

// Error in the middle of the prefix: the consumer still waits for the last
// producer, then inherits the failure.
a.finish(Ok([1, 2, 0, 0]));
b.finish(Err(EIO));
consumer.finish(Ok([7, 8, 0, 0]));
assert_eq!(fence_status(&cons_fence), 0);
c.finish(Ok([3, 4, 0, 0]));
assert_eq!(fence_status(&cons_fence), PRODUCER_FAILED.to_errno());

assert_eq!(blocks().1 - start.1, 0);
drop(consumer);
assert_eq!(blocks(), (start.0 + 1, start.1 + 1));
}

#[test]
fn link_block_is_freed_once_on_release_and_drop_paths() {
let contexts = FenceContexts::new(1, c_str!("asahi_pub_block_free"), KEY).unwrap();
let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap();

// Release: timestamp-free consumer settles when both producers publish cleanly.
let (a, _) = make_pub(&contexts, &status, true);
let (b, _) = make_pub(&contexts, &status, true);
Prepared::new(a.clone(), core::iter::empty()).unwrap().activate();
Prepared::new(b.clone(), core::iter::empty()).unwrap().activate();
let (consumer, cons_fence) = make_pub(&contexts, &status, false);
let start = blocks();
Prepared::new(consumer.clone(), [&a, &b].into_iter()).unwrap().activate();
a.finish(Ok([1, 2, 0, 0]));
assert!(consumer.is_pending());
b.finish(Ok([3, 4, 0, 0]));
assert!(!consumer.is_pending());
consumer.finish(Ok([5, 6, 0, 0]));
assert!(fence_status(&cons_fence) > 0);
drop(consumer);
assert_eq!(blocks(), (start.0 + 1, start.1 + 1));

// Setup that fails before activation drops its block unused.
let (late, _) = make_pub(&contexts, &status, false);
let start = blocks();
drop(Prepared::new(late.clone(), [&a, &b].into_iter()).unwrap());
assert_eq!(blocks(), (start.0 + 1, start.1 + 1));

// A predecessor dropped before it publishes releases the links installed in it.
let (stuck, _) = make_pub(&contexts, &status, true);
Prepared::new(stuck.clone(), core::iter::empty()).unwrap().activate();
let (waiter, _) = make_pub(&contexts, &status, false);
let start = blocks();
Prepared::new(waiter.clone(), core::iter::once(&stuck)).unwrap().activate();
drop(stuck);
assert_eq!(blocks().1 - start.1, 0);
drop(waiter);
assert_eq!(blocks(), (start.0 + 1, start.1 + 1));

// No predecessors: no block at all.
let (alone, _) = make_pub(&contexts, &status, false);
let start = blocks();
Prepared::new(alone.clone(), core::iter::empty()).unwrap().activate();
assert_eq!(blocks(), start);
}
}
Loading
Loading