From f207315d7ad68ae3452b3f8d1e31018458e15d7c Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 27 Nov 2026 09:00:17 -0500 Subject: [PATCH 1/7] drm/asahi: g17: keep M5 work nodes and compute descriptors firmware-cached linux#3170 made every firmware-mutable pooled G17 object uncached after a J716c (T6050) compute queue record rebound in place had a dirty firmware line revert the host's owner fields. linux#3186 restored firmware caching for WorkState node pages and compute DescriptorRings on G17P only, leaving M5 uncached. On M5 Max (J775c, T6050), keeping WorkState node pages and compute DescriptorRings uncached regressed light submission throughput by ~17-20% (render.light queue d8 18.01 -> 23.19-23.48 us). Both objects obey the same lifetime invariants on M5 as on G17P: - Work nodes are rewritten only after WorkStorage::drained() has observed the firmware's final completed count from memory, and returned work states are zeroed only once their pool fence is met. - Compute descriptor slots are rewritten only after the kick that last used the slot has retired (at most DESCRIPTORS kicks are in flight). Objects the host rewrites in place while their queue may run keep linux#3170's uncached mappings everywhere: render queue records (Family::QueueState), the compute graph, and M5 scheduler pages (Family::Scheduler). Restore firmware caching for Family::WorkState (node page, UAT_PGSZ) and compute Family::Descriptor (size) on M5 as well, and update the cache policy checks and mutations in tools/asahi/g17-object-fence-tests.py. Verified on J775c (M5 Max, lobata, one-shot trial boot on 88ddea8ba): - render.light queue d4/d8/d16/d32: 27.92/23.48 -> 23.61/19.35/19.17/18.79 us (-15.4%/-17.6% at d4/d8) - compute.light queue d8/d16/d32: 13.78 -> 12.45/12.43/12.44 us (-9.7% at d32) - copy.bw queue d8: 412.6 -> 421.2 GB/s - dEQP-VK.synchronization2.op.multi_queue.*: 16680/16680 pass, 0 fail (7080 not supported) - Concurrent render.light+compute.light+copy.bw stress, queues mode (d2/d4/d8), sync.signal, and 60x rapid context create/destroy cycles: 0 errors, 0 GPU faults, 0 kernel WARNs. - tools/asahi/g17-object-fence-tests.py + all 9 mutations pass. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/context.rs | 16 +++++----- drivers/gpu/drm/asahi/g17/queue/compute.rs | 18 +++++------- tools/asahi/g17-object-fence-tests.py | 34 ++++++++++++---------- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index d5b2e15224741..12a7333a3dc17 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -313,18 +313,18 @@ impl Context { let scheduler_generation = super::ids::OBJECTS.object()?; let scheduler = Arc::new(scheduler, GFP_KERNEL)?; // Both firmware and host write work nodes (reused every 63 submissions - // and zeroed on pool reuse). M5 keeps the whole work-state object - // uncached. G17P maps the node page firmware-cached: the host rewrites - // a node only after `WorkStorage::drained` has read the firmware's - // final `completed` count from memory, and zeroes a returned object - // only once its pool fence is met, so it never rewrites a node the - // firmware is still updating. The counter page, which the host writes - // on every kick, stays uncached. + // and zeroed on pool reuse). Map the node page firmware-cached on all + // G17 (G17P and M5): the host rewrites a node only after + // `WorkStorage::drained` has read the firmware's final `completed` + // count from memory, and zeroes a returned object only once its pool + // fence is met, so it never rewrites a node the firmware is still + // updating. The counter page, which the host writes on every kick, + // stays uncached. let mut object = pool.allocate( alloc, Family::WorkState, 2 * UAT_PGSZ, - if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }, + UAT_PGSZ, kernel_prot, CpuMap::WriteCombined, )?; diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 67c78957fb364..952da690e5238 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -108,22 +108,20 @@ pub(crate) struct DescriptorRing { impl DescriptorRing { /// Both firmware and host write compute descriptors: the firmware updates /// an accounting word near the end of each descriptor (`+0xfac` on M5), - /// and the host rewrites each slot every 32 kicks. M5 keeps them uncached - /// against the dirty-line writeback hazard of linux#3170, while retaining - /// their VA and fence in the pool. G17P maps them firmware-cached, as it - /// does render descriptors: the host rewrites a slot only after the kick - /// that last used it retired (at most `DESCRIPTORS` kicks are in flight), - /// by when that kick's accounting store is in memory. The hardware reads - /// the same pages through an uncached canonical low alias; on M5 the - /// kernel mapping, in the upper half every execution context includes, is - /// firmware-only. + /// and the host rewrites each slot every 32 kicks. Map the ring + /// firmware-cached on all G17 (G17P and M5), as for render descriptors: + /// the host rewrites a slot only after the kick that last used it retired + /// (at most `DESCRIPTORS` kicks are in flight), by when that kick's + /// accounting store is in memory. The hardware reads the same pages + /// through an uncached canonical low alias; on M5 the kernel mapping, in + /// the upper half every execution context includes, is firmware-only. pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc) -> Result { let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; let object = objects.allocate( alloc, Family::Descriptor, size, - if alloc.uat.is_m5() { 0 } else { size }, + size, if alloc.uat.is_m5() { mmu::PROT_FW_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }, CpuMap::WriteCombined, )?; diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index fc672d2e8ce27..b7c289e2eb6cd 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -17,10 +17,10 @@ match the pool before linux#1978 (BASE) on the same random operations. - Source rules: every accessor that hands the address to the firmware marks it, and only the release path of `retain_linked_work` marks it released. -- Cache policy (linux#3170 and its G17P follow-up): records the host rewrites +- Cache policy (linux#3170 and follow-ups): records the host rewrites in place (render queue records, the compute graph, M5 scheduler pages) stay - uncached on every G17; work nodes and compute descriptors are uncached on M5 - and keep their firmware-cached prefix on G17P. + uncached on every G17; work nodes and compute descriptors keep their + firmware-cached prefix on every G17 (G17P and M5). `--mutation` applies one known-bad change to the compiled copy; the run must then fail. @@ -51,14 +51,17 @@ 'node-unmarked': ('context', ' self.context.expose_work();\n', ''), # A consumed release with an empty list does not mark the work state. 'no-release': ('context', 'mark.released(super::channel::control_witnessed());', 'let _ = mark;'), - # M5 work nodes are firmware-cached again. - 'm5-cached-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', 'UAT_PGSZ'), - # M5 compute descriptors are firmware-cached again. - 'm5-cached-descriptors': ('policy-compute', 'if alloc.uat.is_m5() { 0 } else { size }', 'size'), + # Work nodes lose their firmware-cached prefix (the linux#3170 light-submission cost). + 'uncached-nodes': ('policy-context', 'Family::WorkState,\n 2 * UAT_PGSZ,\n UAT_PGSZ,', + 'Family::WorkState,\n 2 * UAT_PGSZ,\n 0,'), + # Compute descriptors lose their firmware-cached prefix. + 'uncached-descriptors': ('policy-compute', 'Family::Descriptor,\n size,\n size,', + 'Family::Descriptor,\n size,\n 0,'), # Render queue records, which the host retargets in place, are firmware-cached again. 'cached-queue-records': ('policy-memory', 'GRAPH_SIZE,\n 0,\n', 'GRAPH_SIZE,\n 0x8000,\n'), - # G17P work nodes lose their cached prefix (the linux#3170 light-submission cost). - 'uncached-g17p-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', '0'), + # M5 scheduler pages, which are zeroed and reinitialised on reuse, are firmware-cached again. + 'cached-scheduler': ('policy-context', 'Family::Scheduler,\n UAT_PGSZ,\n 0,', + 'Family::Scheduler,\n UAT_PGSZ,\n UAT_PGSZ,'), } @@ -839,14 +842,13 @@ def need(text, pattern, what): if not re.search(pattern, text): failures.append(what) - # Work nodes: uncached on M5, the node page cached on G17P; the counter page stays uncached. - need(context, r'pool\.allocate\(\s*alloc,\s*Family::WorkState,\s*2 \* UAT_PGSZ,\s*' - r'if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ UAT_PGSZ \},', 'work nodes: M5 uncached, G17P node page cached') + # Work nodes: the node page is cached on every G17; the counter page stays uncached. + need(context, r'pool\.allocate\(\s*alloc,\s*Family::WorkState,\s*2 \* UAT_PGSZ,\s*UAT_PGSZ,', + 'work nodes: node page cached') # M5 scheduler pages, which are zeroed and reinitialised on reuse, stay uncached. need(context, r'Family::Scheduler,\s*UAT_PGSZ,\s*0,', 'M5 scheduler pages uncached') - # Compute descriptors: uncached on M5, cached on G17P. - need(compute, r'Family::Descriptor,\s*size,\s*if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ size \},', - 'compute descriptors: M5 uncached, G17P cached') + # Compute descriptors: cached on every G17. + need(compute, r'Family::Descriptor,\s*size,\s*size,', 'compute descriptors cached') # The compute graph, whose queue record is rebound in place, is an ordinary uncached allocation. need(compute, r'let mut graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', 'compute graph uncached') @@ -881,7 +883,7 @@ def main(): if failures: return 1 print('cache policy: in-place rewritten records uncached everywhere; work nodes and compute descriptors ' - 'uncached on M5 and cached on G17P') + 'cached on every G17') if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): return 0 From fd63223418b5d377485f34ea09c31446c25d3909 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 27 Nov 2026 09:45:12 -0500 Subject: [PATCH 2/7] drm/asahi: g17: harden cached work-node and descriptor reuse across recovery and stop Close the forced-stop, recovery, and full-pool fence-overrun gaps for firmware-cached Family::WorkState and compute Family::Descriptor objects: 1. Never overrun a pool fence for firmware-cached objects (prefix != 0) in Pool::allocate: when all 64 slots of a cached family are active or waiting behind their control-ring fence, allocate a fresh unpooled (uncached) object instead of zeroing a cached object whose prior owner's release the firmware has not yet consumed. 2. In Context::retain_linked_work, retain the cached WorkState via retain_until_stop(pool) whenever the context was killed (kill_published) or its VM failed (status != 0), even if the work list head is empty, so aborted work without stamped completion never returns its cached node page to the reuse pool before firmware stop. 3. In Firmware::service_compute_pools, retain a compute queue's cached DescriptorRing via Queue::retain_ring_until_stop(&self.pool) whenever recycle_killed or recycle_quarantined_idle recycles a queue after a kill or quarantine, so its ring leaves the reuse cache until firmware stop instead of returning to Pool on vacate. 4. Sync tools/asahi/run-host-tests.py with the g17-object-fence-tests.py mutation names and add host unit and mutation coverage for cached fence overruns, killed/failed work-state retention, and recycled compute descriptor-ring retention. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/context.rs | 21 ++- drivers/gpu/drm/asahi/g17/object.rs | 14 +- drivers/gpu/drm/asahi/g17/queue/compute.rs | 22 ++- drivers/gpu/drm/asahi/g17/runtime.rs | 5 +- tools/asahi/g17-object-fence-tests.py | 184 ++++++++++++++++----- tools/asahi/run-host-tests.py | 10 +- 6 files changed, 191 insertions(+), 65 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 12a7333a3dc17..41711bcf9e825 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -314,12 +314,15 @@ impl Context { let scheduler = Arc::new(scheduler, GFP_KERNEL)?; // Both firmware and host write work nodes (reused every 63 submissions // and zeroed on pool reuse). Map the node page firmware-cached on all - // G17 (G17P and M5): the host rewrites a node only after - // `WorkStorage::drained` has read the firmware's final `completed` - // count from memory, and zeroes a returned object only once its pool - // fence is met, so it never rewrites a node the firmware is still - // updating. The counter page, which the host writes on every kick, - // stays uncached. + // G17 (G17P and M5): within a healthy context a node slot is rewritten + // only after every command holding its `WorkStateLease` has retired + // with post-maintenance completion stamps (or after `WorkStorage::drained` + // observed `completed >= submitted` from memory on stampless render + // fallback). Across contexts, `Pool::allocate` never overruns a pool + // fence for firmware-cached objects, and `retain_linked_work` keeps a + // killed, failed, or still-linked context's work storage out of pool + // reuse until firmware stop. The counter page, which the host writes on + // every kick, stays uncached. let mut object = pool.allocate( alloc, Family::WorkState, @@ -530,8 +533,12 @@ impl Context { /// cursor snapshot that proved the release consumed, so the witness already covers it. pub(crate) fn retain_linked_work(&self, pool: &Arc) -> bool { // An unreadable head counts as linked: retaining is the safe side. + // A killed context or failed VM may also leave firmware-cached work + // nodes dirty after aborted work without a normal stamped completion: + // keep the storage out of reuse until firmware stop even if the list + // head is empty. let linked = self.work_head().map_or(true, |head| head != [0, self.work_head_address()]); - if linked { + if linked || self.kill_published() || self.status.get() != 0 { self.work.lock().object.retain_until_stop(pool); } else if let Some(mark) = &self.work_mark { mark.released(super::channel::control_witnessed()); diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index b2b935e9e7dae..7e2f5905198c5 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -735,9 +735,10 @@ impl Pool { /// The firmware may still follow a previous owner's pointers into a returned object /// until it has processed that owner's release. Reuse takes the matching object /// returned longest ago once its fence is met (see `return_object`); a younger one is - /// reused only when the family has no room for a fresh pooled object, because an - /// unpooled one is unmapped as soon as its owner drops it. On the A18 Pro a work state is - /// never reused before its fence: with no room, a fresh one stays unpooled instead. + /// reused only when the family has no room for a fresh pooled object and the object + /// is uncached, because an unpooled one is unmapped as soon as its owner drops it. + /// Firmware-cached objects (`prefix != 0`), and A18 Pro work states, are never reused + /// before their fence: with no room, a fresh one stays unpooled (and uncached) instead. pub(crate) fn allocate( self: &kernel::sync::Arc, alloc: &Allocator<'_>, @@ -751,8 +752,11 @@ impl Pool { let begin = family_index * POOL_SLOTS; let witnessed = super::channel::control_witnessed(); // On the A18 Pro a cached work state carries a ReturnMark, allocated before an entry is - // taken so that a failure loses no returned object, and is never reused before its fence. + // taken so that a failure loses no returned object. Firmware-cached objects (`prefix != 0`) + // are also never reused before their fence: zeroing one while a previous owner's release + // is unconsumed risks a delayed firmware writeback reverting host writes. let marked = self.after_release && family == Family::WorkState; + let no_overrun = marked || prefix != 0; let mark = if marked { Some(kernel::sync::Arc::new(ReturnMark::new(), GFP_KERNEL)?) } else { @@ -783,7 +787,7 @@ impl Pool { } } match oldest { - Some((index, _, ready)) if ready || (!room && !marked) => { + Some((index, _, ready)) if ready || (!room && !no_overrun) => { if !ready { inner.fence_overruns[family_index] += 1; } diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 952da690e5238..866401727ceed 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -110,11 +110,15 @@ impl DescriptorRing { /// an accounting word near the end of each descriptor (`+0xfac` on M5), /// and the host rewrites each slot every 32 kicks. Map the ring /// firmware-cached on all G17 (G17P and M5), as for render descriptors: - /// the host rewrites a slot only after the kick that last used it retired - /// (at most `DESCRIPTORS` kicks are in flight), by when that kick's - /// accounting store is in memory. The hardware reads the same pages - /// through an uncached canonical low alias; on M5 the kernel mapping, in - /// the upper half every execution context includes, is firmware-only. + /// within a healthy queue the host rewrites a slot only after the kick that + /// last used it retired (`IN_FLIGHT <= DESCRIPTORS`, with post-maintenance + /// completion stamps mandatory on M5). Across queues, `Pool::allocate` + /// never overruns a pool fence for firmware-cached objects, and any queue + /// recycled after a kill or quarantine retains its descriptor ring until + /// firmware stop (`Queue::retain_ring_until_stop`) instead of returning it + /// to the reuse pool. The hardware reads the same pages through an uncached + /// canonical low alias; on M5 the kernel mapping, in the upper half every + /// execution context includes, is firmware-only. pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc) -> Result { let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; let object = objects.allocate( @@ -2275,6 +2279,14 @@ impl Queue { self.recycle_settled()?; Ok(true) } + /// Keeps this queue's descriptor ring mapped and out of pool reuse until + /// firmware stop, for queues recycled after a kill or quarantine where + /// aborted commands did not complete with post-maintenance stamps. + pub(crate) fn retain_ring_until_stop(&mut self, pool: &Arc) { + if let Some(ring) = self.graph.ring.as_mut() { + ring.object.retain_until_stop(pool); + } + } fn recycle_settled(&mut self) -> Result { self.graph.reset_items()?; self.config_cache = None; diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index e64a10eb7d945..cd60212ed9468 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -4258,8 +4258,9 @@ impl super::Firmware { .filter_map(|entry| entry.queue.as_deref_mut()) { let busy = !queue.channel_free(); - queue.recycle_killed()?; - queue.recycle_quarantined_idle()?; + if queue.recycle_killed()? || queue.recycle_quarantined_idle()? { + queue.retain_ring_until_stop(&self.pool); + } if deferred.vacated_room() { if let Some(vacated) = queue.take_recycled_ring() { deferred.defer_vacated(vacated); diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index b7c289e2eb6cd..f6ec075e3de20 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -10,13 +10,17 @@ - A18 Pro (`after_release`): a work state its context never exposed comes back with fence 0; one whose owner's release was consumed with an empty work list comes back with that witness; one a record or command may name, or that a - retained queue record named, keeps `control_fence()`. A full work-state - family with only waiting entries hands out an uncached object instead of - reusing one, and counts it. -- Without `after_release` (M4, M5) every decision, and the snapshot counts, + retained queue record named, keeps `control_fence()`. +- Firmware-cached families (`prefix != 0`, work states and descriptors on every + G17) never overrun a waiting pool fence when full: they hand out a fresh + unpooled/uncached object instead and count it. +- Uncached pooled objects (`prefix == 0`) without `after_release` (M4, M5) match the pool before linux#1978 (BASE) on the same random operations. -- Source rules: every accessor that hands the address to the firmware marks it, - and only the release path of `retain_linked_work` marks it released. +- Source & recovery rules: every accessor that hands the address to the + firmware marks it; only the clean release path of `retain_linked_work` marks + it released; a killed context or failed VM retains its work state until + firmware stop even with an empty work list; a compute queue recycled after a + kill or quarantine retains its descriptor ring until firmware stop. - Cache policy (linux#3170 and follow-ups): records the host rewrites in place (render queue records, the compute graph, M5 scheduler pages) stay uncached on every G17; work nodes and compute descriptors keep their @@ -39,8 +43,10 @@ BASE = 'fc050503ffcd1032cd1590fb30252eb5a722a5a5' MUTATIONS = { - # Work states may overrun a fence again when their family is full. - 'overrun-work-states': ('object', 'if ready || (!room && !marked) => {', 'if ready || !room => {'), + # Work states and cached objects may overrun a fence again when their family is full. + 'overrun-work-states': ('object', 'if ready || (!room && !no_overrun) => {', 'if ready || !room => {'), + # Firmware-cached objects on non-after_release GPUs (M5) overrun their fence again. + 'overrun-cached-prefix': ('object', 'let no_overrun = marked || prefix != 0;', 'let no_overrun = marked;'), # An unseen work state keeps the strict fence. 'unseen-strict': ('object', 'Self::UNSEEN => (RETURN_UNSEEN, 0),', 'Self::UNSEEN => (RETURN_UNSEEN, super::channel::control_fence()),'), @@ -51,6 +57,21 @@ 'node-unmarked': ('context', ' self.context.expose_work();\n', ''), # A consumed release with an empty list does not mark the work state. 'no-release': ('context', 'mark.released(super::channel::control_witnessed());', 'let _ = mark;'), + # A killed context with an empty list returns its cached work state to the pool. + 'reuse-killed-work-state': ('context', 'if linked || self.kill_published() || self.status.get() != 0 {', + 'if linked || self.status.get() != 0 {'), + # A failed VM with an empty list returns its cached work state to the pool. + 'reuse-failed-work-state': ('context', 'if linked || self.kill_published() || self.status.get() != 0 {', + 'if linked || self.kill_published() {'), + # A compute queue recycled after kill/quarantine returns its cached descriptor ring to the pool. + 'reuse-recycled-descriptor-ring': ( + 'policy-runtime', + ' if queue.recycle_killed()? || queue.recycle_quarantined_idle()? {\n' + ' queue.retain_ring_until_stop(&self.pool);\n' + ' }', + ' queue.recycle_killed()?;\n' + ' queue.recycle_quarantined_idle()?;', + ), # Work nodes lose their firmware-cached prefix (the linux#3170 light-submission cost). 'uncached-nodes': ('policy-context', 'Family::WorkState,\n 2 * UAT_PGSZ,\n UAT_PGSZ,', 'Family::WorkState,\n 2 * UAT_PGSZ,\n 0,'), @@ -158,13 +179,19 @@ def context_source(text): impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } pub mod mmu { + use std::cell::Cell; pub type Prot = u8; pub const UAT_PGSZ: usize = 0x4000; + thread_local! { + pub static ZERO_PREFIX_CALLS: Cell = const { Cell::new(0) }; + } pub struct KernelMapping { pub iova: u64 } impl KernelMapping { pub fn iova(&self) -> u64 { self.iova } pub unsafe fn set_fw_cached_prefix(&self, prefix: usize) -> (crate::Result<[u64; 2]>, bool) { - assert!(prefix > 0, "set_fw_cached_prefix must not be called for prefix == 0"); + if prefix == 0 { + ZERO_PREFIX_CALLS.with(|c| c.set(c.get() + 1)); + } (Ok([0; 2]), true) } } @@ -249,13 +276,13 @@ def context_source(text): ops } -/// Size and cached prefix per family; `variant` 3 gives descriptors a second size. +/// Size and uncached prefix per family for BASE parity; `variant` 3 gives descriptors a second size. pub fn geometry(family: usize, variant: usize) -> (usize, usize) { let page = mmu::UAT_PGSZ; match family { - 0 if variant == 3 => (2 * page, page), - 1 => (2 * page, page), - _ => (page, page), + 0 if variant == 3 => (2 * page, 0), + 1 => (2 * page, 0), + _ => (page, 0), } } @@ -419,6 +446,8 @@ def context_source(text): pool.stop_after_firmware(); assert!(unmapped(kept_id)); assert!(unmapped(ws_id)); + assert_eq!(mmu::ZERO_PREFIX_CALLS.with(|c| c.get()), 0, + "set_fw_cached_prefix must not be called for prefix == 0"); } println!("uncached pooled: prefix == 0 skips firmware caching while keeping fencing, reuse and retention"); } @@ -506,8 +535,10 @@ def context_source(text): println!("return classes: unseen 0, released at its witness, exposed or retained control_fence()"); } - /// A full work-state family whose returned entries all wait leaves a new one uncached on - /// the A18 Pro, and overruns the oldest without after_release, as before. + /// A full cached work-state or descriptor family (`prefix > 0`) whose returned entries + /// all wait leaves a new one unpooled/uncached on every G17 (`after_release` true or false), + /// never overrunning a fence. Uncached pooled families (`prefix == 0`) still overrun without + /// `after_release`, matching BASE. pub fn full_family() { for after_release in [true, false] { let next = Cell::new(1); @@ -521,24 +552,24 @@ def context_source(text): if let Some(mark) = object.return_mark() { mark.expose(); } } let waiting: Vec<_> = live.drain(..POOL_SLOTS / 2).collect(); - let oldest = waiting[0].id; drop(waiting); let s = snapshot(&pool); assert_eq!(crate::count(&s, "cached_objects_1 ", "waiting="), 32, "{s}"); assert_eq!(crate::count(&s, "cached_objects_1 ", "used="), 64, "{s}"); let object = work_state(&pool, &alloc); let s = snapshot(&pool); + assert!(object.lease.is_none(), + "a cached work state is never reused before its fence (after_release={after_release})"); + assert_eq!(object.id, 65); + assert_eq!(crate::count(&s, "cached_objects_1 ", "overruns="), 0, "{s}"); + assert_eq!(crate::count(&s, "cached_objects_1 ", "uncached="), 1, "{s}"); + assert_eq!(crate::count(&s, "cached_objects_1 ", "returned="), 32, "{s}"); + assert!(object.return_mark().is_none(), "an uncached work state has no mark"); + let id = object.id; + drop(object); + assert!(unmapped(id), "an uncached object is unmapped when dropped"); + assert_eq!(crate::count(&snapshot(&pool), "cached_objects_1 ", "returned="), 32); if after_release { - assert!(object.lease.is_none(), "an A18 Pro work state is not reused before its fence"); - assert_eq!(object.id, 65); - assert_eq!(crate::count(&s, "cached_objects_1 ", "overruns="), 0, "{s}"); - assert_eq!(crate::count(&s, "cached_objects_1 ", "uncached="), 1, "{s}"); - assert_eq!(crate::count(&s, "cached_objects_1 ", "returned="), 32, "{s}"); - assert!(object.return_mark().is_none(), "an uncached work state has no mark"); - let id = object.id; - drop(object); - assert!(unmapped(id), "an uncached object is unmapped when dropped"); - assert_eq!(crate::count(&snapshot(&pool), "cached_objects_1 ", "returned="), 32); // An entry whose fence is met is still reused when the family is full. let ready = live.pop().unwrap(); ready.return_mark().unwrap().released(7); @@ -546,26 +577,44 @@ def context_source(text): drop(ready); assert_eq!(work_state(&pool, &alloc).id, id, "a met fence is reused in a full family"); } else { - assert!(object.lease.is_some()); - assert_eq!(object.id, oldest, "without after_release the oldest waiting object is overrun"); - assert_eq!(crate::count(&s, "cached_objects_1 ", "overruns="), 1, "{s}"); - assert_eq!(crate::count(&s, "cached_objects_1 ", "uncached="), 0, "{s}"); assert_eq!(returns(&pool), [0, 0, 0], "work-state classes are counted on the A18 Pro only"); + // Cached descriptors never overrun their fence either. + let mut desc_live: Vec<_> = (0..POOL_SLOTS).map(|_| descriptor(&pool, &alloc)).collect(); + let desc_waiting: Vec<_> = desc_live.drain(..POOL_SLOTS / 2).collect(); + drop(desc_waiting); + let fresh_desc = descriptor(&pool, &alloc); + let s = snapshot(&pool); + assert!(fresh_desc.lease.is_none(), "a cached descriptor is never reused before its fence"); + assert_eq!(crate::count(&s, "cached_objects_0 ", "overruns="), 0, "{s}"); + assert_eq!(crate::count(&s, "cached_objects_0 ", "uncached="), 1, "{s}"); + // Uncached pooled objects (prefix == 0) still overrun when full without after_release. + let mut qs_live: Vec<_> = (0..POOL_SLOTS).map(|_| { + pool.allocate(&alloc, Family::QueueState, mmu::UAT_PGSZ, 0, 0, CpuMap::WriteCombined).unwrap() + }).collect(); + let qs_waiting: Vec<_> = qs_live.drain(..POOL_SLOTS / 2).collect(); + let oldest = qs_waiting[0].id; + drop(qs_waiting); + let overrun = pool.allocate(&alloc, Family::QueueState, mmu::UAT_PGSZ, 0, 0, CpuMap::WriteCombined).unwrap(); + assert!(overrun.lease.is_some()); + assert_eq!(overrun.id, oldest, "uncached pooled objects still overrun when full without after_release"); + let s = snapshot(&pool); + assert_eq!(crate::count(&s, "cached_objects_2 ", "overruns="), 1, "{s}"); } } - // Descriptors on the A18 Pro still overrun in a full family, as #1978 left them. + // Cached descriptors on the A18 Pro never overrun in a full family either. let next = Cell::new(1); let alloc = Allocator { next: &next }; let pool = Pool::new(true).unwrap(); crate::channel::set(10, 7); let mut live: Vec<_> = (0..POOL_SLOTS).map(|_| descriptor(&pool, &alloc)).collect(); let returned: Vec<_> = live.drain(..POOL_SLOTS / 2).collect(); - let oldest = returned[0].id; drop(returned); - assert_eq!(descriptor(&pool, &alloc).id, oldest, "a full descriptor family overruns its oldest entry"); + let fresh = descriptor(&pool, &alloc); + assert!(fresh.lease.is_none(), "a full cached descriptor family stays uncached instead of overrunning"); let s = snapshot(&pool); - assert_eq!(crate::count(&s, "cached_objects_0 ", "overruns="), 1, "{s}"); - println!("full family: A18 Pro work states are left uncached and counted, never overrun; others unchanged"); + assert_eq!(crate::count(&s, "cached_objects_0 ", "overruns="), 0, "{s}"); + assert_eq!(crate::count(&s, "cached_objects_0 ", "uncached="), 1, "{s}"); + println!("full family: firmware-cached work states and descriptors never overrun on any G17; uncached pooled unchanged"); } #[derive(Clone, Copy, PartialEq, Debug)] @@ -677,6 +726,12 @@ def context_source(text): pub struct SchedulerStorage; pub mod mmu { pub struct ContextHold; } pub struct QosLease; + pub struct VmStatus(core::sync::atomic::AtomicI32); + impl VmStatus { + fn new() -> Self { Self(core::sync::atomic::AtomicI32::new(0)) } + fn get(&self) -> i32 { self.0.load(Ordering::Acquire) } + fn fail(&self, err: i32) { self.0.store(err, Ordering::Release); } + } pub struct WorkStorage { pub object: PooledObject } @PAGES@ pub struct Context { @@ -686,11 +741,14 @@ def context_source(text): scheduler: Arc, hold: Arc, qos: Arc, + kill_published: core::sync::atomic::AtomicBool, + status: Arc, /// The work-list head the firmware left. head: Cell<[u64; 2]>, } impl Context { fn work_head(&self) -> Result<[u64; 2]> { Ok(self.head.get()) } + fn kill_published(&self) -> bool { self.kill_published.load(Ordering::Acquire) } @METHODS@ } pub struct WorkStateLease { context: Arc, word: core::sync::atomic::AtomicU32 } @@ -705,6 +763,8 @@ def context_source(text): let context = Arc::new(Context { work: Arc::new(Mutex::new(WorkStorage { object })), work_base, work_mark, scheduler: Arc::new(SchedulerStorage), hold: Arc::new(mmu::ContextHold), qos: Arc::new(QosLease), + kill_published: core::sync::atomic::AtomicBool::new(false), + status: Arc::new(VmStatus::new()), head: Cell::new([0, work_base + (UAT_PGSZ + 0x400) as u64]), }); (context, id) @@ -767,8 +827,40 @@ def context_source(text): drop(context); assert_eq!(super::fence(&pool, Family::WorkState, id), None, "linked work is kept"); assert!(!unmapped(id)); + + // A killed context with an empty list keeps its cached work state until stop. + let (context, killed_id) = new_context(&pool, &alloc); + let _ = context.work_head_va(); + context.kill_published.store(true, Ordering::Release); + assert!(!context.retain_linked_work(&pool)); + drop(context); + assert_eq!(super::fence(&pool, Family::WorkState, killed_id), None, + "a killed context's work state is kept out of reuse until stop"); + assert!(!unmapped(killed_id)); + + // A failed VM (recovery/fault) with an empty list keeps its cached work state until stop. + let (context, failed_id) = new_context(&pool, &alloc); + let _ = context.work_head_va(); + context.status.fail(-5); + assert!(!context.retain_linked_work(&pool)); + drop(context); + assert_eq!(super::fence(&pool, Family::WorkState, failed_id), None, + "a failed VM's work state is kept out of reuse until stop"); + assert!(!unmapped(failed_id)); + + // Even after advancing the control fence, a fresh allocation never reuses kept work states. + crate::channel::set(100, 100); + let next_ws = super::work_state(&pool, &alloc); + assert_ne!(next_ws.id, id); + assert_ne!(next_ws.id, killed_id); + assert_ne!(next_ws.id, failed_id); + drop(next_ws); + + pool.stop_after_firmware(); + assert!(unmapped(id) && unmapped(killed_id) && unmapped(failed_id), + "kept work states are unmapped once firmware stops"); } - println!("context: records, commands and retained records mark the work state; a consumed release with an empty list releases it"); + println!("context: records, commands and retained records mark the work state; killed/failed/linked contexts retain until stop"); } } } @@ -813,9 +905,10 @@ def source_rules(context, observation, tree): assert context.count('object.gpu_va()') == 2 assert 'let work_base = object.gpu_va();' in context assert 'fw::WorkNode::new(self.object.gpu_va() + counter as u64, word)' in context - # A release is marked only where retain_linked_work found the list empty. + # A release is marked only where retain_linked_work found a clean, unkilled, empty-list context. linked = block(context, ' pub(crate) fn retain_linked_work(') - assert re.search(r'if linked \{\n\s+self\.work\.lock\(\)\.object\.retain_until_stop\(pool\);\n' + assert re.search(r'if linked \|\| self\.kill_published\(\) \|\| self\.status\.get\(\) != 0 \{\n' + r'\s+self\.work\.lock\(\)\.object\.retain_until_stop\(pool\);\n' r'\s+\} else if let Some\(mark\) = &self\.work_mark \{\n' r'\s+mark\.released\(super::channel::control_witnessed\(\)\);', linked), linked assert context.count('.released(') == 1 and context.count('.retain()') == 1 @@ -834,8 +927,8 @@ def source_rules(context, observation, tree): print('source: records and commands mark the work state; only a consumed empty-list release releases it') -def cache_policy(context, compute, memory): - """The firmware-cached prefix each pooled G17 object family gets. Returns the failures.""" +def cache_policy(context, compute, memory, runtime): + """The firmware-cached prefix and recovery retention policy each pooled G17 object family gets.""" failures = [] def need(text, pattern, what): @@ -849,6 +942,12 @@ def need(text, pattern, what): need(context, r'Family::Scheduler,\s*UAT_PGSZ,\s*0,', 'M5 scheduler pages uncached') # Compute descriptors: cached on every G17. need(compute, r'Family::Descriptor,\s*size,\s*size,', 'compute descriptors cached') + # A compute queue recycled after kill or quarantine retains its descriptor ring until stop. + need(compute, r'pub\(crate\) fn retain_ring_until_stop\(&mut self, pool: &Arc\) \{\s*' + r'if let Some\(ring\) = self\.graph\.ring\.as_mut\(\) \{\s*' + r'ring\.object\.retain_until_stop\(pool\);', 'compute retain_ring_until_stop helper') + need(runtime, r'if queue\.recycle_killed\(\)\? \|\| queue\.recycle_quarantined_idle\(\)\? \{\s*' + r'queue\.retain_ring_until_stop\(&self\.pool\);', 'recycled compute queues retain descriptor ring until stop') # The compute graph, whose queue record is rebound in place, is an ordinary uncached allocation. need(compute, r'let mut graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', 'compute graph uncached') @@ -873,11 +972,12 @@ def main(): source_rules(ctx, observation, DRIVER) policy = {'context': ctx, 'compute': (DRIVER / 'g17/queue/compute.rs').read_text(), - 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text()} + 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text(), + 'runtime': (DRIVER / 'g17/runtime.rs').read_text()} if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): where, old, new = MUTATIONS[args.mutation] policy[where[len('policy-'):]] = replace(policy[where[len('policy-'):]], old, new) - failures = cache_policy(policy['context'], policy['compute'], policy['memory']) + failures = cache_policy(policy['context'], policy['compute'], policy['memory'], policy['runtime']) for failure in failures: print(f'FAIL line 0: cache policy: {failure}') if failures: diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a20d283737988..5231ae8e97922 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -359,10 +359,12 @@ def mutations(flag, names, base, expect=KILL): 'g17-growth-gate-tests.py': [([], PASS)], 'g17-growth-tests.py': [([], PASS)], 'g17-object-fence-tests.py': [([], PASS)] - + mutations('--mutation', ('overrun-work-states', 'unseen-strict', 'retain-not-sticky', - 'node-unmarked', 'no-release', 'm5-cached-nodes', - 'm5-cached-descriptors', 'cached-queue-records', - 'uncached-g17p-nodes'), []), + + mutations('--mutation', ('overrun-work-states', 'overrun-cached-prefix', 'unseen-strict', + 'retain-not-sticky', 'node-unmarked', 'no-release', + 'reuse-killed-work-state', 'reuse-failed-work-state', + 'reuse-recycled-descriptor-ring', 'uncached-nodes', + 'uncached-descriptors', 'cached-queue-records', + 'cached-scheduler'), []), 'g17-owner-release-order-tests.py': [([], PASS)], 'g17-pool-release-tests.py': [([], PASS)], # no-drain-release is the old rule: only a lease ends a slot's quarantine. From b9979d514796626550bc7ab0b9637e7f8c060dae Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 27 Nov 2026 14:16:35 -0500 Subject: [PATCH 3/7] drm/asahi: g17: retain work-state lease across stampless render retirement On stampless render retirement, retiring the submission via Deferred::Retired releases Submission::state.work while Active still keeps the descriptor slot with stamps_owed = true waiting for post-maintenance completion stamps. With firmware-cached WorkNode pages, releasing WorkStateLease early allows the same context to rewrite the node slot before firmware completion stamps witness cache writeback; the host cannot rely on WorkStorage::drained() (which reads WorkNode.completed on the cached node page) to order writeback of the rest of the 0xc8-byte node. Keep WorkStateLease on Active::stamps_owed_work before deferring Deferred::Retired when stampless is true so the work-node slot stays pinned until post-maintenance completion stamps pop the Active entry. If a stamps_owed group is instead released through pair-wide drain in release_witnessed(), mark the context stampless_drained so Context::retain_linked_work() retains the work storage via retain_until_stop() until firmware stop. Update the Context::new comment to reflect that cached work-node reuse is always gated by post-maintenance completion stamps or firmware stop, and extend g17-object-fence-tests.py, g17-quarantine-drain-tests.py, and run-host-tests.py with host checks and mutations covering both invariants. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/context.rs | 42 +++++++++++++----- drivers/gpu/drm/asahi/g17/queue/render.rs | 23 +++++++--- tools/asahi/g17-object-fence-tests.py | 53 +++++++++++++++++++---- tools/asahi/g17-quarantine-drain-tests.py | 8 +++- tools/asahi/run-host-tests.py | 4 +- 5 files changed, 101 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 41711bcf9e825..e332e6d5ab2fb 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -214,6 +214,9 @@ pub(crate) struct Context { /// A kill of this context was published, through a compute queue or on its render pairs' /// behalf. A context is killed at most once. kill_published: AtomicBool, + /// A stampless-retired render group of this context was later released through pair-wide + /// drain instead of observing post-maintenance completion stamps. + stampless_drained: AtomicBool, /// The host's recovery generation when it first saw the kill of this context done (its /// scheduler page's killed state), `u64::MAX` before ([`Self::restarted_since_kill`]). kill_seen: AtomicU64, @@ -316,13 +319,13 @@ impl Context { // and zeroed on pool reuse). Map the node page firmware-cached on all // G17 (G17P and M5): within a healthy context a node slot is rewritten // only after every command holding its `WorkStateLease` has retired - // with post-maintenance completion stamps (or after `WorkStorage::drained` - // observed `completed >= submitted` from memory on stampless render - // fallback). Across contexts, `Pool::allocate` never overruns a pool - // fence for firmware-cached objects, and `retain_linked_work` keeps a - // killed, failed, or still-linked context's work storage out of pool - // reuse until firmware stop. The counter page, which the host writes on - // every kick, stays uncached. + // with post-maintenance completion stamps (including stampless render, + // where `Active` retains `WorkStateLease` until those stamps arrive). + // Across contexts, `Pool::allocate` never overruns a pool fence for + // firmware-cached objects, and `retain_linked_work` keeps a killed, + // failed, stampless-drained, or still-linked context's work storage + // out of pool reuse until firmware stop. The counter page, which the + // host writes on every kick, stays uncached. let mut object = pool.allocate( alloc, Family::WorkState, @@ -369,6 +372,7 @@ impl Context { scheduler_generation, published: AtomicBool::new(false), kill_published: AtomicBool::new(false), + stampless_drained: AtomicBool::new(false), kill_seen: AtomicU64::new(u64::MAX), closed_generation: AtomicU64::new(u64::MAX), closed_for_open_client: AtomicBool::new(false), @@ -533,12 +537,16 @@ impl Context { /// cursor snapshot that proved the release consumed, so the witness already covers it. pub(crate) fn retain_linked_work(&self, pool: &Arc) -> bool { // An unreadable head counts as linked: retaining is the safe side. - // A killed context or failed VM may also leave firmware-cached work - // nodes dirty after aborted work without a normal stamped completion: - // keep the storage out of reuse until firmware stop even if the list - // head is empty. + // A killed context, stampless-drained render context, or failed VM may + // leave firmware-cached work nodes dirty without a normal stamped + // completion: keep the storage out of reuse until firmware stop even if + // the list head is empty. let linked = self.work_head().map_or(true, |head| head != [0, self.work_head_address()]); - if linked || self.kill_published() || self.status.get() != 0 { + if linked + || self.kill_published() + || self.stampless_drained() + || self.status.get() != 0 + { self.work.lock().object.retain_until_stop(pool); } else if let Some(mark) = &self.work_mark { mark.released(super::channel::control_witnessed()); @@ -590,6 +598,16 @@ impl Context { self.kill_published.load(Ordering::Acquire) } + /// Record that a stampless-retired render group was released via pair-wide drain. + pub(crate) fn note_stampless_drain(&self) { + self.stampless_drained.store(true, Ordering::Release); + } + + /// A stampless-retired render group of this context was released via pair-wide drain. + pub(crate) fn stampless_drained(&self) -> bool { + self.stampless_drained.load(Ordering::Acquire) + } + /// This context's queue closed at the host's recovery `generation`, under the device mutex: /// by its client (`release_queue`), or on its behalf once a GPU recovery failed its VM as /// guilty (`Firmware::close_failed_owners`). Only the first close counts. A close notes it diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 27dbcaab8ce7e..ae343e460f4d0 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -175,9 +175,11 @@ struct Active { /// First observation of this group executed and consumed while its stamps lagged. stamp_wait_since: Option, /// The group retired on its pass record without completion stamps and its client has its - /// result, but the firmware may still store the stamps through its descriptor: the - /// descriptor slot stays held until stamps cover the group. + /// result, but the firmware may still store the stamps through its descriptor and hold + /// dirty cache lines on its work node: both the descriptor slot and `stamps_owed_work` + /// stay held until stamps cover the group. stamps_owed: bool, + stamps_owed_work: Option>, } /// A firmware-retired, unexecuted group must hold on two observations this far @@ -1280,6 +1282,7 @@ impl Pair { abandoned_since: None, stamp_wait_since: None, stamps_owed: false, + stamps_owed_work: None, }) .map_err(|_| EBUSY)?; self.prepared = None; @@ -2313,14 +2316,20 @@ impl Pair { &front.packet, [timestamps[0], timestamps[3]], ); + if stampless { + // Retain the work-state lease before Deferred::Retired releases the + // submission's own lease: the pass record does not witness cache + // writeback on the firmware-cached work node. + front.stamps_owed_work = Some(front.packet.completion.work_state()?); + } defer(Deferred::Retired( front.packet.completion.clone(), front.packet.check_firmware_producers().map(|()| timestamps), ))?; if stampless { - // The pass record is no witness that the firmware is done with the descriptor: it - // can still store the completion stamps through it, and a reused slot names no - // stamp target. Keep the slot until stamps cover the group. + // The pass record is no witness that the firmware is done with the descriptor or + // its work node: it can still store the completion stamps through it, and a reused + // slot names no stamp target. Keep both until stamps cover the group. front.stamps_owed = true; return Ok(true); } @@ -2888,7 +2897,9 @@ impl Pair { // A group retired on its pass record was reported then (`stamps_owed`): the pair-wide // proof above covers its stamps too (or the kill of its context), so only its // descriptor is released. It has no drained result of its own. - if !active.stamps_owed { + if active.stamps_owed { + active.packet.context.note_stampless_drain(); + } else { let result = active.drained_result.ok_or(EIO)?; defer(Deferred::Drained(active.packet.completion.clone(), result))?; } diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index f6ec075e3de20..1bd1f0e3e44bc 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -58,11 +58,26 @@ # A consumed release with an empty list does not mark the work state. 'no-release': ('context', 'mark.released(super::channel::control_witnessed());', 'let _ = mark;'), # A killed context with an empty list returns its cached work state to the pool. - 'reuse-killed-work-state': ('context', 'if linked || self.kill_published() || self.status.get() != 0 {', - 'if linked || self.status.get() != 0 {'), + 'reuse-killed-work-state': ('context', + ' || self.kill_published()\n', ''), + # A stampless-drained context with an empty list returns its cached work state to the pool. + 'reuse-stampless-drained-work-state': ('context', + ' || self.stampless_drained()\n', ''), # A failed VM with an empty list returns its cached work state to the pool. - 'reuse-failed-work-state': ('context', 'if linked || self.kill_published() || self.status.get() != 0 {', - 'if linked || self.kill_published() {'), + 'reuse-failed-work-state': ('context', + ' || self.status.get() != 0\n', ''), + # Stampless render drops its WorkStateLease before completion stamps arrive. + 'drop-stampless-work-lease': ( + 'policy-render', + ' front.stamps_owed_work = Some(front.packet.completion.work_state()?);\n', + '', + ), + # Pair-wide drain of a stampless render group fails to mark the context stampless-drained. + 'drop-stampless-drain-mark': ( + 'policy-render', + ' active.packet.context.note_stampless_drain();\n', + '', + ), # A compute queue recycled after kill/quarantine returns its cached descriptor ring to the pool. 'reuse-recycled-descriptor-ring': ( 'policy-runtime', @@ -742,6 +757,7 @@ def context_source(text): hold: Arc, qos: Arc, kill_published: core::sync::atomic::AtomicBool, + stampless_drained: core::sync::atomic::AtomicBool, status: Arc, /// The work-list head the firmware left. head: Cell<[u64; 2]>, @@ -749,6 +765,7 @@ def context_source(text): impl Context { fn work_head(&self) -> Result<[u64; 2]> { Ok(self.head.get()) } fn kill_published(&self) -> bool { self.kill_published.load(Ordering::Acquire) } + fn stampless_drained(&self) -> bool { self.stampless_drained.load(Ordering::Acquire) } @METHODS@ } pub struct WorkStateLease { context: Arc, word: core::sync::atomic::AtomicU32 } @@ -764,6 +781,7 @@ def context_source(text): work: Arc::new(Mutex::new(WorkStorage { object })), work_base, work_mark, scheduler: Arc::new(SchedulerStorage), hold: Arc::new(mmu::ContextHold), qos: Arc::new(QosLease), kill_published: core::sync::atomic::AtomicBool::new(false), + stampless_drained: core::sync::atomic::AtomicBool::new(false), status: Arc::new(VmStatus::new()), head: Cell::new([0, work_base + (UAT_PGSZ + 0x400) as u64]), }); @@ -838,6 +856,16 @@ def context_source(text): "a killed context's work state is kept out of reuse until stop"); assert!(!unmapped(killed_id)); + // A stampless-drained render context with an empty list keeps its cached work state until stop. + let (context, stampless_id) = new_context(&pool, &alloc); + let _ = context.work_head_va(); + context.stampless_drained.store(true, Ordering::Release); + assert!(!context.retain_linked_work(&pool)); + drop(context); + assert_eq!(super::fence(&pool, Family::WorkState, stampless_id), None, + "a stampless-drained context's work state is kept out of reuse until stop"); + assert!(!unmapped(stampless_id)); + // A failed VM (recovery/fault) with an empty list keeps its cached work state until stop. let (context, failed_id) = new_context(&pool, &alloc); let _ = context.work_head_va(); @@ -853,6 +881,7 @@ def context_source(text): let next_ws = super::work_state(&pool, &alloc); assert_ne!(next_ws.id, id); assert_ne!(next_ws.id, killed_id); + assert_ne!(next_ws.id, stampless_id); assert_ne!(next_ws.id, failed_id); drop(next_ws); @@ -907,7 +936,7 @@ def source_rules(context, observation, tree): assert 'fw::WorkNode::new(self.object.gpu_va() + counter as u64, word)' in context # A release is marked only where retain_linked_work found a clean, unkilled, empty-list context. linked = block(context, ' pub(crate) fn retain_linked_work(') - assert re.search(r'if linked \|\| self\.kill_published\(\) \|\| self\.status\.get\(\) != 0 \{\n' + assert re.search(r'if linked\s+\|\| self\.kill_published\(\)\s+\|\| self\.stampless_drained\(\)\s+\|\| self\.status\.get\(\) != 0\s+\{\n' r'\s+self\.work\.lock\(\)\.object\.retain_until_stop\(pool\);\n' r'\s+\} else if let Some\(mark\) = &self\.work_mark \{\n' r'\s+mark\.released\(super::channel::control_witnessed\(\)\);', linked), linked @@ -927,7 +956,7 @@ def source_rules(context, observation, tree): print('source: records and commands mark the work state; only a consumed empty-list release releases it') -def cache_policy(context, compute, memory, runtime): +def cache_policy(context, compute, memory, runtime, render): """The firmware-cached prefix and recovery retention policy each pooled G17 object family gets.""" failures = [] @@ -955,6 +984,12 @@ def need(text, pattern, what): failures.append('compute graph not pooled') # Render queue records, retargeted and bound to work slots in place, stay uncached. need(memory, r'Family::QueueState,\s*GRAPH_SIZE,\s*0,\s*prot,', 'render queue records uncached') + # Stampless render retains its WorkStateLease until post-maintenance stamps arrive, + # and marks the context stampless-drained if released via pair-wide drain instead. + need(render, r'if stampless \{[^}]*front\.stamps_owed_work = Some\(front\.packet\.completion\.work_state\(\)\?\);[^}]*\}\s*defer\(Deferred::Retired\(', + 'stampless render retains WorkStateLease across stamps_owed') + need(render, r'if active\.stamps_owed \{\s*active\.packet\.context\.note_stampless_drain\(\);', + 'stampless render drain retains WorkState until stop') return failures @@ -973,11 +1008,13 @@ def main(): policy = {'context': ctx, 'compute': (DRIVER / 'g17/queue/compute.rs').read_text(), 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text(), - 'runtime': (DRIVER / 'g17/runtime.rs').read_text()} + 'runtime': (DRIVER / 'g17/runtime.rs').read_text(), + 'render': (DRIVER / 'g17/queue/render.rs').read_text()} if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): where, old, new = MUTATIONS[args.mutation] policy[where[len('policy-'):]] = replace(policy[where[len('policy-'):]], old, new) - failures = cache_policy(policy['context'], policy['compute'], policy['memory'], policy['runtime']) + failures = cache_policy(policy['context'], policy['compute'], policy['memory'], + policy['runtime'], policy['render']) for failure in failures: print(f'FAIL line 0: cache policy: {failure}') if failures: diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index a86e6e957069b..a42da01f79719 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -204,7 +204,11 @@ def fixture(): } ''' + command + '\n}\n' + item(completion, 'pub(crate) enum Deferred {') + '\n' + item(completion, 'impl Deferred {') + r''' -pub struct Packet { completion: Arc } +pub struct Context { stampless_drained: AtomicBool } +impl Context { + fn note_stampless_drain(&self) { self.stampless_drained.store(true, Ordering::Release); } +} +pub struct Packet { completion: Arc, context: Context } pub struct Ticket { ordinal: u64 } pub struct Active { packet: Arc, @@ -312,7 +316,7 @@ def fixture(): } fn firmware(pool: &Arc, commands: &[(&Command, u64)]) -> Firmware { let active = commands.iter().map(|(command, ordinal)| Active { - packet: Arc::new(Packet { completion: command.completion.clone() }), + packet: Arc::new(Packet { completion: command.completion.clone(), context: Context { stampless_drained: AtomicBool::new(false) } }), ticket: Ticket { ordinal: *ordinal }, stamps_owed: false, failed: false, flist_completed: false, drained_result: None, }).collect(); diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 5231ae8e97922..3061e662f9257 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -361,7 +361,9 @@ def mutations(flag, names, base, expect=KILL): 'g17-object-fence-tests.py': [([], PASS)] + mutations('--mutation', ('overrun-work-states', 'overrun-cached-prefix', 'unseen-strict', 'retain-not-sticky', 'node-unmarked', 'no-release', - 'reuse-killed-work-state', 'reuse-failed-work-state', + 'reuse-killed-work-state', 'reuse-stampless-drained-work-state', + 'reuse-failed-work-state', 'drop-stampless-work-lease', + 'drop-stampless-drain-mark', 'reuse-recycled-descriptor-ring', 'uncached-nodes', 'uncached-descriptors', 'cached-queue-records', 'cached-scheduler'), []), From 55f4a282137236cda262a0693068ffa74e2f94d6 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Fri, 27 Nov 2026 15:15:40 -0500 Subject: [PATCH 4/7] drm/asahi: g17: pin unstamped-drained work-state slots against same-context reuse When an unstamped render drain (pair-wide drain in release_witnessed(), fail_dropped(), settle_interrupted_front(), fail_after_observation(), or failing replay_abandoned()) releases an active group without per-node post-maintenance completion stamps, setting stampless_drained on the context protects cross-context pool reuse in retain_linked_work() but still let Drop for WorkStateLease return the slot index to WorkStates for a later submission in the same context. Add WorkStates::pin() and WorkStateLease::pin_until_stop() so every unstamped drain path permanently keeps that slot index out of WorkStates::allocate() for the rest of the context's life (while clearing live[index] to FREE so older_live() never stalls, decrementing held[engine] to avoid may_take() starvation, releasing shared claims for sibling contexts, and returning EIO from acquire() if all 63 slots are ever pinned) and still sets stampless_drained for cross-context retention until firmware stop. Extend g17-object-fence-tests.py, g17-quarantine-drain-tests.py, run-host-tests.py, and identity.rs KUnit tests to cover same-context pinning and its negative-control mutations. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/context.rs | 41 ++++++- drivers/gpu/drm/asahi/g17/context/identity.rs | 90 ++++++++++++++- drivers/gpu/drm/asahi/g17/queue/render.rs | 35 +++++- tools/asahi/g17-object-fence-tests.py | 108 ++++++++++++++++-- tools/asahi/g17-quarantine-drain-tests.py | 27 ++++- tools/asahi/run-host-tests.py | 2 +- 6 files changed, 281 insertions(+), 22 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index e332e6d5ab2fb..053e9b94f096c 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -317,11 +317,13 @@ impl Context { let scheduler = Arc::new(scheduler, GFP_KERNEL)?; // Both firmware and host write work nodes (reused every 63 submissions // and zeroed on pool reuse). Map the node page firmware-cached on all - // G17 (G17P and M5): within a healthy context a node slot is rewritten - // only after every command holding its `WorkStateLease` has retired - // with post-maintenance completion stamps (including stampless render, - // where `Active` retains `WorkStateLease` until those stamps arrive). - // Across contexts, `Pool::allocate` never overruns a pool fence for + // G17 (G17P and M5): within a context a node slot is rewritten only + // after every command holding its `WorkStateLease` has retired with + // post-maintenance completion stamps (including stampless render, where + // `Active` retains `WorkStateLease` until those stamps arrive; any + // unstamped drain pins the slot via `WorkStateLease::pin_until_stop` so + // later submissions in the same context never acquire it). Across + // contexts, `Pool::allocate` never overruns a pool fence for // firmware-cached objects, and `retain_linked_work` keeps a killed, // failed, stampless-drained, or still-linked context's work storage // out of pool reuse until firmware stop. The counter page, which the @@ -747,6 +749,9 @@ pub(crate) struct WorkStateLease { word: AtomicU32, /// Index of the engine whose admission took the node, valid once `word` is set. engine: AtomicU8, + /// Retired through an unstamped drain: keep the slot out of same-context + /// reuse when this lease drops instead of returning it to `WorkStates`. + pinned: AtomicBool, /// The ioctl's place in its context's submission order. ordinal: u64, } @@ -761,6 +766,7 @@ impl WorkStateLease { context, word: AtomicU32::new(FREE), engine: AtomicU8::new(0), + pinned: AtomicBool::new(false), ordinal, }) } @@ -783,6 +789,9 @@ impl WorkStateLease { if !order.admits(self.ordinal) { return Err(EBUSY); } + if self.context.states.exhausted() { + return Err(EIO); + } let engine = engine.index(); let candidate = self.context.states.allocate(engine).ok_or(EBUSY)?; if let Err(error) = work.initialize(candidate) { @@ -885,12 +894,25 @@ impl WorkStateLease { .payload(pair, ordinal) .ok_or(EINVAL) } + /// Keeps this lease's work-state slot out of reuse within its context and + /// retains the context's work storage out of pool reuse until firmware stop. + /// Used on unstamped drain paths whose cached work node may still hold dirty + /// firmware cache lines. + pub(crate) fn pin_until_stop(&self) { + self.pinned.store(true, Ordering::Release); + self.context.note_stampless_drain(); + } } impl Drop for WorkStateLease { fn drop(&mut self) { let word = self.word(); if word != FREE { - self.context.release_state(word, usize::from(self.engine.load(Ordering::Relaxed))); + let engine = usize::from(self.engine.load(Ordering::Relaxed)); + if self.pinned.load(Ordering::Acquire) { + self.context.pin_state(word, engine); + } else { + self.context.release_state(word, engine); + } } else if self.context.order.lock().leave(self.ordinal) { self.context.pass_turn(); } @@ -905,6 +927,13 @@ impl Context { self.state_returns.notify(); } } + /// Retires a slot without returning its index to `allocate`: decrementing + /// `held[engine]` may still satisfy `may_take(1, 0)` for a waiting engine. + fn pin_state(&self, word: u32, engine: usize) { + if self.states.pin(word, engine) { + self.state_returns.notify(); + } + } /// A refused publisher waits on its engine's domain. Bumping both once the turn moved past a /// refusal means one that sampled before its refused acquire() never sleeps through it. fn pass_turn(&self) { diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index fabed7ae649d3..78447b4808e21 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -30,6 +30,13 @@ pub(super) const fn may_take(free: usize, held: u32) -> bool { pub(super) struct WorkStates { next: AtomicU32, live: [AtomicU32; 64], + /// Slots retired without post-maintenance completion stamps (for example + /// stampless render groups released via pair-wide drain or recovery-dropped + /// groups). A pinned slot stays out of `allocate` for the rest of this + /// context's life so the host never rewrites a cached work node the firmware + /// may still hold dirty; `live[index]` returns to `FREE` so `older_live` + /// never stalls behind it. + pinned: AtomicU64, /// Nodes taken by each engine's admissions and not yet released. held: [AtomicU32; ENGINES], /// Indices claimed by every context sharing this one's execution context @@ -43,6 +50,7 @@ impl WorkStates { // 0x17c8.. 0x17ea on the J813). next: AtomicU32::new(0x40), live: [const { AtomicU32::new(FREE) }; 64], + pinned: AtomicU64::new(0), held: [const { AtomicU32::new(0) }; ENGINES], claims: None, } @@ -51,6 +59,12 @@ impl WorkStates { pub(super) fn shared(claims: Arc) -> Self { Self { claims: Some(claims), ..Self::new() } } + /// Every slot of this context is pinned out of reuse, so no future release + /// can ever free one. + pub(super) fn exhausted(&self) -> bool { + let mask = (1u64 << STATE_COUNT) - 1; + (self.pinned.load(Ordering::Acquire) & mask).count_ones() as usize >= STATE_COUNT + } /// Takes a node for `engine`, or none when [`may_take`] refuses. Callers serialize /// allocations of one context; releases may run concurrently. pub(super) fn allocate(&self, engine: usize) -> Option { @@ -58,14 +72,20 @@ impl WorkStates { if !may_take(STATE_COUNT.saturating_sub(self.used()), held.load(Ordering::Acquire)) { return None; } + let pinned = self.pinned.load(Ordering::Acquire); for _ in 0..64 { let word = self.next.fetch_add(1, Ordering::Relaxed); let index = (word & 63) as usize; if index != STATE_COUNT + && (pinned & (1u64 << index)) == 0 && self.live[index] .compare_exchange(FREE, word, Ordering::AcqRel, Ordering::Acquire) .is_ok() { + if (self.pinned.load(Ordering::Acquire) & (1u64 << index)) != 0 { + self.live[index].store(FREE, Ordering::Release); + continue; + } if let Some(claims) = &self.claims { if claims.fetch_or(1 << index, Ordering::AcqRel) & (1 << index) != 0 { self.live[index].store(FREE, Ordering::Release); @@ -94,6 +114,31 @@ impl WorkStates { } released } + /// Retires `word` while keeping its slot index out of reuse for the rest of + /// this context's life (cross-context pool reuse is separately prevented by + /// `Context::retain_linked_work`). + pub(super) fn pin(&self, word: u32, engine: usize) -> bool { + let index = (word & 63) as usize; + if index == STATE_COUNT || self.live[index].load(Ordering::Acquire) != word { + return false; + } + let mask = 1u64 << index; + // Set `pinned` before clearing `live[index]` so a concurrent `allocate` + // cannot observe `FREE` without also observing the pin bit. + self.pinned.fetch_or(mask, Ordering::AcqRel); + let pinned = self.live[index] + .compare_exchange(word, FREE, Ordering::AcqRel, Ordering::Acquire) + .is_ok(); + if pinned { + if let Some(claims) = &self.claims { + claims.fetch_and(!mask, Ordering::AcqRel); + } + if let Some(held) = self.held.get(engine) { + held.fetch_sub(1, Ordering::AcqRel); + } + } + pinned + } } /// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the @@ -283,10 +328,18 @@ impl WorkStates { } pub(super) fn used(&self) -> usize { + let pinned = self.pinned.load(Ordering::Acquire); if let Some(claims) = &self.claims { - return claims.load(Ordering::Acquire).count_ones() as usize; + return (claims.load(Ordering::Acquire) | pinned).count_ones() as usize; } - self.live.iter().filter(|word| word.load(Ordering::Acquire) != FREE).count() + self.live + .iter() + .enumerate() + .filter(|&(i, word)| { + i != STATE_COUNT + && (word.load(Ordering::Acquire) != FREE || (pinned & (1u64 << i)) != 0) + }) + .count() } } impl RenderSlots { @@ -411,4 +464,37 @@ mod tests { // An engine outside the table takes nothing. assert!(states.allocate(ENGINES).is_none()); } + + #[test] + fn pinned_slot_is_never_reused_and_never_stalls_older_live() { + let states = WorkStates::new(); + let first = states.allocate(0).unwrap(); + let pinned_index = first & 63; + let second = states.allocate(0).unwrap(); + assert_eq!(states.older_live(second), Some(first)); + assert!(states.pin(first, 0)); + assert!(!states.pin(first, 0)); + assert_eq!(states.older_live(second), None); + assert_eq!(states.used(), 2); + assert_eq!(states.held[0].load(Ordering::Acquire), 1); + assert!(states.release(second, 0)); + assert_eq!(states.used(), 1); + assert_eq!(states.held[0].load(Ordering::Acquire), 0); + // Cycling well past STATE_COUNT never hands back the pinned slot. + for _ in 0..(STATE_COUNT * 3) { + let word = states.allocate(0).unwrap(); + assert_ne!(word & 63, pinned_index); + assert!(states.release(word, 0)); + } + assert!(!states.exhausted()); + // Pinning the remaining slots exhausts the context cleanly. + for _ in 1..STATE_COUNT { + let word = states.allocate(0).unwrap(); + assert!(states.pin(word, 0)); + } + assert!(states.exhausted()); + assert_eq!(states.used(), STATE_COUNT); + assert!(states.allocate(0).is_none()); + assert!(states.allocate(1).is_none()); + } } diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index ae343e460f4d0..deeaa3384ee12 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -2509,6 +2509,11 @@ impl Pair { if failing { // decide() replays only innocent groups that never ran: like `fail_dropped`, // they fail without poisoning their VM. Restarts other VMs caused dropped them. + if let Ok(work) = packet.completion.work_state() { + work.pin_until_stop(); + } else { + packet.context.note_stampless_drain(); + } packet.completion.classify(recovery::Class::Spared); defer(Deferred::Retired(packet.completion.clone(), Err(ENODATA)))?; self.memory.retire(ordinal)?; @@ -2555,6 +2560,11 @@ impl Pair { } let ordinal = front.ticket.ordinal; let completion = front.packet.completion.clone(); + if let Ok(work) = completion.work_state() { + work.pin_until_stop(); + } else { + front.packet.context.note_stampless_drain(); + } completion.classify(recovery::Class::Spared); defer(Deferred::Retired(completion, Err(ENODATA)))?; self.memory.retire(ordinal)?; @@ -2633,6 +2643,11 @@ impl Pair { ordinal ); let packet = self.active.front().ok_or(EIO)?.packet.clone(); + if let Ok(work) = packet.completion.work_state() { + work.pin_until_stop(); + } else { + packet.context.note_stampless_drain(); + } defer(Deferred::Retired(packet.completion.clone(), Err(ECANCELED)))?; self.memory.retire(ordinal)?; self.active.pop().ok_or(EIO)?; @@ -2895,11 +2910,20 @@ impl Pair { } while let Some(active) = self.active.front() { // A group retired on its pass record was reported then (`stamps_owed`): the pair-wide - // proof above covers its stamps too (or the kill of its context), so only its - // descriptor is released. It has no drained result of its own. + // drain does not deliver per-node post-maintenance stamps, so pin its work-state slot + // against same-context reuse and retain the context's work storage until firmware stop. if active.stamps_owed { - active.packet.context.note_stampless_drain(); + if let Some(work) = &active.stamps_owed_work { + work.pin_until_stop(); + } else { + active.packet.context.note_stampless_drain(); + } } else { + if let Ok(work) = active.packet.completion.work_state() { + work.pin_until_stop(); + } else { + active.packet.context.note_stampless_drain(); + } let result = active.drained_result.ok_or(EIO)?; defer(Deferred::Drained(active.packet.completion.clone(), result))?; } @@ -3009,6 +3033,11 @@ impl Pair { active.ticket.ordinal, left ); + if let Ok(work) = active.packet.completion.work_state() { + work.pin_until_stop(); + } else { + active.packet.context.note_stampless_drain(); + } defer(Deferred::Retired( active.packet.completion.clone(), Err(if spared { ECANCELED } else { EIO }), diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 1bd1f0e3e44bc..dcedebc1eb8ee 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -72,10 +72,20 @@ ' front.stamps_owed_work = Some(front.packet.completion.work_state()?);\n', '', ), - # Pair-wide drain of a stampless render group fails to mark the context stampless-drained. - 'drop-stampless-drain-mark': ( + # Pair-wide drain of a stampless render group fails to pin its work-state lease. + 'drop-stampless-drain-pin': ( 'policy-render', + ' if let Some(work) = &active.stamps_owed_work {\n' + ' work.pin_until_stop();\n' + ' } else {\n' + ' active.packet.context.note_stampless_drain();\n' + ' }\n', ' active.packet.context.note_stampless_drain();\n', + ), + # WorkStates::pin forgets to record the pin bit, allowing same-context reuse after unstamped drain. + 'same-context-reuse-pinned-slot': ( + 'identity', + ' self.pinned.fetch_or(mask, Ordering::AcqRel);\n', '', ), # A compute queue recycled after kill/quarantine returns its cached descriptor ring to the pool. @@ -142,6 +152,17 @@ def context_source(text): return pages, methods, node +def identity_source(text): + """Extract the real WorkStates allocator, pin, older_live, used, and may_take from context/identity.rs.""" + consts = '\n'.join(re.search(r'^pub\(super\) const ' + name + r': [^;]+;', text, re.M).group(0) + for name in ['FREE', 'STATE_COUNT', 'ENGINES']) + may_take = block(text, 'pub(super) const fn may_take(') + struct = block(text, 'pub(super) struct WorkStates {') + impl1 = block(text, 'impl WorkStates {') + impl2 = block(text, 'impl WorkStates {', text.index('impl WorkStates {') + 1) + return '\n'.join([consts, may_take, struct, impl1, impl2]) + + PRELUDE = r''' #![allow(dead_code, unused_imports, unused_variables, unused_mut, unused_unsafe, unused_macros)] #![allow(private_interfaces, private_bounds)] @@ -240,7 +261,12 @@ def context_source(text): } } -pub mod channel { +pub mod identity { + use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + use std::sync::Arc; +@IDENTITY@ +} +mod channel { use core::sync::atomic::{AtomicU64, Ordering}; @CHANNEL@ /// Sets the published and consumed control-record counts. @@ -894,7 +920,60 @@ def context_source(text): } } +fn work_states_pin_prevents_same_context_reuse() { + use crate::identity::{WorkStates, STATE_COUNT}; + let states = WorkStates::new(); + let drained = states.allocate(0).expect("initial render slot"); + let drained_slot = drained & 63; + let newer = states.allocate(0).expect("newer slot"); + assert_eq!(states.older_live(newer), Some(drained)); + assert!(states.pin(drained, 0), "pinning a live slot succeeds once"); + assert!(!states.pin(drained, 0), "double pin is a no-op"); + assert_eq!(states.older_live(newer), None, "pinned slot must not stall older_live"); + assert_eq!(states.used(), 2, "pinned slot stays counted in used()"); + assert!(states.release(newer, 0)); + assert_eq!(states.used(), 1); + for _ in 0..(STATE_COUNT * 4) { + let w = states.allocate(0).expect("same-context submission"); + assert_ne!(w & 63, drained_slot, "same-context submission re-acquired pinned slot"); + assert!(states.release(w, 0)); + } + for _ in 1..(STATE_COUNT - 2) { + let w = states.allocate(0).expect("slot to pin"); + assert!(states.pin(w, 0)); + } + let r = states.allocate(0).expect("render takes 1 of 2 remaining"); + let c = states.allocate(1).expect("compute takes last remaining"); + assert!(states.release(r, 0)); + assert!(states.release(c, 1)); + for _ in 0..2 { + let w = states.allocate(0).expect("final slot to pin"); + assert!(states.pin(w, 0)); + } + assert!(states.exhausted(), "all 63 slots pinned must report exhausted()"); + assert!(states.allocate(0).is_none()); + assert!(states.allocate(1).is_none()); + let claims = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); + let ctx_a = WorkStates::shared(claims.clone()); + let ctx_b = WorkStates::shared(claims.clone()); + let wa = ctx_a.allocate(0).expect("shared ctx_a slot"); + let sa = wa & 63; + assert!(ctx_a.pin(wa, 0)); + assert_eq!(claims.load(std::sync::atomic::Ordering::Acquire) & (1u64 << sa), 0, + "pinned slot releases shared work-key claim for sibling context"); + assert_eq!(ctx_a.used(), 1, "pinning context still accounts for its pinned slot"); + for _ in 0..(STATE_COUNT * 2) { + let w = ctx_a.allocate(0).expect("shared ctx_a retry"); + assert_ne!(w & 63, sa, "shared context re-acquired its own pinned slot"); + assert!(ctx_a.release(w, 0)); + } + let wb = ctx_b.allocate(0).expect("sibling ctx_b slot"); + assert!(ctx_b.release(wb, 0)); + println!("same-context WorkStates pin: pinned slot never re-acquired, older_live unblocked, exhaustion clean"); +} + fn main() { + work_states_pin_prevents_same_context_reuse(); now::uncached_pooled(); now::return_classes(); now::full_family(); @@ -985,11 +1064,23 @@ def need(text, pattern, what): # Render queue records, retargeted and bound to work slots in place, stay uncached. need(memory, r'Family::QueueState,\s*GRAPH_SIZE,\s*0,\s*prot,', 'render queue records uncached') # Stampless render retains its WorkStateLease until post-maintenance stamps arrive, - # and marks the context stampless-drained if released via pair-wide drain instead. + # and every unstamped drain path pins the slot via pin_until_stop() (same-context + cross-context). need(render, r'if stampless \{[^}]*front\.stamps_owed_work = Some\(front\.packet\.completion\.work_state\(\)\?\);[^}]*\}\s*defer\(Deferred::Retired\(', 'stampless render retains WorkStateLease across stamps_owed') - need(render, r'if active\.stamps_owed \{\s*active\.packet\.context\.note_stampless_drain\(\);', - 'stampless render drain retains WorkState until stop') + need(render, r'if active\.stamps_owed \{\s*if let Some\(work\) = &active\.stamps_owed_work \{\s*work\.pin_until_stop\(\);', + 'stampless render drain pins WorkStateLease until stop') + need(render, r'fn fail_dropped\([\s\S]*?work\.pin_until_stop\(\);', + 'fail_dropped pins WorkStateLease until stop') + need(render, r'fn settle_interrupted_front\([\s\S]*?work\.pin_until_stop\(\);', + 'settle_interrupted_front pins WorkStateLease until stop') + need(render, r'fn fail_after_observation\([\s\S]*?work\.pin_until_stop\(\);', + 'fail_after_observation pins WorkStateLease until stop') + need(context, r'pub\(crate\) fn pin_until_stop\(&self\) \{\s*self\.pinned\.store\(true, Ordering::Release\);\s*self\.context\.note_stampless_drain\(\);\s*\}', + 'WorkStateLease::pin_until_stop sets pinned and stampless_drained') + need(context, r'if self\.pinned\.load\(Ordering::Acquire\) \{\s*self\.context\.pin_state\(word, engine\);', + 'WorkStateLease::drop pins slot on unstamped drain') + need(context, r'if self\.context\.states\.exhausted\(\) \{\s*return Err\(EIO\);\s*\}', + 'WorkStateLease::acquire fails cleanly when all slots are pinned') return failures @@ -1026,17 +1117,20 @@ def main(): now = pool_source(obj) pages, methods, node = context_source(ctx) + ident = identity_source((DRIVER / 'g17/context/identity.rs').read_text()) if args.mutation: where, old, new = MUTATIONS[args.mutation] if where == 'object': now = replace(now, old, new) + elif where == 'identity': + ident = replace(ident, old, new) else: methods, node = (replace(methods, old, new), node) if old in methods else (methods, replace(node, old, new)) channel = '\n'.join(re.search(r'(?ms)^(?:///[^\n]*\n)*static ' + name + r': AtomicU64 = AtomicU64::new\(0\);', chan).group(0) for name in ['CONTROL_PUBLISHED', 'CONTROL_CONSUMED']) channel += '\n' + '\n'.join(block(chan, 'pub(crate) fn ' + name + '()') for name in ['control_fence', 'control_published', 'control_witnessed']) - code = (PRELUDE.replace('@CHANNEL@', channel).replace('@BASE@', pool_source(base)).replace('@NOW@', now) + code = (PRELUDE.replace('@CHANNEL@', channel).replace('@IDENTITY@', ident).replace('@BASE@', pool_source(base)).replace('@NOW@', now) .replace('@PAGES@', pages).replace('@METHODS@', methods).replace('@NODE@', node)) with tempfile.TemporaryDirectory() as work: diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index a42da01f79719..7feb5bb24f77f 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -183,6 +183,7 @@ def fixture(): signalled: AtomicBool, accepted: AtomicBool, spared: AtomicBool, + work: Arc, result: Mutex>>, } fn discarded(error: Error) -> bool { error == ECANCELED || error == ENODATA } @@ -192,6 +193,7 @@ def fixture(): fn status(&self) -> &Arc { &self.status } fn report(&self, _: Error) {} fn signal_terminal(&self, result: Result<[u64; 4]>) { *self.result.lock() = Some(result); } + fn work_state(&self) -> Result> { Ok(self.work.clone()) } /// The lease handling of the real complete_with_compute (checked against it above). fn complete(&self, result: Result<[u64; 4]>) -> bool { self.complete_with_compute(result, None) } fn complete_with_compute(&self, result: Result<[u64; 4]>, _: Option<[u64; 2]>) -> bool { @@ -208,12 +210,23 @@ def fixture(): impl Context { fn note_stampless_drain(&self) { self.stampless_drained.store(true, Ordering::Release); } } -pub struct Packet { completion: Arc, context: Context } +pub struct WorkStateLease { + context: Arc, + pinned: AtomicBool, +} +impl WorkStateLease { + fn pin_until_stop(&self) { + self.pinned.store(true, Ordering::Release); + self.context.note_stampless_drain(); + } +} +pub struct Packet { completion: Arc, context: Arc } pub struct Ticket { ordinal: u64 } pub struct Active { packet: Arc, ticket: Ticket, stamps_owed: bool, + stamps_owed_work: Option>, failed: bool, flist_completed: bool, drained_result: Option>, @@ -305,20 +318,23 @@ def fixture(): let pin = Arc::new(Mutex::new(None)); let vm = Arc::new(AtomicBool::new(false)); let guard = VmJobGuard { pool: pool.clone(), slot: lease.slot(), quarantined: pin.clone(), vm: vm.clone() }; + let context = Arc::new(Context { stampless_drained: AtomicBool::new(false) }); + let work = Arc::new(WorkStateLease { context, pinned: AtomicBool::new(false) }); let completion = Arc::new(Completion { status: Arc::new(Status), output: Output, sources: Some(Arc::new(Sources)), vm_job: Mutex::new(Some(guard)), render: Mutex::new(Some(lease)), is_compute: false, signalled: AtomicBool::new(false), accepted: AtomicBool::new(true), spared: AtomicBool::new(false), + work, result: Mutex::new(None), }); Command { completion, pin, vm } } fn firmware(pool: &Arc, commands: &[(&Command, u64)]) -> Firmware { let active = commands.iter().map(|(command, ordinal)| Active { - packet: Arc::new(Packet { completion: command.completion.clone(), context: Context { stampless_drained: AtomicBool::new(false) } }), + packet: Arc::new(Packet { completion: command.completion.clone(), context: command.completion.work.context.clone() }), ticket: Ticket { ordinal: *ordinal }, - stamps_owed: false, failed: false, flist_completed: false, drained_result: None, + stamps_owed: false, stamps_owed_work: None, failed: false, flist_completed: false, drained_result: None, }).collect(); let pair = Pair { quarantined: false, active: Ring(active), terminal: None, memory: Memory { retired: Vec::new() }, drain_failures: 0, drain_retry_at: 0, guilty_released: false, @@ -330,6 +346,7 @@ def fixture(): fn stampless_retirement(firmware: &mut Firmware, deferred: &mut DeferredBatch) { let front = firmware.pair.as_mut().unwrap().active.front_mut().unwrap(); front.flist_completed = true; + front.stamps_owed_work = Some(front.packet.completion.work_state().unwrap()); deferred.push(Deferred::Retired(front.packet.completion.clone(), Ok(TICKS))).unwrap(); front.stamps_owed = true; } @@ -416,6 +433,10 @@ def fixture(): pool.release_owner(OWNER); firmware.host.drained = true; firmware.release_drained_render(usize::from(slot), &mut deferred).unwrap(); + assert!(command.completion.work.pinned.load(Ordering::Acquire), + "pair-wide drain pins the stampless work-state lease against same-context reuse"); + assert!(command.completion.work.context.stampless_drained.load(Ordering::Acquire), + "pair-wide drain marks the context stampless-drained for cross-context retention"); assert!(quarantined(&pool, slot), "a lease of the slot is still held"); assert_ne!(pool.state.lock().drained & bit(slot), 0); deferred.finish(); diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 3061e662f9257..85eaa19d02b75 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -363,7 +363,7 @@ def mutations(flag, names, base, expect=KILL): 'retain-not-sticky', 'node-unmarked', 'no-release', 'reuse-killed-work-state', 'reuse-stampless-drained-work-state', 'reuse-failed-work-state', 'drop-stampless-work-lease', - 'drop-stampless-drain-mark', + 'drop-stampless-drain-pin', 'same-context-reuse-pinned-slot', 'reuse-recycled-descriptor-ring', 'uncached-nodes', 'uncached-descriptors', 'cached-queue-records', 'cached-scheduler'), []), From ae0f996aa8c497b05f38bec986373117f52cad44 Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 29 Nov 2026 03:04:16 -0500 Subject: [PATCH 5/7] drm/asahi: g17: read live work states before the pin mask in WorkStates::used() WorkStates::used() loaded the pin mask first and then each slot's live word (or the shared claims). pin() sets the pin bit and then clears the live word and the claim. A pin landing between used()'s two reads made its slot look free: neither live nor pinned. With one genuinely free slot and the requesting engine already holding a node, may_take() then saw two free slots and let that engine take the last one, which is reserved for its peer. Read the live words, or the claims, first and the pin mask after them. pin() publishes its bit before the release that clears the word, so an acquire load that sees the cleared word or claim also sees the bit. g17-object-fence-tests.py hooks used()'s pin-mask load to run a pin() right after it, on a private and on a shared context, and checks that the requesting engine is still refused the peer's last node. The used-pin-first and used-pin-first-shared mutations restore the old read order and fail it. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/context/identity.rs | 19 +++--- tools/asahi/g17-object-fence-tests.py | 61 ++++++++++++++++++- tools/asahi/run-host-tests.py | 1 + 3 files changed, 72 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index 78447b4808e21..3ca3719c8105c 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -327,19 +327,22 @@ impl WorkStates { .min_by_key(|&live| live.wrapping_sub(word) as i32) } + /// Slots in use, pinned ones included. The live words (or the shared claims) are read + /// before the pin mask: `pin` sets its bit before it clears the slot's live word and + /// claim, so a slot a concurrent `pin` has just freed is seen pinned here, never free. pub(super) fn used(&self) -> usize { - let pinned = self.pinned.load(Ordering::Acquire); if let Some(claims) = &self.claims { - return (claims.load(Ordering::Acquire) | pinned).count_ones() as usize; + let claimed = claims.load(Ordering::Acquire); + return (claimed | self.pinned.load(Ordering::Acquire)).count_ones() as usize; } - self.live + let live = self + .live .iter() .enumerate() - .filter(|&(i, word)| { - i != STATE_COUNT - && (word.load(Ordering::Acquire) != FREE || (pinned & (1u64 << i)) != 0) - }) - .count() + .filter(|&(i, word)| i != STATE_COUNT && word.load(Ordering::Acquire) != FREE) + .fold(0u64, |mask, (i, _)| mask | (1u64 << i)); + let pinned = self.pinned.load(Ordering::Acquire) & !(1u64 << STATE_COUNT); + (live | pinned).count_ones() as usize } } impl RenderSlots { diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index ee8682b346f7b..c0a0c9f617184 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -102,6 +102,11 @@ ' }\n', ' active.packet.context.note_stampless_drain();\n', ), + # WorkStates::used reads the pin mask before the live words (or the shared claims), so a slot + # a concurrent pin just freed counts as free and may_take lets an engine take its peer's last + # node (linux#3389 review). + 'used-pin-first': ('identity', ' let live = self\n .live\n .iter()\n .enumerate()\n .filter(|&(i, word)| i != STATE_COUNT && word.load(Ordering::Acquire) != FREE)\n .fold(0u64, |mask, (i, _)| mask | (1u64 << i));\n let pinned = crate::race::pinned_load(&self.pinned) & !(1u64 << STATE_COUNT);\n', ' let pinned = crate::race::pinned_load(&self.pinned) & !(1u64 << STATE_COUNT);\n let live = self\n .live\n .iter()\n .enumerate()\n .filter(|&(i, word)| i != STATE_COUNT && word.load(Ordering::Acquire) != FREE)\n .fold(0u64, |mask, (i, _)| mask | (1u64 << i));\n'), + 'used-pin-first-shared': ('identity', ' let claimed = claims.load(Ordering::Acquire);\n return (claimed | crate::race::pinned_load(&self.pinned)).count_ones() as usize;\n', ' let pinned = crate::race::pinned_load(&self.pinned);\n return (claims.load(Ordering::Acquire) | pinned).count_ones() as usize;\n'), # WorkStates::pin forgets to record the pin bit, allowing same-context reuse after unstamped drain. 'same-context-reuse-pinned-slot': ( 'identity', @@ -180,7 +185,16 @@ def identity_source(text): struct = block(text, 'pub(super) struct WorkStates {') impl1 = block(text, 'impl WorkStates {') impl2 = block(text, 'impl WorkStates {', text.index('impl WorkStates {') + 1) - return '\n'.join([consts, may_take, struct, impl1, impl2]) + return hook_used('\n'.join([consts, may_take, struct, impl1, impl2])) + + +def hook_used(ident): + """Route used()'s pin-mask loads through crate::race, which can run a scheduled pin() + right after the load: a concurrent pin landing between used()'s reads.""" + start = ident.index(' pub(super) fn used(&self) -> usize {') + end = ident.index('\n }\n', start) + len('\n }\n') + body = ident[start:end].replace('self.pinned.load(Ordering::Acquire)', 'crate::race::pinned_load(&self.pinned)') + return ident[:start] + body + ident[end:] PRELUDE = r''' @@ -293,6 +307,22 @@ def identity_source(text): } } +pub mod race { + use core::sync::atomic::{AtomicU64, Ordering}; + use std::cell::RefCell; + thread_local! { static AFTER: RefCell>> = RefCell::new(None); } + /// Runs `f` once, right after the next pin-mask load in `WorkStates::used`. + pub fn after_next_pin_load(f: impl FnOnce() + 'static) { + AFTER.with(|a| *a.borrow_mut() = Some(Box::new(f))); + } + pub fn pinned_load(pinned: &AtomicU64) -> u64 { + let value = pinned.load(Ordering::Acquire); + if let Some(f) = AFTER.with(|a| a.borrow_mut().take()) { + f(); + } + value + } +} pub mod identity { use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; use std::sync::Arc; @@ -1057,6 +1087,34 @@ def identity_source(text): } } +/// A pin that lands between used()'s reads must not make its slot count as free: with +/// one free slot and the requesting engine already holding a node, may_take must still +/// refuse that engine the last node (the peer's), on a private and a shared context. +fn work_states_used_sees_concurrent_pin() { + use crate::identity::{WorkStates, STATE_COUNT}; + for shared in [false, true] { + let claims = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); + let states: &'static WorkStates = + Box::leak(Box::new(if shared { WorkStates::shared(claims) } else { WorkStates::new() })); + // Engine 0 holds its node and the fillers; engine 1 holds only the node it is about + // to pin. All slots but one are taken, so exactly one slot is free. + let mine = states.allocate(0).expect("engine 0 node"); + let peer = states.allocate(1).expect("engine 1 node"); + let mut rest = Vec::new(); + for _ in 0..(STATE_COUNT - 3) { + rest.push(states.allocate(0).expect("filler")); + } + assert_eq!(states.used(), STATE_COUNT - 1, "one slot free (shared={shared})"); + crate::race::after_next_pin_load(move || assert!(states.pin(peer, 1), "concurrent pin")); + assert!(states.allocate(0).is_none(), + "engine 0 must not take the last free node while holding one, even when a pin lands mid-count (shared={shared})"); + assert_eq!(states.used(), STATE_COUNT - 1, "the pinned slot stays used (shared={shared})"); + assert!(states.allocate(1).is_some(), "the peer can still take the last node (shared={shared})"); + let _ = (mine, rest); + } + println!("WorkStates used(): a pin between its reads keeps the slot counted, so may_take still reserves the peer's node"); +} + fn work_states_pin_prevents_same_context_reuse() { use crate::identity::{WorkStates, STATE_COUNT}; let states = WorkStates::new(); @@ -1111,6 +1169,7 @@ def identity_source(text): fn main() { work_states_pin_prevents_same_context_reuse(); + work_states_used_sees_concurrent_pin(); now::uncached_pooled(); now::return_classes(); now::full_family(); diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 02c9f7ccd3476..82049f2d7215e 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -407,6 +407,7 @@ def mutations(flag, names, base, expect=KILL): 'reuse-killed-work-state', 'reuse-stampless-drained-work-state', 'reuse-failed-work-state', 'drop-stampless-work-lease', 'drop-stampless-drain-pin', 'same-context-reuse-pinned-slot', + 'used-pin-first', 'used-pin-first-shared', 'reuse-recycled-descriptor-ring', 'uncached-nodes', 'uncached-descriptors', 'cached-queue-records', 'cached-scheduler', 'defer-unexposed', 'unexposed-head'), []), From 730f85a54126b2daa74f620abb13b3f64033c57e Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 29 Nov 2026 14:45:00 -0500 Subject: [PATCH 6/7] drm/asahi: g17: keep M5 compute descriptors uncached MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With cached work nodes, also caching the M5 compute descriptor ring made light compute submits at queue depth 4 slower on J775c: 17.9 µs on main, 17.5 µs with nodes alone, 20.4 µs with both. It added nothing at the depths where cached nodes help. Return M5 descriptors to main's rule: uncached on M5, firmware-cached on G17P. A queue recycled after a kill or quarantine still retains its ring until firmware stop. g17-object-fence-tests.py again requires main's descriptor rule. Its uncached-descriptors mutation is replaced by main's m5-cached-descriptors. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/queue/compute.rs | 25 +++++++++++----------- tools/asahi/g17-object-fence-tests.py | 14 ++++++------ tools/asahi/run-host-tests.py | 2 +- 3 files changed, 21 insertions(+), 20 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 797cfe66ae90e..511ec6acff308 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -108,24 +108,25 @@ pub(crate) struct DescriptorRing { impl DescriptorRing { /// Both firmware and host write compute descriptors: the firmware updates /// an accounting word near the end of each descriptor (`+0xfac` on M5), - /// and the host rewrites each slot every 32 kicks. Map the ring - /// firmware-cached on all G17 (G17P and M5), as for render descriptors: - /// within a healthy queue the host rewrites a slot only after the kick that - /// last used it retired (`IN_FLIGHT <= DESCRIPTORS`, with post-maintenance - /// completion stamps mandatory on M5). Across queues, `Pool::allocate` - /// never overruns a pool fence for firmware-cached objects, and any queue - /// recycled after a kill or quarantine retains its descriptor ring until - /// firmware stop (`Queue::retain_ring_until_stop`) instead of returning it - /// to the reuse pool. The hardware reads the same pages through an uncached - /// canonical low alias; on M5 the kernel mapping, in the upper half every - /// execution context includes, is firmware-only. + /// and the host rewrites each slot every 32 kicks. M5 keeps them uncached: + /// with cached work nodes, cached M5 descriptors made light compute + /// submits at queue depth 4 slower on J775c (linux#3389), and they add + /// nothing at the depths where cached nodes help. G17P maps them + /// firmware-cached, as it does render descriptors: the host rewrites a slot + /// only after the kick that last used it retired (at most `DESCRIPTORS` + /// kicks are in flight). Any queue recycled after a kill or quarantine + /// retains its descriptor ring until firmware stop + /// (`Queue::retain_ring_until_stop`) instead of returning it to the reuse + /// pool. The hardware reads the same pages through an uncached canonical + /// low alias; on M5 the kernel mapping, in the upper half every execution + /// context includes, is firmware-only. pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc) -> Result { let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; let object = objects.allocate( alloc, Family::Descriptor, size, - size, + if alloc.uat.is_m5() { 0 } else { size }, if alloc.uat.is_m5() { mmu::PROT_FW_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }, CpuMap::WriteCombined, )?; diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index c0a0c9f617184..bffabebc4794c 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -125,9 +125,8 @@ # Work nodes lose their firmware-cached prefix (the linux#3170 light-submission cost). 'uncached-nodes': ('policy-context', 'Family::WorkState,\n 2 * UAT_PGSZ,\n UAT_PGSZ,', 'Family::WorkState,\n 2 * UAT_PGSZ,\n 0,'), - # Compute descriptors lose their firmware-cached prefix. - 'uncached-descriptors': ('policy-compute', 'Family::Descriptor,\n size,\n size,', - 'Family::Descriptor,\n size,\n 0,'), + # M5 compute descriptors are firmware-cached again (slower light compute at depth 4, linux#3389). + 'm5-cached-descriptors': ('policy-compute', 'if alloc.uat.is_m5() { 0 } else { size }', 'size'), # Render queue records, which the host retargets in place, are firmware-cached again. 'cached-queue-records': ('policy-memory', 'GRAPH_SIZE,\n 0,\n', 'GRAPH_SIZE,\n 0x8000,\n'), # M5 scheduler pages, which are zeroed and reinitialised on reuse, are firmware-cached again. @@ -1256,8 +1255,9 @@ def need(text, pattern, what): 'work nodes: node page cached') # M5 scheduler pages, which are zeroed and reinitialised on reuse, stay uncached. need(context, r'Family::Scheduler,\s*UAT_PGSZ,\s*0,', 'M5 scheduler pages uncached') - # Compute descriptors: cached on every G17. - need(compute, r'Family::Descriptor,\s*size,\s*size,', 'compute descriptors cached') + # Compute descriptors: uncached on M5, cached on G17P. + need(compute, r'Family::Descriptor,\s*size,\s*if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ size \},', + 'compute descriptors: M5 uncached, G17P cached') # A compute queue recycled after kill or quarantine retains its descriptor ring until stop. need(compute, r'pub\(crate\) fn retain_ring_until_stop\(&mut self, pool: &Arc\) \{\s*' r'if let Some\(ring\) = self\.graph\.ring\.as_mut\(\) \{\s*' @@ -1320,8 +1320,8 @@ def main(): print(f'FAIL line 0: cache policy: {failure}') if failures: return 1 - print('cache policy: in-place rewritten records uncached everywhere; work nodes and compute descriptors ' - 'cached on every G17') + print('cache policy: in-place rewritten records uncached everywhere; work nodes cached on every G17; ' + 'compute descriptors cached on G17P only') if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): return 0 diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f806cfe700fb..6e4cf6b4106c8 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -421,7 +421,7 @@ def mutations(flag, names, base, expect=KILL): 'drop-stampless-drain-pin', 'same-context-reuse-pinned-slot', 'used-pin-first', 'used-pin-first-shared', 'reuse-recycled-descriptor-ring', 'uncached-nodes', - 'uncached-descriptors', 'cached-queue-records', 'cached-scheduler', + 'm5-cached-descriptors', 'cached-queue-records', 'cached-scheduler', 'defer-unexposed', 'unexposed-head'), []), 'g17-output-fence-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-member-done', 'set-error-when-signalled', From ad4234d0372580e05926c147e3a240a1afd0c6af Mon Sep 17 00:00:00 2001 From: Satya Benson Date: Sun, 29 Nov 2026 15:50:49 -0500 Subject: [PATCH 7/7] drm/asahi: g17: initialise pinned in WorkStateLease::deferred_split The merge of main brought in deferred_split(), which builds a WorkStateLease without the pinned field this series adds, so the driver no longer compiled (E0063). Start it unpinned, as the other constructor does. Signed-off-by: Satya Benson --- drivers/gpu/drm/asahi/g17/context.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 70f56a6ca5f34..f9ff321d9dd0a 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -792,6 +792,7 @@ impl WorkStateLease { context, word: AtomicU32::new(FREE), engine: AtomicU8::new(0), + pinned: AtomicBool::new(false), ordinal, }) }