From b99cc53c96fe3511922884b6c2fe922312acdd9c Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 22 Nov 2026 17:06:11 -0300 Subject: [PATCH 1/6] drm/asahi: g17: keep userspace-sized submit vectors off contiguous pages The submit ioctl collects its validated commands and their VM pins in KVecs, and builds each command's dependency, checked-input and firmware fence lists in KVecs too. All of them are sized by userspace: up to 64 commands per submission, each over a kilobyte once validated, and as many dependencies as the command waits for, which for the other engine's unfinished commands can be thousands. kmalloc() needs them physically contiguous, so a large submission asks for an order-3 block for its commands alone, on every ioctl. On a machine without compaction that is never allowed to fail and ends in the OOM killer instead, five times in one dEQP-VK run on an M4 Pro, with 26 GB available: deqp-vk invoked oom-killer: gfp_mask=0x40cc0(GFP_KERNEL|__GFP_COMP), order=3 krealloc_node_align_noprof+0x154/0x238 rust_helper_krealloc_node_align+0x10/0x20 ..._asahi_core3g175queue...18prepare_submission... Nothing needs these contiguous: only the ioctl and the job read them. Make them KVVecs, and the cursor array the merge of a long dependency list allocates a kvmalloc_array(). Small ones keep their kmalloc memory. Userspace decides how large they get, so charge all of them to the caller's memory cgroup (GFP_KERNEL_ACCOUNT). A vmalloc()ed vector must be freed where vfree() may sleep. The command, dependency and merge vectors are freed in the ioctl. A job's packet keeps its checked inputs and firmware fences, and its owners release it under the runtime's mutexes or from drm_sched's free_job() work, never under a spinlock or in a fence callback. The fence array of the merged dependency itself is allocated by __dma_fence_unwrap_merge() and freed with kfree() by dma_fence_array, so it stays contiguous. It holds only unsignalled fences, 8 bytes each. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/job.rs | 10 ++--- drivers/gpu/drm/asahi/g17/queue/mod.rs | 49 ++++++++++++++----------- drivers/gpu/drm/asahi/g17/sync_input.c | 5 ++- drivers/gpu/drm/asahi/g17/sync_input.rs | 5 ++- 4 files changed, 38 insertions(+), 31 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index b6536c07b443f..d66383901fa6f 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -122,8 +122,8 @@ pub(crate) struct Packet { pub(crate) order: Order, pub(crate) completion: Arc, pub(crate) footprint: Option>, - inputs: KVec, - firmware: KVec, + inputs: KVVec, + firmware: KVVec, publication: AtomicU8, cancelled: AtomicBool, early: AtomicI32, @@ -140,8 +140,8 @@ impl Packet { command: Validated, order: Order, completion: Arc, - inputs: KVec, - firmware: KVec, + inputs: KVVec, + firmware: KVVec, ) -> Result> { let footprint = match &command { Validated::Render { attachments, pass, .. } => { @@ -603,7 +603,7 @@ impl Scheduler { pub(crate) fn enqueue( &mut self, packet: Arc, - dependencies: KVec, + dependencies: KVVec, early: bool, publication: Option, ) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index d322c2710ab9e..8edb31f0089ab 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -111,8 +111,8 @@ pub(crate) struct Queue { } type ValidatedBatch = ( - KVec<(Validated, Order, Destinations)>, - KVec, + KVVec<(Validated, Order, Destinations)>, + KVVec, ); impl Queue { @@ -336,9 +336,12 @@ impl Queue { }); } let failure_count = failures.iter().flatten().count(); - let mut dependencies = KVec::with_capacity( + // These grow with the producers this command waits for, which userspace decides: the + // other engine's unfinished commands alone can number thousands. So they need no + // contiguous pages and are charged to the caller. + let mut dependencies = KVVec::with_capacity( inputs.len() + count + timestamp_count + failure_count, - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; // Host-waited producers are checked on the host instead of in firmware. let (host_count, firmware_count) = if host_waits { @@ -346,22 +349,22 @@ impl Queue { } else { (0, count) }; - let mut checked_inputs = KVec::with_capacity( + let mut checked_inputs = KVVec::with_capacity( inputs.len() + host_count + timestamp_count + failure_count, - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; - let mut firmware = KVec::with_capacity(firmware_count, GFP_KERNEL)?; + let mut firmware = KVVec::with_capacity(firmware_count, GFP_KERNEL_ACCOUNT)?; for fence in failures.into_iter().flatten() { - checked_inputs.push(fence.clone(), GFP_KERNEL)?; - dependencies.push(fence.clone(), GFP_KERNEL)?; + checked_inputs.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; + dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; } // Same-engine parents order GPU execution, not the host's timestamp // writes. Only timestamp publishers need these completion waits and // status checks; ordinary compute keeps its existing queue ordering. for (_, fences) in timestamps { if fences.ready.raw() == fences.completed.raw() { - checked_inputs.push(fences.completed.clone(), GFP_KERNEL)?; - dependencies.push(fences.ready.clone(), GFP_KERNEL)?; + checked_inputs.push(fences.completed.clone(), GFP_KERNEL_ACCOUNT)?; + dependencies.push(fences.ready.clone(), GFP_KERNEL_ACCOUNT)?; } } for (_, fences) in frontier { @@ -374,11 +377,11 @@ impl Queue { if host_waits { // Keep other-engine producers on the host until completion, and // propagate their errors before publishing the consumer. - dependencies.push(fences.completed.clone(), GFP_KERNEL)?; - checked_inputs.push(fences.completed.clone(), GFP_KERNEL)?; + dependencies.push(fences.completed.clone(), GFP_KERNEL_ACCOUNT)?; + checked_inputs.push(fences.completed.clone(), GFP_KERNEL_ACCOUNT)?; } else { - dependencies.push(fences.ready.clone(), GFP_KERNEL)?; - firmware.push(fences.completed.clone(), GFP_KERNEL)?; + dependencies.push(fences.ready.clone(), GFP_KERNEL_ACCOUNT)?; + firmware.push(fences.completed.clone(), GFP_KERNEL_ACCOUNT)?; } } // Each command owns every input fence; independent engines may publish in @@ -398,14 +401,14 @@ impl Queue { { continue; } - dependencies.push(fence.clone(), GFP_KERNEL)?; - checked_inputs.push(fence.clone(), GFP_KERNEL)?; + dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; + checked_inputs.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; } } if let Some(sources) = &sources { for ready in sources.publication_waits() { - dependencies.push(ready.clone(), GFP_KERNEL)?; - checked_inputs.push(ready.clone(), GFP_KERNEL)?; + dependencies.push(ready.clone(), GFP_KERNEL_ACCOUNT)?; + checked_inputs.push(ready.clone(), GFP_KERNEL_ACCOUNT)?; } } // Publish from the ioctl whenever nothing has to wait, at any depth. @@ -463,7 +466,9 @@ impl Queue { // starts only after the entire ioctl has been validated and pinned. let base = self.sequence; let mut preceding = [0; 2]; - let mut pending = KVec::with_capacity(1, GFP_KERNEL)?; + // Up to MAX_COMMANDS_PER_SUBMISSION commands of over a kilobyte each: a high-order + // block of contiguous pages they do not need. Charged to the caller. + let mut pending = KVVec::with_capacity(1, GFP_KERNEL_ACCOUNT)?; while let Some(command) = parser.next()? { let mut payload = self .proof @@ -506,11 +511,11 @@ impl Queue { } } .map_err(|error| refused("its timestamp destinations", error))?; - pending.push((payload, order, destinations), GFP_KERNEL)?; + pending.push((payload, order, destinations), GFP_KERNEL_ACCOUNT)?; } parser.finish()?; // Every accepted command pins the VM before any command is enqueued. - let mut guards = KVec::with_capacity(pending.len(), GFP_KERNEL)?; + let mut guards = KVVec::with_capacity(pending.len(), GFP_KERNEL_ACCOUNT)?; guards .push_within_capacity(parse_guard) .map_err(|_| ENOMEM)?; diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 145a5955c8796..9056c7f029935 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -94,10 +94,11 @@ struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t struct dma_fence_unwrap *cursors; struct dma_fence *merged; - cursors = kmalloc_array(count, sizeof(*cursors), GFP_KERNEL); + /* One cursor per fence the command waits for: no contiguous pages needed. */ + cursors = kvmalloc_array(count, sizeof(*cursors), GFP_KERNEL_ACCOUNT); if (!cursors) return NULL; merged = __dma_fence_unwrap_merge(count, (struct dma_fence **)fences, cursors); - kfree(cursors); + kvfree(cursors); return merged; } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 33ac3f94d4f21..9d3e0885e7e74 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -21,9 +21,10 @@ unsafe extern "C" { /// One fence that signals once all of `fences` have (see `job::MERGED_DEPENDENCIES`). pub(super) fn merge(fences: &[Fence]) -> Result { - let mut raw = KVec::with_capacity(fences.len(), GFP_KERNEL)?; + // As many as the command waits for: no contiguous pages, charged to the caller. + let mut raw = KVVec::with_capacity(fences.len(), GFP_KERNEL_ACCOUNT)?; for fence in fences { - raw.push(fence.raw(), GFP_KERNEL)?; + raw.push(fence.raw(), GFP_KERNEL_ACCOUNT)?; } // SAFETY: Every pointer is a live fence borrowed from `fences` for this call; // the helper only reads them and returns a new reference of its own. From ad7c997ec0f2638fe40adf0b28023d58db35e2d1 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sat, 28 Nov 2026 14:57:43 -0300 Subject: [PATCH 2/6] drm/asahi: g17: keep the enqueue ordering vectors off contiguous pages Since this branch was written, main builds a command's producer waits in two steps: EnqueueOrdering collects the covered predecessors, host waits, firmware waits and inherited timestamp waits from the frontier, and the publication's Prepared links one record per predecessor. Each of those vectors grows with the same covered prefixes this branch's dependency vectors do, pushed one entry at a time from empty, so a deep prefix of the other engine reallocates them into high-order contiguous blocks on every command. Make them KVVecs charged to the caller with GFP_KERNEL_ACCOUNT, and charge the per-predecessor link records too. vfree() context: EnqueueOrdering and Prepared are consumed or dropped in the ioctl; Prepared::activate() frees its links after the target's mutex is released. The inherited timestamp waits end up in Fences, which only the Queue holds, and the Queue already keeps KVVecs. Signed-off-by: Jonathan Goyvaerts --- .../drm/asahi/g17/completion/publication.rs | 9 ++--- drivers/gpu/drm/asahi/g17/job.rs | 2 +- drivers/gpu/drm/asahi/g17/queue/mod.rs | 33 ++++++++++--------- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index b22bb9a5b5e78..13a79bf574fc2 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -227,7 +227,7 @@ impl Publication { /// links retain the successor only, so closing a queue cannot form an Arc cycle. pub(crate) struct Prepared { target: Arc, - links: KVec<(Arc, KBox)>, + links: KVVec<(Arc, KBox)>, } impl Prepared { @@ -235,15 +235,16 @@ impl Prepared { target: Arc, predecessors: impl Iterator> + Clone, ) -> Result { - let mut links = KVec::with_capacity(predecessors.clone().count(), GFP_KERNEL)?; + // One per covered unfinished predecessor, which userspace sizes: charged to the caller. + let mut links = KVVec::with_capacity(predecessors.clone().count(), GFP_KERNEL_ACCOUNT)?; 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)?; + }, GFP_KERNEL_ACCOUNT)?; + links.push((predecessor.clone(), link), GFP_KERNEL_ACCOUNT)?; } Ok(Self { target, links }) } diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 1b9ba7f1c2524..5845d5c4f02cb 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -554,7 +554,7 @@ pub(crate) struct Fences { /// timestamp-free publication chaining. `None` for commands that write their /// own timestamps (covered by `completed`) or have no pending timestamp /// ancestors. - pub(crate) timestamp_waits: Option>>, + pub(crate) timestamp_waits: Option>>, pub(crate) owner: Arc, } diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 21f348e469f9d..b7c96d438c192 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -762,9 +762,9 @@ impl FrontierEntry for Fences { } } -fn push_unique_fence(out: &mut KVec, fence: &Fence) -> Result { +fn push_unique_fence(out: &mut KVVec, fence: &Fence) -> Result { if !out.iter().any(|existing| existing.raw() == fence.raw()) { - out.push(fence.clone(), GFP_KERNEL)?; + out.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; } Ok(()) } @@ -772,7 +772,7 @@ fn push_unique_fence(out: &mut KVec, fence: &Fence) -> Result { /// Collect the actual pending host-timestamp writer fences represented by `entry`: /// its own `completed` fence when it writes host timestamps, otherwise its still-pending /// inherited timestamp-writer fences. -fn collect_timestamp_waits(entry: &E, out: &mut KVec) -> Result { +fn collect_timestamp_waits(entry: &E, out: &mut KVVec) -> Result { let Some(pub_ref) = entry.pending_publication() else { return Ok(()); }; @@ -788,11 +788,14 @@ fn collect_timestamp_waits(entry: &E, out: &mut KVec) - Ok(()) } +/// Each of these grows with the covered prefixes, which userspace sizes: the other engine's +/// unfinished commands alone can number thousands. So they need no contiguous pages and are +/// charged to the caller. struct EnqueueOrdering<'a> { - predecessors: KVec<&'a Arc>, - host_waits: KVec, - firmware_waits: KVec<(Fence, Fence)>, - inherited_timestamp_waits: KVec, + predecessors: KVVec<&'a Arc>, + host_waits: KVVec, + firmware_waits: KVVec<(Fence, Fence)>, + inherited_timestamp_waits: KVVec, } impl<'a> EnqueueOrdering<'a> { @@ -820,16 +823,16 @@ impl<'a> EnqueueOrdering<'a> { // deferred error published between pruning and link selection, // `add_successor()` still delivers that failure immediately instead of // letting the successor signal success. - let mut predecessors = KVec::new(); - let mut host = KVec::new(); - let mut firmware = KVec::new(); - let mut inherited_timestamp_waits = KVec::new(); + let mut predecessors = KVVec::new(); + let mut host = KVVec::new(); + let mut firmware = KVVec::new(); + let mut inherited_timestamp_waits = KVVec::new(); if same_chain { for (_, entry) in same_covered.clone() { let status = entry.status(); if status <= 0 { if let Some(publication) = entry.pending_publication() { - predecessors.push(publication, GFP_KERNEL)?; + predecessors.push(publication, GFP_KERNEL_ACCOUNT)?; collect_timestamp_waits(entry, &mut inherited_timestamp_waits)?; } else if status < 0 { // Failed after `prune_frontier()` without an active @@ -843,7 +846,7 @@ impl<'a> EnqueueOrdering<'a> { for (_, entry) in other_covered.clone() { if entry.status() <= 0 { if let Some(publication) = entry.pending_publication() { - predecessors.push(publication, GFP_KERNEL)?; + predecessors.push(publication, GFP_KERNEL_ACCOUNT)?; collect_timestamp_waits(entry, &mut inherited_timestamp_waits)?; } } @@ -895,13 +898,13 @@ impl<'a> EnqueueOrdering<'a> { collect_timestamp_waits(entry, &mut host)?; firmware.push( (entry.scheduled().clone(), entry.completed().clone()), - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; } } else { firmware.push( (entry.scheduled().clone(), entry.completed().clone()), - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; } } From cab097479b9a1b529e2136c5ebfa01e5d6ac5fcd Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sat, 28 Nov 2026 15:02:52 -0300 Subject: [PATCH 3/6] selftests: asahi-m4: shim kvmalloc_array() for g17/sync_input.c test-fence-signalling.py compiles the production g17/sync_input.c against host shims. Its fence merge now takes its cursor array with kvmalloc_array(GFP_KERNEL_ACCOUNT) and frees it with kvfree(), so the shim provides those instead of kmalloc_array(), kfree() and GFP_KERNEL, which nothing else in the harness uses. Signed-off-by: Jonathan Goyvaerts --- .../selftests/drivers/gpu/asahi-m4/test-fence-signalling.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index b985dad1a9ed5..10ab1ed84123c 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -551,7 +551,7 @@ def extract_function(text, name): typedef uint64_t u64; #define ASAHI_G17_SYNC_SCOPE_H 1 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) -#define GFP_KERNEL 0 +#define GFP_KERNEL_ACCOUNT 0 struct dma_fence { uint64_t context; @@ -635,13 +635,13 @@ def extract_function(text, name): for ((fence) = dma_fence_unwrap_first((head), (cursor)); (fence); \ (fence) = dma_fence_unwrap_next((cursor))) -static inline void *kmalloc_array(size_t n, size_t size, int flags) +static inline void *kvmalloc_array(size_t n, size_t size, int flags) { (void)flags; return calloc(n, size); } -static inline void kfree(void *p) +static inline void kvfree(void *p) { free(p); } From e25c142aa1a1ce27ab19faaacf401ead5a77524d Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 00:13:27 -0300 Subject: [PATCH 4/6] drm/asahi: g17: don't charge a publication's links to the caller Prepared::new() takes one link record per covered predecessor, and the vector holding them, with GFP_KERNEL_ACCOUNT. Every submit charges them to the caller's memory cgroup, and the event work that publishes the predecessor uncharges them, which puts memcg's slab hooks on both paths. On an M4 Pro, Cyberpunk 2077 spent 0.35-0.40% of its samples in them, against 0.03% before, and its median frame time rose from about 48 to 52-53 ms; without the charge both come back. The charge buys nothing here: the links are transient, bounded by the frontier, and never outlive the predecessor's publication. Take them with GFP_KERNEL; the vector stays a KVVec, so a deep prefix still needs no contiguous pages. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/completion/publication.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 13a79bf574fc2..4df5fe368b872 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -235,16 +235,17 @@ impl Prepared { target: Arc, predecessors: impl Iterator> + Clone, ) -> Result { - // One per covered unfinished predecessor, which userspace sizes: charged to the caller. - let mut links = KVVec::with_capacity(predecessors.clone().count(), GFP_KERNEL_ACCOUNT)?; + // One per covered unfinished predecessor: no contiguous pages. Not charged: the links are + // transient, bounded by the frontier, and never outlive the predecessor's publication. + let mut links = KVVec::with_capacity(predecessors.clone().count(), GFP_KERNEL)?; for predecessor in predecessors { let link = KBox::new(Link { target: target.clone(), result: Ok(()), next: None, resume: None, - }, GFP_KERNEL_ACCOUNT)?; - links.push((predecessor.clone(), link), GFP_KERNEL_ACCOUNT)?; + }, GFP_KERNEL)?; + links.push((predecessor.clone(), link), GFP_KERNEL)?; } Ok(Self { target, links }) } From edade58c698e5ecf97c4f2652abdb06ae17ac581 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 01:16:02 -0300 Subject: [PATCH 5/6] drm/asahi: g17: keep a publication's links in one charged block A command's publication waits on every covered unfinished predecessor through one link each. Since "drm/asahi: g17: don't charge a publication's links to the caller", each link is its own uncharged KBox. Nothing caps how many a client keeps alive: every command behind a stalled predecessor adds one link per covered unfinished publication, so n such commands hold n(n-1)/2 links for as long as the stall lasts. They are per-job state of the same kind as the job's fence vectors (Packet::inputs and Packet::firmware hold one fence per covered producer): sized by what the command covers, and charged to the client, so the client's memory cgroup is their bound, as it is for those vectors. What made charging them cost frame time was one charge and uncharge per link: on an M4 Pro, Cyberpunk 2077 spent 0.35-0.40% of its samples in memcg's slab hooks, on the submit path and in the event work that frees links. Allocate all of a successor's links in one block, charged with GFP_KERNEL_ACCOUNT. The successor's publication owns the block from activation on, and predecessors' lists point into it. That is one charge and one uncharge per job, whatever the number of links. The block outlives every link in it: a publication publishes only after each predecessor has consumed its link, and each link holds its successor until then, which a predecessor dropped before publishing releases (State::drop). A link reaches no other thread while it sits in one list, under that predecessor's lock, or in the one traversal that detached it. KUnit checks that a successor with three predecessors makes exactly one allocation, charged, and frees it exactly once: after an error in the middle of its prefix, after a clean settle, when setup is dropped before activation and when a predecessor is dropped unpublished. Allocating per link again, or dropping __GFP_ACCOUNT, fails it. Signed-off-by: Jonathan Goyvaerts --- .../drm/asahi/g17/completion/publication.rs | 289 +++++++++++++++--- 1 file changed, 246 insertions(+), 43 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 4df5fe368b872..11302cdd0bbaf 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -9,13 +9,23 @@ 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>; +type Links = Option>; +/// 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, + /// 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>, + /// The predecessor to install in, held only between setup and activation. + predecessor: Option>, result: Result, next: Links, // Reuse an already-consumed link as a traversal frame instead of recursing @@ -23,6 +33,48 @@ struct Link { 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) { + // 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>); + +// 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 { + note_block(true); + } + } +} + struct State { remaining: usize, result: Option>, @@ -33,6 +85,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, +} + +// 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 { @@ -83,6 +155,7 @@ impl Publication { published: None, upstream_released: false, successors: None, + block: None, }, "G17 host timestamp publication"), }), GFP_KERNEL, @@ -129,7 +202,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. @@ -139,10 +212,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 } @@ -175,16 +251,22 @@ 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) { + /// # Safety + /// + /// `link` must be a set-up link that no list or traversal reaches yet. + unsafe fn add_successor(&self, link: NonNull) { let immediate = { let mut state = self.state.lock(); if let Some(result) = state.published { @@ -192,30 +274,48 @@ impl Publication { } 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; } @@ -223,11 +323,13 @@ impl Publication { } } -/// 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, - links: KVVec<(Arc, KBox)>, + block: LinkBlock, } impl Prepared { @@ -235,33 +337,54 @@ impl Prepared { target: Arc, predecessors: impl Iterator> + Clone, ) -> Result { - // One per covered unfinished predecessor: no contiguous pages. Not charged: the links are - // transient, bounded by the frontier, and never outlive the predecessor's publication. - let mut links = KVVec::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(()))); } } @@ -405,4 +528,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); + } } From 25ac1dfa71bec0b06cd1cfc946b579551bd7d466 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 29 Nov 2026 01:52:21 -0300 Subject: [PATCH 6/6] drm/asahi: g17: assert that a link block is freed where it may sleep A publication's link block is a KVVec, so a large one may come from vmalloc, and vfree() may sleep outside interrupt context. Its last reference drops wherever the publication's does: in the ioctl, at queue teardown, in drm_sched's free_job and kill work, and in the event work through Deferred::finish(). None of them holds a spinlock, has interrupts disabled or is in an RCU read side. The hard interrupt and the rescan hrtimer only queue the event work. Dropping a publication already takes a mutex (fence::Member's drop, through Submission::release_state()), so those places had to be able to sleep before the block existed. Make that a checked rule at the free site: might_sleep() when a block that owns memory is freed. With CONFIG_DEBUG_ATOMIC_SLEEP, KUnit runs clean, and dropping only an unactivated block under a spinlock reports "sleeping function called from invalid context" from LinkBlock's drop. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/completion/publication.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index 11302cdd0bbaf..e317ad67ce82a 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -70,6 +70,9 @@ 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); } }