Skip to content
Open
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
78 changes: 50 additions & 28 deletions drivers/gpu/drm/asahi/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,14 @@ fn admit_bind(
ledger.admit(client, BOUND_OBJECT_BYTES)
}

/// Closing the handle can wake a submitter independently of the queue's ioctl mutex.
#[pin_data]
struct QueueHandle {
admission: Option<Arc<dyn queue::Room>>,
#[pin]
state: Mutex<TableQueue>,
}

/// A queue in a file's table. Its count in the creating process's share of the device's
/// queues is given back once the queue itself is gone.
pub(crate) struct TableQueue {
Expand All @@ -390,7 +398,7 @@ impl TableQueue {
const REUSE_CMDBUF_CAP: usize = 4096;

/// Takes the cached command-buffer staging allocation so userspace copies run outside the
/// queue mutex (preventing `queue.lock()` -> `mmap_lock` lock-order inversion).
/// queue mutex (preventing `queue.state.lock()` -> `mmap_lock` lock-order inversion).
fn take_cmdbuf(&mut self) -> KVVec<u8> {
core::mem::take(&mut self.cmdbuf)
}
Expand Down Expand Up @@ -438,7 +446,7 @@ pub(crate) struct File {
// Fields drop in order: the queues go first, so that a closing client's submitted work
// can finish before its VMs unmap the user ranges.
// #[pin]
queues: xarray::XArray<Arc<Mutex<TableQueue>>>,
queues: xarray::XArray<Arc<QueueHandle>>,
// #[pin]
vms: xarray::XArray<KBox<Vm>>,
// #[pin]
Expand Down Expand Up @@ -550,7 +558,7 @@ impl File {
let raw_queues = addr_of_mut!((*slot).queues);
pin_init::raw_try_init(
raw_queues,
xarray::XArray::<Arc<Mutex<TableQueue>>>::new(
xarray::XArray::<Arc<QueueHandle>>::new(
xarray::AllocKind::Alloc1,
),
)?;
Expand Down Expand Up @@ -580,7 +588,7 @@ impl File {
}

#[allow(clippy::type_complexity)]
fn queues(self: Pin<&Self>) -> Pin<&xarray::XArray<Arc<Mutex<TableQueue>>>> {
fn queues(self: Pin<&Self>) -> Pin<&xarray::XArray<Arc<QueueHandle>>> {
// SAFETY: Structural pinned projection for queues.
// We never move out of this field.
unsafe { self.map_unchecked(|s| &s.queues) }
Expand Down Expand Up @@ -1537,13 +1545,13 @@ impl File {
.queues()
.find(index, usize::MAX)
.map(|(idx, guard)| {
let queue: Arc<Mutex<TableQueue>> = guard.borrow().into();
let queue: Arc<QueueHandle> = guard.borrow().into();
(idx, queue)
})
else {
break;
};
queue.lock().drain();
queue.state.lock().drain();
if idx == usize::MAX {
break;
}
Expand All @@ -1557,10 +1565,10 @@ impl File {
let mut index = 0;
while let Some((idx, entry)) = this.vms().find(index, usize::MAX) {
let vm: &Vm = entry.borrow();
if which(vm) {
if let Some(status) = vm.vm.status() {
status.mark_client_closed();
}
let status = if which(vm) { vm.vm.status().cloned() } else { None };
drop(entry);
if let Some(status) = status {
status.mark_client_closed();
}
if idx == usize::MAX {
break;
Expand Down Expand Up @@ -1847,10 +1855,13 @@ impl File {

data.queue_id = resv.index().try_into()?;
resv.fill(Arc::pin_init(
new_mutex!(TableQueue {
queue,
cmdbuf: KVVec::new(),
_share: share,
pin_init!(QueueHandle {
admission: queue.admission(),
state <- new_mutex!(TableQueue {
queue,
cmdbuf: KVVec::new(),
_share: share,
}),
}),
GFP_KERNEL,
)?)?;
Expand All @@ -1867,11 +1878,9 @@ impl File {
) -> Result<u32> {
// grab the queue so the xarray spinlock is dropped first
let queue = file.inner().queues().remove(data.queue_id as usize);
if queue.is_none() {
Err(ENOENT)
} else {
Ok(0)
}
let queue = queue.ok_or(ENOENT)?;
if let Some(room) = &queue.admission { room.close(); }
Ok(0)
}

/// IOCTL: submit: Submit GPU work to a command submission queue.
Expand All @@ -1897,7 +1906,7 @@ impl File {
}

// Upgrade to Arc<T> to drop the XArray lock early
let queue: Arc<Mutex<TableQueue>> = file
let queue: Arc<QueueHandle> = file
.inner()
.queues()
.lock()
Expand Down Expand Up @@ -1927,11 +1936,11 @@ impl File {
// on every failure but a refusal (ENOMEM, ENOSPC), which leaves them
// untouched (DRM_ASAHI_FEATURE_SUBMIT_REFUSAL_UNTOUCHED). Take the fallible userspace snapshot before that point,
// staging into a buffer taken from the queue's reusable cache so user
// copies never execute under `queue.lock()`.
// copies never execute under `queue.state.lock()`.
let mut cmdbuf = if guarded {
let mut buf = queue.lock().take_cmdbuf();
let mut buf = queue.state.lock().take_cmdbuf();
if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) {
queue.lock().return_cmdbuf(buf);
queue.state.lock().return_cmdbuf(buf);
return Err(e);
}
Some(buf)
Expand All @@ -1958,7 +1967,7 @@ impl File {
Ok(syncs) => syncs,
Err(e) => {
if let Some(buf) = cmdbuf {
queue.lock().return_cmdbuf(buf);
queue.state.lock().return_cmdbuf(buf);
}
return Err(e);
}
Expand All @@ -1972,23 +1981,36 @@ impl File {
id
);

// Copy the command buffer into the kernel outside `queue.lock()`. Because we
// Copy the command buffer into the kernel outside `queue.state.lock()`. Because we
// need to iterate the command buffer twice, we do this in one big copy_from_user
// to avoid TOCTOU issues.
let cmdbuf = match cmdbuf.take() {
Some(buf) => buf,
None => {
let mut buf = queue.lock().take_cmdbuf();
let mut buf = queue.state.lock().take_cmdbuf();
if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) {
queue.lock().return_cmdbuf(buf);
queue.state.lock().return_cmdbuf(buf);
return Err(e);
}
buf
}
};

let objects = file.inner().objects();
let mut guard = queue.lock();
// A full queue takes the submission once it has room. Sleep without its lock, which
// nothing that frees the room takes, and check again under it. Nothing is published yet,
// so a signal restarts the ioctl.
let mut guard = loop {
let guard = queue.state.lock();
let Some(room) = queue.admission.as_ref().filter(|room| room.must_wait()) else {
break guard;
};
drop(guard);
if let Err(error) = room.wait() {
queue.state.lock().return_cmdbuf(cmdbuf);
return Err(error);
}
};
let ret = guard.queue.submit(
reg_data,
id,
Expand Down
47 changes: 47 additions & 0 deletions drivers/gpu/drm/asahi/g17/completion/publication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ struct Link {
// 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,
/// One unit of the queue budget ([`Prepared::with_charges`]), given back with the link's
/// memory: delivered, dropped unused, or freed with a queue.
charge: Option<crate::g17::queue::budget::Charge>,
}

struct State {
Expand Down Expand Up @@ -545,12 +548,23 @@ impl Prepared {
result: Ok(()),
next: None,
resume: None,
charge: None,
}, GFP_KERNEL)?;
links.push((predecessor.clone(), link), GFP_KERNEL)?;
}
Ok(Self { target, links })
}

/// Charges each link one unit of `budget`, given back when the link is freed (delivered or
/// dropped unused), not when the publication goes: its queue's frontier keeps that until the
/// next submission, which may be waiting for these units.
pub(crate) fn with_charges(mut self, budget: &Arc<crate::g17::queue::budget::Budget>) -> Self {
for (_, link) in self.links.iter_mut() {
link.charge = Some(budget.charge(1));
}
self
}

/// Called after all fallible scheduler setup and before any GPU publication.
pub(crate) fn activate(self) {
let attach_now = {
Expand Down Expand Up @@ -633,6 +647,39 @@ mod tests {
(Publication::new(output, status.clone(), has_outputs).unwrap(), handle)
}

#[test]
fn link_units_come_back_once_the_links_are_freed() {
let contexts = FenceContexts::new(1, c_str!("asahi_pub_charge"), KEY).unwrap();
let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap();
let budget = crate::g17::queue::budget::Budget::with_limit(1).unwrap();
let pair = || {
let (producer, _) = make_pub(&contexts, &status, true);
let (consumer, _) = make_pub(&contexts, &status, false);
Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate();
Prepared::new(consumer.clone(), core::iter::once(&producer))
.unwrap()
.with_charges(&budget)
.activate();
(producer, consumer)
};
// Delivered: the consumer finishes first, so its link waits in the producer's successor
// list until the producer publishes. The units come back while `consumer` still holds the
// publication, as its queue's frontier does until the next submission.
let (producer, consumer) = pair();
assert!(budget.full());
consumer.finish(Ok([1, 2, 3, 4]));
assert!(budget.full());
producer.finish(Ok([5, 6, 0, 0]));
assert_eq!(budget.used(), 0);
// Dropped unused: the producer has published when the consumer finishes.
let (producer, consumer2) = pair();
assert!(budget.full());
producer.finish(Ok([5, 6, 0, 0]));
consumer2.finish(Ok([1, 2, 3, 4]));
assert_eq!(budget.used(), 0);
drop((consumer, consumer2));
}

#[test]
fn consumer_retiring_before_delayed_producer_failure_inherits_error() {
let contexts = FenceContexts::new(1, c_str!("asahi_pub_test"), KEY).unwrap();
Expand Down
4 changes: 2 additions & 2 deletions drivers/gpu/drm/asahi/g17/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ impl Context {
let render_id =
Arc::pin_init(new_mutex!(render_id, "G17 context render pool identity"), GFP_KERNEL)?;
let order =
Arc::pin_init(new_mutex!(Order::new(), "G17 context admission order"), GFP_KERNEL)?;
Arc::pin_init(new_mutex!(Order::new()?, "G17 context admission order"), GFP_KERNEL)?;
let kill = Arc::new(Kill::new(), GFP_KERNEL)?;
let order_wait =
Arc::pin_init(new_condvar!("G17 context admission order wait"), GFP_KERNEL)?;
Expand Down Expand Up @@ -867,7 +867,7 @@ pub(super) struct TestOrderWindow {
#[cfg(CONFIG_KUNIT = "y")]
impl TestOrderWindow {
pub(super) fn new_full() -> Result<Self> {
let order = KBox::pin_init(new_mutex!(Order::new(), "G17 test order"), GFP_KERNEL)?;
let order = KBox::pin_init(new_mutex!(Order::new()?, "G17 test order"), GFP_KERNEL)?;
let wait = KBox::pin_init(new_condvar!("G17 test order wait"), GFP_KERNEL)?;
let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL)?;
let first = {
Expand Down
Loading
Loading