From d77b0f0d43f0e6cc26298c4d492a405d6bb27ad6 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 10:23:10 -0500 Subject: [PATCH 1/3] drm/asahi: g16: never run compute beside another VM's compute Compute commands queued behind compute flights of any VM, so the CDM pipes ran dispatches of different VMs at once, without a barrier between them. With six dEQP-VK processes, about one draw in 285 of dEQP-VK.glsl.texture_functions.* then read back zero or a partial image, with no fault and no recovery: the readback copy, running beside another VM's compute, lost its results. One process never fails, every failed case passes alone, and the failures stop entirely once compute waits for other VMs' flights, over three full runs. gpubench compute.long showed the same loss: a ray-query dispatch that another VM's compute overlapped was reported complete with its results unwritten. Let compute publish behind its own VM's flights only, on either pipe, as it already did behind another VM's render, and as G15 runs one VM at a time. Compute of one VM still pipelines on both pipes, and renders still pipeline across VMs. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 20 +++++----- drivers/gpu/drm/asahi/g16/hw.rs | 5 ++- .../drivers/gpu/asahi-m4/test-publication.py | 39 ++++++++++++------- 3 files changed, 38 insertions(+), 26 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index e3074d55cabdd..0c85e94fd77cd 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -434,7 +434,8 @@ pub(crate) enum HoldCause { DrainFailed, /// A cold `InitBM` render is in flight. DrainInitbm, - /// Compute and render of different VMs, or an SCS compute conflict. + /// Compute behind any flight of another VM, render behind compute of another VM, or an + /// SCS compute conflict. DrainCross, /// No warm PB/UMA allocator slot of the VM can take the render behind active flights. DrainPb, @@ -1401,7 +1402,7 @@ impl Firmware { || f.recovery_suspect || f.initbm || (is_compute && scs_compute_conflict(f, &job.vm, is_rt_compute)) - || (((is_compute && f.renders != 0) || (is_render && f.computes != 0)) + || ((is_compute || (is_render && f.computes != 0)) && !Arc::ptr_eq(&f.job.vm, &job.vm)) }) || (is_render && !self.render_can_pipeline(job)) @@ -1589,8 +1590,8 @@ impl Firmware { /// Whether `job`'s next command may be published behind the flights in flight: /// - /// - Compute queues behind healthy non-InitBM compute flights of any VM or same-VM - /// render flights (up to [`params::compute_flights`] active computes), each in its own + /// - Compute queues behind healthy non-InitBM compute and render flights of its own VM + /// (up to [`params::compute_flights`] active computes), each in its own /// `ComputeSlot` and hardware UMA slot (`COMPUTE_UMA_SLOT + index`), unless `query_access` /// is set and a same-queue predecessor in its compute or render barrier prefix has /// CPU-published timestamp outputs that have not retired yet @@ -1606,6 +1607,10 @@ impl Firmware { /// dispatch from one client cannot starve another client's fragment shading into a /// firmware DM1 timeout. Cold InitBM priming renders and every failure or recovery path /// still drain the engine first. + /// - Compute never runs beside compute of another VM, on either pipe: with several clients + /// dispatching barrier-free compute, the overlapped dispatches occasionally lost their + /// results without a fault (loads read zero, readbacks came back empty or partial), + /// which one client alone never does. G15 runs one VM at a time for the same reason. fn can_queue_behind(&self, job: &Arc) -> bool { let mut ta_pending = None; self.can_queue_behind_with_ta(job, &mut ta_pending) @@ -1672,17 +1677,14 @@ impl Firmware { }) }) })); - let cross_vm_render = e - .flights - .iter() - .any(|f| f.renders != 0 && !Arc::ptr_eq(&f.job.vm, &job.vm)); + let cross_vm = e.flights.iter().any(|f| !Arc::ptr_eq(&f.job.vm, &job.vm)); let scs = job.resources.compute_scs() || c.is_rt(); let scs_conflict = e .flights .iter() .any(|f| scs_compute_conflict(f, &job.vm, scs)); let compute_count: usize = e.flights.iter().map(|f| f.computes as usize).sum(); - !cross_vm_render + !cross_vm && !scs_conflict && !waits_for_timestamps && compute_count < params::compute_flights() diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 3d9cf3793dc03..7f96e6cf1f02d 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -831,8 +831,9 @@ pub(crate) mod sizes { pub(crate) const PB_BLOCKS: u32 = 2048; pub(crate) const PB_LIST_RECORDS: u32 = 4096; pub(crate) const PB_GROW_STEP: u32 = 10; - /// Published prefixes at most. Warm compute and render commands may pipeline across VMs - /// on disjoint hardware UMA slots while cold `InitBM` renders and recovery paths drain. + /// Published prefixes at most. Warm render commands may pipeline across VMs on disjoint + /// hardware UMA slots, compute only behind its own VM's work, while cold `InitBM` renders + /// and recovery paths drain. pub(crate) const FLIGHTS: usize = 32; /// Retained compute units per VM at most; each unit owns its own hardware UMA slot /// (`COMPUTE_UMA_SLOT + index`, fitting in `1..RENDER_UMA_SLOT = 33`). A unit is reused diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 3cc505d49350b..73dbb31f2a668 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -589,7 +589,7 @@ def item(declaration): assert_eq!(fw.attempted,[11]); assert_eq!(fw.engine.stats.hold[0],0); - // Cross-VM compute queues immediately behind another VM's active compute without drain. + // Cross-VM compute drains behind another VM's active compute (no cross-VM C<->C overlap). let vm1_c=job_on_vm(12,vm1.clone(),false,0,Ok(())); let vm2_c=job_on_vm(13,vm2.clone(),false,0,Ok(())); let mut fc=firmware(vec![vm2_c],vec![(Ok(()),true)]); @@ -598,8 +598,8 @@ def item(declaration): fc.engine.flights.push(flc); fc.allow_behind=true; assert_eq!(fc.publish_checked(&mut done),Ok(())); - assert_eq!(fc.attempted,[13]); - assert_eq!(fc.engine.stats.hold[0],0); + assert!(fc.attempted.is_empty()); + assert_eq!(fc.engine.stats.hold[0],1); // Cross-VM compute drains behind another VM's active render (no cross-VM R<->C overlap). let vm1_r2=job_on_vm(14,vm1.clone(),true,0,Ok(())); @@ -938,10 +938,9 @@ def item(declaration): pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, }; assert!(p.can_queue_behind(&j2)); - // Cross-VM compute queues behind another VM's healthy compute, but drains behind - // another VM's render. - assert!(p.can_queue_behind(&j_other_vm)); - assert!(!p.needs_engine_drain(&j_other_vm)); + // Cross-VM compute drains behind another VM's compute as behind its render. + assert!(!p.can_queue_behind(&j_other_vm)); + assert!(p.needs_engine_drain(&j_other_vm)); assert!(p.can_queue_behind(&j_render)); p.engine.flights[0].doomed=true; assert!(!p.can_queue_behind(&j2)); @@ -995,13 +994,17 @@ def item(declaration): assert!(!p.can_queue_behind(j)); assert!(p.needs_engine_drain(j)); } - // SCS compute does not start beside non-SCS compute on either pipe. + // SCS compute does not start beside non-SCS compute on either pipe, and no compute + // starts beside another VM's compute. for pipe in [0u8,1] { p.engine.flights=vec![flight(alu.clone(),false,pipe)]; assert!(!p.can_queue_behind(&rq)); assert!(p.needs_engine_drain(&rq)); - assert!(p.can_queue_behind(&rq_post)); - assert!(!p.needs_engine_drain(&rq_post)); + assert!(!p.can_queue_behind(&rq_post)); + assert!(p.needs_engine_drain(&rq_post)); + p.engine.flights=vec![flight(rq_post.clone(),false,pipe)]; + assert!(!p.can_queue_behind(&rq)); + assert!(p.needs_engine_drain(&rq)); } // A render flight of its own VM does not hold it; once SCS compute is gone, the rest // overlaps as before. @@ -1012,8 +1015,10 @@ def item(declaration): assert!(!p.needs_engine_drain(&rq)); assert!(p.can_queue_behind(&rq)); p.engine.flights=vec![flight(rq_post.clone(),false,0)]; - assert!(p.can_queue_behind(&alu)); - assert!(!p.needs_engine_drain(&alu)); + assert!(p.can_queue_behind(&rq_post)); + assert!(!p.needs_engine_drain(&rq_post)); + assert!(!p.can_queue_behind(&alu)); + assert!(p.needs_engine_drain(&alu)); } #[test]fn compute_query_access_waits_for_timed_predecessor_unless_no_query_access(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); @@ -1134,11 +1139,11 @@ def item(declaration): assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); assert!(p.can_queue_behind(&vm2_r) && !p.needs_engine_drain(&vm2_r)); assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); - // Active VM1 Compute: same-VM R & C allowed; cross-VM C allowed; cross-VM R blocked + drains. + // Active VM1 Compute: same-VM R & C allowed; cross-VM C and R blocked + drain. p.engine.flights=vec![mk_flight(vm1_c.clone(),1,0)]; assert!(p.can_queue_behind(&vm1_r) && !p.needs_engine_drain(&vm1_r)); assert!(p.can_queue_behind(&vm1_c) && !p.needs_engine_drain(&vm1_c)); - assert!(p.can_queue_behind(&vm2_c) && !p.needs_engine_drain(&vm2_c)); + assert!(!p.can_queue_behind(&vm2_c) && p.needs_engine_drain(&vm2_c)); assert!(!p.can_queue_behind(&vm2_r) && p.needs_engine_drain(&vm2_r)); // Mixed active VM1 Render + VM1 Compute: both cross-VM R and cross-VM C blocked + drain. p.engine.flights=vec![mk_flight(vm1_r.clone(),0,1),mk_flight(vm1_c.clone(),1,0)]; @@ -1880,9 +1885,13 @@ def item(declaration): host.engine.next_compute_pipe=0; assert_eq!(host.choose_compute_pipe(&q3, [None, None], (1u32 << 24) - 1, false, false), 0); assert_eq!(host.choose_compute_pipe(&q1, [None, None], (1u32 << 24) - 1, false, true), 0); - assert!(host.can_queue_behind(&c_vm2)); + // No compute queues beside another VM's compute flight, on either pipe. + assert!(!host.can_queue_behind(&c_vm2)); + assert!(!host.can_queue_behind(&c2)); // Same-VM compute still pipelines without draining. + host.engine.flights.pop(); assert!(host.can_queue_behind(&c2)); + assert!(!host.can_queue_behind(&c_vm2)); } #[test]fn two_pipe_compute_barriers_reuse_single_pipe_and_serialize_across_both_pipes(){ let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); From 990b848a7a6e8af6dbd33adbd52e3009a3bf9d61 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 18:03:57 -0500 Subject: [PATCH 2/3] drm/asahi: g16: keep a VM's last PB epoch until its next render retires With the display manager running, gpubench-vk render.light kind=tri --mode procs at depth 16 faults in 5 to 11 of 13 runs on J773g, and the GPU can be lost for the rest of the boot. With the display manager stopped, the same kernels pass. Every fault has one shape: fault bank 3: status 0x8f81fdc021 va 0x704000cf00 (write unmapped level 0 unit 0xe0 ctx 62) attribution: busy=0 ctx=62 flight_matches=1 live_vm=Some(108) event=0xffffffff flights=1 Unit 0xe0 is gPM_SP(0), the parameter manager. The DYNAMIC window holds only PB page lists: the faulting addresses are records 16 to 976 of a VM's first (0x7040000000) or second (0x704000c000) page list. The context is an open client's, and the only flight is that client's cold InitBM render. kwin and the login greeter's VMs move the round-robin [home, alt] PB slot pairs, so 16 clients and those VMs share 16 warm slots and take displaced slots from each other while all are open. When another VM's epoch retires on slot k, retire_flight() replaces owners[k] and the open VM's epoch goes, unmapping its page list. At that VM's next InitBM, the parameter manager writes back to the page list of the manager the context used last, through that context, and the list is gone. Commit 047b934ce47a ("drm/asahi: g16: keep closed VMs' PB epochs until their slot is replaced") covered only closed VMs. Keep each VM's last retired epoch in Pools, indexed by its TTBAT slot, which the entry keeps bound. A newer render of the same VM replaces it once that render fully retired; a failed render keeps it. A closed VM's entry goes once none of its accepted renders is unpublished or in flight, so closed VMs pin nothing extra. An open VM whose slot was taken keeps one more epoch (two 32 KiB lists and its records) until its next render retires. Count such replacements as "kept" on the debugfs pb line. Add host tests for the open-VM sequence and the closed-VM release, and for the extra reclaim pass a closed VM's entry asks for. Fixes: e30cdb92b4f5 ("drm/asahi: g16: scale warm render PB/UMA slots to 16 and keep pass slots VM-affine") Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/poll.rs | 7 +- drivers/gpu/drm/asahi/g16/pools.rs | 77 +++++++++- drivers/gpu/drm/asahi/g16/resources.rs | 6 + drivers/gpu/drm/asahi/g16/vm.rs | 9 ++ .../drivers/gpu/asahi-m4/test-poll-retire.py | 17 +++ .../drivers/gpu/asahi-m4/test-resources.py | 134 +++++++++++++++++- 6 files changed, 242 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 43647519f2202..6101777abaa1f 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -639,9 +639,10 @@ impl Firmware { let Some(shared) = self.engine.shared.as_ref() else { return; }; - if !shared.closed_vm_reclaim.load(Ordering::Acquire) - || !shared.closed_vm_reclaim.swap(false, Ordering::AcqRel) - { + let armed = shared.closed_vm_reclaim.load(Ordering::Acquire) + && shared.closed_vm_reclaim.swap(false, Ordering::AcqRel); + // A closed VM's render retired and recorded its last epoch after the VM was closed. + if !self.pools.take_closed_vm_last() && !armed { return; } let remaining = self.pools.reclaim_closed() | self.slots.reclaim_closed(); diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index c08da53d7fac2..1cc226458d575 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -77,6 +77,8 @@ pub(crate) struct PbStats { /// render counts again when it is retried). pub(crate) reused: u64, pub(crate) fresh: u64, + /// Retirements that replaced an open VM's owner epoch still kept as that VM's last epoch. + pub(crate) kept: u64, } pub(crate) struct PoolSet { @@ -501,7 +503,17 @@ pub(crate) struct Pools { quarantined: [bool; sizes::PB_SLOTS], /// Fresh PB epoch retained when an aborted render had not yet replaced `owners[k]`. quarantined_epochs: [Option>; sizes::PB_SLOTS], + /// Per TTBAT slot, the epoch of the last render its VM retired, kept until a newer render + /// of the same VM retires. The parameter manager writes back to the page list of the + /// manager a context used last, through that context, when the context's next InitBM + /// runs, also after another VM's epoch replaced `owners[k]` on the old slot. An entry + /// holds its VM and so the TTBAT slot that indexes it. + vm_last: [Option>; VM_LAST_ENTRIES], + /// A closed VM's [`Self::vm_last`] entry was recorded since the last reclaim pass. + closed_vm_last: bool, } +/// Entries of [`Pools::vm_last`]: one per TTBAT user slot (ASIDs `1..=MAX_VMS`). +const VM_LAST_ENTRIES: usize = sizes::MAX_VMS as usize + 1; impl Pools { #[allow(dead_code)] pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { @@ -523,6 +535,8 @@ impl Pools { inflight: [0; sizes::PB_SLOTS], quarantined: [false; sizes::PB_SLOTS], quarantined_epochs: [const { None }; sizes::PB_SLOTS], + vm_last: [const { None }; VM_LAST_ENTRIES], + closed_vm_last: false, } } /// Allocates [`Pools`] directly on the heap so probe/backend bring-up does not stage the @@ -549,6 +563,8 @@ impl Pools { inflight: [0; sizes::PB_SLOTS], quarantined: [false; sizes::PB_SLOTS], quarantined_epochs: [const { None }; sizes::PB_SLOTS], + vm_last: [const { None }; VM_LAST_ENTRIES], + closed_vm_last: false, }), GFP_KERNEL, )?) @@ -962,6 +978,14 @@ impl Pools { if self.quarantined[k] { return Ok(()); } + if self.owners[k].as_ref().is_some_and(|old| { + !Arc::ptr_eq(&old._vm, &epoch._vm) && !old._vm.vm.is_closed() && self.is_vm_last(old) + }) { + self.stats.kept += 1; + } + if completed { + self.note_vm_last(epoch); + } self.owners[k] = Some(epoch.clone()); self.retained_pb[k] = Some(epoch.records_lease()); if let Some(vm) = self.pending_vms[k].take() { @@ -977,6 +1001,33 @@ impl Pools { self.retire_epoch(k, binding, completed); Ok(()) } + /// Whether `epoch` is the last retired epoch of its VM ([`Self::vm_last`]). + fn is_vm_last(&self, epoch: &Arc) -> bool { + self.vm_last + .get(epoch._vm.slot as usize) + .and_then(Option::as_ref) + .is_some_and(|last| Arc::ptr_eq(last, epoch)) + } + /// A render of `epoch` retired normally: its VM's context has run that render's InitBM (or + /// reused the epoch), so the VM's earlier epoch is no longer written and may go. A closed + /// VM keeps an entry only until [`Self::reclaim_closed`] finds nothing of it pending. + fn note_vm_last(&mut self, epoch: &Arc) { + let vm = &epoch._vm; + let closed = vm.vm.is_closed(); + let Some(entry) = self.vm_last.get_mut(vm.slot as usize) else { + return; + }; + if entry.as_ref().is_some_and(|last| Arc::ptr_eq(last, epoch)) { + return; + } + *entry = Some(epoch.clone()); + self.closed_vm_last |= closed; + } + /// Whether a closed VM's entry was recorded since the last call: [`Self::reclaim_closed`] + /// must run again to release it. + pub(crate) fn take_closed_vm_last(&mut self) -> bool { + core::mem::take(&mut self.closed_vm_last) + } /// Quarantines allocator slot `k` permanently after a passed abort, retaining all leases /// including any fresh epoch published on the aborted flight alongside `owners[k]`. #[allow(dead_code)] @@ -1042,6 +1093,7 @@ impl Pools { /// The owner epoch itself stays until a newer epoch retires on its slot /// ([`Self::retire_flight`]): `pb_mgr_table[k]` keeps naming its manager, and the parameter /// manager can still write that manager's page list through the context of the epoch's VM. + /// Also releases a closed VM's [`Self::vm_last`] entry once nothing of that VM is pending. pub(crate) fn reclaim_closed(&mut self) -> bool { let mut remaining = false; for k in 0..sizes::PB_SLOTS { @@ -1076,6 +1128,26 @@ impl Pools { remaining = true; } } + // A closed VM accepts no new render. Once none it accepted waits for publication or + // retirement, its context runs no further InitBM and its last epoch may go. A render + // left on a quarantined slot keeps its VM there anyway. + for i in 0..VM_LAST_ENTRIES { + let Some(vm) = self.vm_last[i].as_ref().map(|last| &last._vm) else { + continue; + }; + if !vm.vm.is_closed() { + continue; + } + let pending = (0..sizes::PB_SLOTS).any(|k| { + !self.quarantined[k] + && self.pending_vms[k].as_ref().is_some_and(|p| Arc::ptr_eq(p, vm)) + }); + if pending || vm.renders_unpublished() { + remaining = true; + } else { + self.vm_last[i] = None; + } + } remaining } #[allow(dead_code)] @@ -1087,12 +1159,13 @@ impl Pools { pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { writeln!( f, - "pb: M4 private allocators blocks {} requests {} bad {} reused {} fresh {}", + "pb: M4 private allocators blocks {} requests {} bad {} reused {} fresh {} kept {}", buffer::MAX_BLOCKS, self.stats.requests, self.stats.bad, self.stats.reused, - self.stats.fresh + self.stats.fresh, + self.stats.kept ) } } diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 0961b97b38903..385dbaaa3dfbb 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -1031,6 +1031,12 @@ impl Cache { } } + /// Whether accepted renders still hold standby reservations, that is, are not yet + /// published ([`Prepared::commit_render`]) or dropped. + pub(crate) fn renders_unpublished(&self) -> bool { + self.standby.lock().reserved != 0 + } + /// The VM's client closed. Lets go of the arenas and surplus standby epochs: accepted /// renders keep only the exact standby count they reserved until they finish, and hardware /// slots hold their own last-owner leases. diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 0367a4421554c..63bc92df97044 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -138,6 +138,15 @@ pub(crate) struct VmStateInner { pub(crate) live: Arc, } +impl VmStateInner { + /// Whether renders this VM's SUBMITs accepted are not yet published. + pub(crate) fn renders_unpublished(&self) -> bool { + self.resources + .as_ref() + .is_some_and(|cache| cache.renders_unpublished()) + } +} + impl Drop for VmStateInner { fn drop(&mut self) { mod_pr_debug!("G16: VM {} releases context {}\n", self.id, self.slot); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 4634f0cc2bd0e..8cdeb175dac37 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -284,12 +284,16 @@ def item(declaration, text=source): struct Pools { reclaim_calls: u32, reclaim_remaining: bool, + closed_vm_last: bool, } impl Pools { fn reclaim_closed(&mut self) -> bool { self.reclaim_calls += 1; self.reclaim_remaining } + fn take_closed_vm_last(&mut self) -> bool { + core::mem::take(&mut self.closed_vm_last) + } } #[derive(Default)] @@ -570,6 +574,19 @@ def item(declaration, text=source): .unwrap(); assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (3, 3)); assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + + // A closed VM's render retired after the flag cleared and recorded its last PB epoch: + // the next pass reclaims once without the flag, then scans stop again. + fw.pools.closed_vm_last = true; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (4, 4)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (4, 4)); } #[test] diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index 5aa9f7afbabfd..e9b9840101e88 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -174,13 +174,16 @@ def module(text, name): pub mod vm { use crate::{mmu,sync::Arc}; use core::sync::atomic::{AtomicBool,Ordering}; - pub struct MockVm(AtomicBool); + pub struct MockVm(AtomicBool,AtomicBool); impl MockVm{ - pub fn new()->Self{Self(AtomicBool::new(false))} + pub fn new()->Self{Self(AtomicBool::new(false),AtomicBool::new(false))} pub fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)} pub fn close(&self){self.0.store(true,Ordering::Release);} + // Accepted renders still unpublished (the VM cache's standby reservations). + pub fn set_unpublished(&self,v:bool){self.1.store(v,Ordering::Release);} } pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} + impl VmState{pub fn renders_unpublished(&self)->bool{self.vm.1.load(Ordering::Acquire)}} struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -1060,7 +1063,8 @@ def module(text, name): let _=p.bind(1,false);p.publish_flight(1); p.invalidate(); p.quarantine_flight(1,Some(e3.clone())); - assert_eq!(sync::Arc::strong_count(&e2),2,"prior slot owner epoch must stay mapped"); + // e2 is slot 1's prior owner and VM2's last retired epoch. + assert_eq!(sync::Arc::strong_count(&e2),3,"prior slot owner epoch must stay mapped"); assert_eq!(sync::Arc::strong_count(&e3),2,"aborted fresh epoch must stay mapped"); // Render class must NOT wedge: slot 2 is fresh and needed_slots advances to 3. assert!(!p.exhausted()); @@ -2969,6 +2973,130 @@ def module(text, name): assert!(!p.reclaim_closed()); } + // Live cross-VM steal of a warm PB slot (display manager active: kwin, its helpers and 16 + // clients over 16 warm slots). VM A's epoch owns slot 3. VM B's fresh epoch rebinds slot 3 + // and retires, replacing owners[3] while A is still open. A's next render is a cold InitBM + // on slot 4, the only flight; gPM_SP(0) then writes the old epoch's page list through A's + // context: "write unmapped level 0 unit 0xe0 ctx 62 ... flights=1 live_vm=Some(108)". + #[test]fn live_vm_displaced_pb_epoch_keeps_page_list_until_its_next_render_retires(){ + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + let run = |p: &mut g16::pools::Pools, v: &sync::Arc, k: usize, + e: &sync::Arc, completed: bool| { + let b = p.bind(k, false); + p.hold_alloc(k, v, None, None).unwrap(); + p.publish_flight(k); + p.retire_flight(k, e, b, completed).unwrap(); + }; + + let a = vm(62); + let b = vm(5); + let ea1 = epoch(&a, 3); + run(&mut p, &a, 3, &ea1, true); + let eb = epoch(&b, 3); + run(&mut p, &b, 3, &eb, true); + assert!(p.reusable(3, &a).is_none(), "slot 3 is bound to B's epoch"); + assert_eq!(sync::Arc::strong_count(&ea1), 2, "A's page list unmapped while A is open"); + assert_eq!(p.stats.kept, 1); + + // A's next render binds slot 4 with InitBM. The old list stays while it is in flight + // and after a failed retirement, which need not have run the InitBM. + let ea2 = epoch(&a, 4); + let b2 = p.bind(4, false); + p.hold_alloc(4, &a, None, None).unwrap(); + p.publish_flight(4); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + p.retire_flight(4, &ea2, b2, false).unwrap(); + assert_eq!(sync::Arc::strong_count(&ea1), 2, "a failed render released the old list"); + let ea3 = epoch(&a, 4); + run(&mut p, &a, 4, &ea3, true); + assert_eq!(sync::Arc::strong_count(&ea1), 1, "released after A's newer render retired"); + assert_eq!(sync::Arc::strong_count(&ea3), 3, "slot 4 owner and A's last epoch"); + assert_eq!(sync::Arc::strong_count(&eb), 3, "slot 3 owner and B's last epoch"); + // Warm reuse of the same epoch changes nothing. + run(&mut p, &b, 3, &eb, true); + assert_eq!(sync::Arc::strong_count(&eb), 3); + assert_eq!(p.stats.kept, 1); + // Open VMs never keep reclaim armed. + assert!(!p.take_closed_vm_last()); + assert!(!p.reclaim_closed()); + } + + // A closed VM keeps its last epoch while a render it accepted waits for publication or + // retirement, and loses it once none does, so its context and lists are not pinned. + #[test]fn closed_vm_last_pb_epoch_waits_for_its_accepted_renders(){ + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + let run = |p: &mut g16::pools::Pools, v: &sync::Arc, k: usize, + e: &sync::Arc| { + let b = p.bind(k, false); + p.hold_alloc(k, v, None, None).unwrap(); + p.publish_flight(k); + p.retire_flight(k, e, b, true).unwrap(); + }; + + let a = vm(20); + let b = vm(21); + let ea1 = epoch(&a, 3); + run(&mut p, &a, 3, &ea1); + let eb = epoch(&b, 3); + run(&mut p, &b, 3, &eb); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + + // A closes with an accepted render not yet published. + a.vm.set_unpublished(true); + a.vm.close(); + assert!(p.reclaim_closed(), "accepted render of the closed VM still unpublished"); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + // It publishes a fresh InitBM epoch on slot 4. + a.vm.set_unpublished(false); + let ea2 = epoch(&a, 4); + let b2 = p.bind(4, false); + p.hold_alloc(4, &a, None, None).unwrap(); + p.publish_flight(4); + assert!(p.reclaim_closed(), "render of the closed VM in flight"); + assert_eq!(sync::Arc::strong_count(&ea1), 2); + p.retire_flight(4, &ea2, b2, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&ea1), 1, "older epoch released after the InitBM"); + assert!(p.take_closed_vm_last(), "a closed VM's entry asks for another reclaim pass"); + assert!(!p.take_closed_vm_last()); + // B retires on slot 5, so slot 4 is displaced; nothing of A is pending any more. + let eb5 = epoch(&b, 5); + run(&mut p, &b, 5, &eb5); + assert!(!p.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&ea2), 2, "only slot 4's owner keeps A's last epoch"); + drop(ea1); + drop(ea2); + // Slot 4's owner holds A until a newer epoch retires there. + assert_eq!(sync::Arc::strong_count(&a), 2); + let eb4 = epoch(&b, 4); + run(&mut p, &b, 4, &eb4); + assert_eq!(sync::Arc::strong_count(&a), 1, "closed VM fully released"); + assert!(!p.reclaim_closed()); + } + } ''' poll_source = (production/'poll.rs').read_text() From f445466d8f881c8cdcf3c9331afb408c0ecd28f4 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 19:21:18 -0500 Subject: [PATCH 3/3] drm/asahi: g16: wake closed-VM reclaim on cancel and return abort suffix credits Address two review findings on the per-VM last PB epoch retention: - When a closed VM's final unpublished render reservation is cancelled, wake idle closed-VM reclaim so its displaced vm_last epoch and ASID do not stay pinned while idle. - When recovery retains an aborted job for quarantine and discards its unpublished suffix, return the discarded suffix's render credits while keeping the published quarantine backing intact. Add host regression tests covering both paths. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/mod.rs | 13 +- drivers/gpu/drm/asahi/g16/poll.rs | 10 +- drivers/gpu/drm/asahi/g16/resources.rs | 51 +++- drivers/gpu/drm/asahi/g16/vm.rs | 1 + .../drivers/gpu/asahi-m4/test-resources.py | 257 +++++++++++++++++- 5 files changed, 299 insertions(+), 33 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 7c7851ee6068a..0a647cbbd2cb5 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -251,8 +251,8 @@ pub(crate) struct Shared { /// Set by external state changes (VM teardown, unstarted queue cancellation) so the next /// `poll_step()` re-evaluates `publish_checked()` even while unrelated flights are active. pub(crate) publish_wake: AtomicBool, - /// Set on VM close (and re-armed while any non-quarantined slot still holds a closed VM) - /// so displaced closed-VM slot leases are reclaimed without scanning on the hot path. + /// Set on VM close and when its last unpublished render reservation is released. + /// Re-armed while a closed VM still holds a lease awaiting reclaim. pub(crate) closed_vm_reclaim: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, @@ -507,6 +507,12 @@ impl Shared { } } + /// Arms and wakes the poll worker to reclaim closed VM leases. + pub(crate) fn wake_closed_vm_reclaim(self: &Arc) { + self.closed_vm_reclaim.store(true, Ordering::Release); + self.wake_publish(); + } + /// Latches the fail-stop state. pub(crate) fn fail_stop(&self, error: Error) { self.feed.begin_shutdown(); @@ -904,8 +910,7 @@ impl gpu::Gpu for Gpu { } fn vm_closed(&self, vm: &mmu::Vm) { self.vms.close(vm.id()); - self.shared.closed_vm_reclaim.store(true, Ordering::Release); - self.shared.wake_publish(); + self.shared.wake_closed_vm_reclaim(); } fn new_queue( diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 6101777abaa1f..d189df2e4560d 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -741,11 +741,10 @@ impl Firmware { self.reclaim_closed_vm_slots(); } // Skip redundant `publish_checked()` walks on busy polls where nothing could have - // unblocked `engine.pending`. `Prepared::drop` releases standby PB epochs only for - // `Cache::prepare` waiters (`standby_available`, which enter `submit_locked()` directly), - // while `publish_woke` covers external state changes (VM close, unstarted queue - // cancellation) and `ta_wave_ready()` wakes TA-wave-paced renders when a `0x70` TA - // pass finishes while FS is still running. + // unblocked `engine.pending`. Standby release wakes `Cache::prepare` waiters, which + // enter `submit_locked()` directly. `publish_woke` covers external state changes + // including a closed VM's final reservation release. `ta_wave_ready()` wakes + // TA-wave-paced renders when a `0x70` TA pass finishes while FS is still running. let coalesce_due = self.engine.coalesce_deadline_ns != 0 && (!evented || now >= self.engine.coalesce_deadline_ns); let should_publish = !self.engine.pending.is_empty() @@ -1687,6 +1686,7 @@ impl Firmware { p.pending.store(false, Ordering::Relaxed); self.engine.pending.retain(|j| !Arc::ptr_eq(j, &job)); p.count.store(p.sent(), Ordering::Relaxed); + job.resources.discard_unpublished_renders(); } if receipt.owner_retired() && self.engine.flights.iter().all(|other| { diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 385dbaaa3dfbb..56e87b15b8dad 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -11,6 +11,7 @@ use super::{ pools::{PbEpoch, PoolSet}, slots::{ComputeSlot, PassCmds, PassSlot, Placement, UnitCmds}, vm::VmState, + Shared, }; use crate::mmu; use core::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; @@ -921,12 +922,14 @@ pub(crate) struct Cache { bind: mmu::VmBind, live: Arc, budget: Arc, + shared: Arc, } impl Cache { pub(crate) fn new( factory: Factory, bind: mmu::VmBind, live: Arc, + shared: Arc, ) -> Result> { let budget = super::budget::Budget::new()?; let epochs = KVec::with_capacity(super::budget::LIMIT as usize, GFP_KERNEL)?; @@ -943,7 +946,7 @@ impl Cache { standby_available <- new_condvar!(), closed: AtomicBool::new(false), active_render_passes: AtomicU32::new(0), - factory, bind, live, budget }), + factory, bind, live, budget, shared }), GFP_KERNEL, ) } @@ -986,11 +989,13 @@ impl Cache { if count == 0 { return; } - let (mut wake, excess) = { + let (mut wake, reclaim, excess) = { let mut standby = self.standby.lock(); standby.reserved = standby.reserved.saturating_sub(count); let wake = standby.waiters != 0; - let keep = if self.closed.load(Ordering::Acquire) { + let closed = self.closed.load(Ordering::Acquire); + let reclaim = closed && standby.reserved == 0; + let keep = if closed { standby.reserved as usize } else { (standby.reserved as usize).max(SPARE_EPOCHS) @@ -1000,7 +1005,7 @@ impl Cache { } else { None }; - (wake, excess) + (wake, reclaim, excess) }; if let Some(excess) = excess { drop(excess); @@ -1029,6 +1034,14 @@ impl Cache { if wake { self.standby_available.notify_all(); } + if reclaim { + self.shared.wake_closed_vm_reclaim(); + } + } + + fn release_render_passes(&self, count: u32) { + let previous = self.active_render_passes.fetch_sub(count, Ordering::AcqRel); + debug_assert!(previous >= count); } /// Whether accepted renders still hold standby reservations, that is, are not yet @@ -1450,7 +1463,7 @@ impl Cache { render_ext, pb_heap_ext, pb_ext, - total_renders: render_count, + active_renders: AtomicU32::new(render_count), unpublished_renders: AtomicU32::new(render_count), cache, }) @@ -1473,8 +1486,8 @@ pub(crate) struct Prepared { pub(crate) pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], /// The VM's lazily allocated recovery PB/UMA allocator slots when the job was prepared. pub(crate) pb_ext: [Option>; EXT_PB_SLOTS], - /// Total render commands accounted against `Cache::active_render_passes`. - total_renders: u32, + /// Render commands still accounted against `Cache::active_render_passes`. + active_renders: AtomicU32, /// Render commands of this job whose standby reservation has not yet been committed. unpublished_renders: AtomicU32, /// The VM cache holding the standby PB epoch pool. @@ -1483,18 +1496,28 @@ pub(crate) struct Prepared { impl Drop for Prepared { fn drop(&mut self) { - let Some(cache) = self.cache.take() else { + let Some(cache) = &self.cache else { return; }; - let previous = cache - .active_render_passes - .fetch_sub(self.total_renders, Ordering::AcqRel); - debug_assert!(previous >= self.total_renders); - let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); - cache.release_reserved(remaining); + cache.release_render_passes(*self.active_renders.get_mut()); + cache.release_reserved(*self.unpublished_renders.get_mut()); } } impl Prepared { + /// Returns canceled render credits even if the job stays retained for its published work. + /// The device lock serializes suffix discard with publication. + pub(crate) fn discard_unpublished_renders(&self) { + let Some(cache) = &self.cache else { + return; + }; + let remaining = self.unpublished_renders.swap(0, Ordering::AcqRel); + if remaining != 0 { + self.active_renders.fetch_sub(remaining, Ordering::AcqRel); + cache.release_render_passes(remaining); + cache.release_reserved(remaining); + } + } + pub(crate) fn compute(&self) -> Result<&ComputeUnitSet> { self.compute.as_deref().ok_or(EINVAL) } diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 63bc92df97044..735b6743bed66 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -415,6 +415,7 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Resul factory, live.bind.as_ref().ok_or(EIO)?.clone(), live.clone(), + gpu.shared.clone(), )?; let inner = VmStateInner { id, diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index e9b9840101e88..27cc9aab32d72 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -174,16 +174,42 @@ def module(text, name): pub mod vm { use crate::{mmu,sync::Arc}; use core::sync::atomic::{AtomicBool,Ordering}; - pub struct MockVm(AtomicBool,AtomicBool); + use super::resources::reservations::Cache; + pub struct MockVm { + closed: AtomicBool, + unpublished: AtomicBool, + cache: Option>, + _live: Option>, + } impl MockVm{ - pub fn new()->Self{Self(AtomicBool::new(false),AtomicBool::new(false))} - pub fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)} - pub fn close(&self){self.0.store(true,Ordering::Release);} + pub fn new() -> Self { + Self { + closed: AtomicBool::new(false), + unpublished: AtomicBool::new(false), + cache: None, + _live: None, + } + } + pub fn tracked(cache: Arc) -> (Self, std::sync::Arc) { + let live = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(1)); + let released = std::sync::Arc::new(AtomicBool::new(false)); + let registry = Arc::new(Registry { live: live.clone() }, 0).unwrap(); + let bind = mmu::VmBind { live, released: released.clone() }; + let token = Arc::new(LiveToken { registry, bind: Some(bind), file_id: 0 }, 0).unwrap(); + (Self { cache: Some(cache), _live: Some(token), ..Self::new() }, released) + } + pub fn is_closed(&self)->bool{self.closed.load(Ordering::Acquire)} + pub fn close(&self){self.closed.store(true,Ordering::Release);} // Accepted renders still unpublished (the VM cache's standby reservations). - pub fn set_unpublished(&self,v:bool){self.1.store(v,Ordering::Release);} + pub fn set_unpublished(&self,v:bool){self.unpublished.store(v,Ordering::Release);} } pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} - impl VmState{pub fn renders_unpublished(&self)->bool{self.vm.1.load(Ordering::Acquire)}} + impl VmState { + pub fn renders_unpublished(&self) -> bool { + self.vm.unpublished.load(Ordering::Acquire) + || self.vm.cache.as_ref().is_some_and(|cache| cache.renders_unpublished()) + } + } struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -260,6 +286,197 @@ def module(text, name): pub(crate) const BASE_RENDER_SLOTS: usize = super::hw::sizes::BASE_RENDER_SLOTS; const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; __RENDER_BURST__ + + pub(crate) mod reservations { + use super::{ComputeArena as ComputeUnitSet, PoolExtArena, RenderArena}; + use crate::{ + device::Device, + driver::AsahiDrmDevice, + g16::{budget::Budget, object::Factory, pools::{PbEpoch, Pools}, slots::Slots, vm::{MockVm, VmState}}, + sync::{Arc, CondVar, Mutex}, + KVec, + }; + use core::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + + #[derive(Default)] + pub(crate) struct Shared { + closed_vm_reclaim: AtomicBool, + publish_wake: AtomicBool, + started: AtomicBool, + sleeping: AtomicBool, + poll_queued: AtomicBool, + } + impl Shared { + __WAKE_PUBLISH__ + __WAKE_CLOSED_VM_RECLAIM__ + + fn poll_now(&self) { + self.poll_queued.store(true, Ordering::Release); + } + } + + __STANDBY__ + __SPARE_EPOCHS__ + struct RenderExtArena; + struct PbHeapExtArena; + const EXT_RENDER_TIERS: [(); 0] = []; + const PB_HEAP_EXT_TIERS: [(); 0] = []; + const EXT_PB_SLOTS: usize = 1; + + pub(crate) struct Cache { + standby: Mutex, + standby_available: CondVar, + closed: AtomicBool, + active_render_passes: AtomicU32, + shared: Arc, + } + impl Cache { + __RELEASE_RESERVED__ + __RELEASE_RENDER_PASSES__ + __RENDERS_UNPUBLISHED__ + } + + __PREPARED__ + __DROP_PREPARED__ + impl Prepared { + __COMMIT_RENDER__ + __DISCARD_UNPUBLISHED__ + } + + struct Engine { + shared: Option>, + } + struct Firmware { + engine: Engine, + pools: Pools, + slots: Slots, + } + impl Firmware { + __RECLAIM_CLOSED_VM_SLOTS__ + + fn idle_poll(&mut self) { + let shared = self.engine.shared.as_ref().unwrap(); + assert!(shared.poll_queued.swap(false, Ordering::AcqRel), "poll must be queued"); + self.reclaim_closed_vm_slots(); + } + } + + fn displaced_vm(credits: u32) -> ( + Firmware, Arc, Arc, Arc, std::sync::Arc, Prepared, + ) { + let shared = Arc::new(Shared::default(), 0).unwrap(); + shared.started.store(true, Ordering::Release); + let cache = Arc::new(Cache { + standby: Mutex::new(Standby { epochs: KVec::new(), reserved: credits, waiters: 0 }), + standby_available: CondVar::new(), + closed: AtomicBool::new(false), + active_render_passes: AtomicU32::new(credits), + shared: shared.clone(), + }, 0).unwrap(); + let (vm, released) = MockVm::tracked(cache.clone()); + let vm = Arc::new(VmState { id: 1, slot: 1, generation: 1, vm }, 0).unwrap(); + let replacement = crate::resources::vm(2); + let mut pools = Pools::new(&AsahiDrmDevice(Device)); + let budget = Budget::new().unwrap(); + for _ in 0..credits { + let credit = Budget::reserve(&budget, 1).unwrap().take().unwrap(); + cache.standby.lock().epochs.push(PbEpoch::new(&Factory, &vm, credit).unwrap(), 0).unwrap(); + } + let epoch = exposed_epoch(&budget, &vm, 0); + let newer = exposed_epoch(&budget, &replacement, 0); + for (owner, backing) in [(&vm, &epoch), (&replacement, &newer)] { + let binding = pools.bind(0, false); + pools.hold_alloc(0, owner, None, None).unwrap(); + pools.publish_flight(0); + pools.retire_flight(0, backing, binding, true).unwrap(); + } + let firmware = Firmware { + engine: Engine { shared: Some(shared) }, + pools, + slots: Slots::new().unwrap(), + }; + let prepared = Prepared { + active_renders: AtomicU32::new(credits), + unpublished_renders: AtomicU32::new(credits), + cache: Some(cache.clone()), + compute: None, + compute_ext: None, + compute_scs: false, + render: None, + render_scs: false, + render_ext: [], + pb_heap_ext: [], + pb_ext: [Some(Arc::new(PoolExtArena, 0).unwrap())], + }; + (firmware, cache, vm, epoch, released, prepared) + } + + fn exposed_epoch(budget: &Arc, vm: &Arc, slot: usize) -> Arc { + let credit = Budget::reserve(budget, 1).unwrap().take().unwrap(); + let e = PbEpoch::new(&Factory, vm, credit).unwrap(); + e.prepare(slot, crate::g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + } + + #[test] + fn cancel_last_unpublished_render_wakes_idle_reclaim_and_releases_asid() { + let (mut fw, cache, vm, epoch, released, job) = displaced_vm(1); + vm.vm.close(); + cache.closed.store(true, Ordering::Release); + cache.shared.wake_closed_vm_reclaim(); + fw.idle_poll(); + assert!(cache.shared.closed_vm_reclaim.load(Ordering::Acquire)); + assert_eq!(Arc::strong_count(&epoch), 2, "vm_last still holds the epoch"); + assert!(!cache.shared.poll_queued.load(Ordering::Acquire)); + drop(epoch); + drop(vm); + assert!(!released.load(Ordering::Acquire)); + + drop(job); + assert_eq!(cache.standby.lock().reserved, 0); + fw.idle_poll(); + assert!(!cache.shared.closed_vm_reclaim.load(Ordering::Acquire)); + assert!(released.load(Ordering::Acquire), "idle poll released the ASID and last PB epoch"); + } + + #[test] + fn passed_abort_returns_unpublished_credits_and_preserves_quarantine() { + let (mut fw, cache, vm, old_epoch, released, job) = displaced_vm(3); + let aborted = cache.standby.lock().epochs.pop().unwrap(); + aborted.prepare(1, crate::g16::hw::client::pb_heap(0), 512).unwrap(); + aborted.expose(); + fw.pools.bind(1, false); + fw.pools.hold_alloc(1, &vm, None, None).unwrap(); + fw.pools.publish_flight(1); + job.commit_render(1); + vm.vm.close(); + cache.closed.store(true, Ordering::Release); + cache.shared.wake_closed_vm_reclaim(); + fw.idle_poll(); + assert_eq!(Arc::strong_count(&old_epoch), 2); + assert_eq!(cache.standby.lock().reserved, 2); + + fw.pools.quarantine_flight(1, Some(aborted.clone())); + let retained = Arc::new(job, 0).unwrap(); + retained.discard_unpublished_renders(); + retained.discard_unpublished_renders(); + let reserved = cache.standby.lock().reserved; + assert_eq!(reserved, 0); + assert_eq!(cache.active_render_passes.load(Ordering::Acquire), 1); + fw.idle_poll(); + assert_eq!(Arc::strong_count(&old_epoch), 1, "vm_last released the displaced epoch"); + assert_eq!(fw.pools.quarantined_mask(), 1 << 1); + assert_eq!(Arc::strong_count(&aborted), 2); + assert!(retained.pb_ext[0].is_some(), "retained job still owns its arena"); + drop(old_epoch); + drop(aborted); + drop(vm); + assert!(!released.load(Ordering::Acquire), "quarantine pins the published ASID"); + drop(retained); + assert_eq!(cache.active_render_passes.load(Ordering::Acquire), 0); + } + } } pub mod boot {pub fn eproto()->crate::Error{crate::Error(71)}} pub mod engine { @@ -634,7 +851,7 @@ def module(text, name): s.release(&mut claims);s.note_published(&claims);assert_eq!(s.stats.cross_vm_retargets,[1,0]); } - fn vm(id:u64)->sync::Arc{ + pub(super) fn vm(id:u64)->sync::Arc{ sync::Arc::new( g16::vm::VmState{id,slot:id as u32,generation:1,vm:g16::vm::MockVm::new()},0, ).unwrap() @@ -3108,8 +3325,9 @@ def module(text, name): assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' assert 'closed_vm_reclaim' in mod_source -assert 'self.shared.closed_vm_reclaim.store(true, Ordering::Release);' in mod_source +assert 'self.shared.wake_closed_vm_reclaim();' in item(mod_source, 'fn vm_closed(') assert 'reclaim_closed_vm_slots' in poll_source +assert 'job.resources.discard_unpublished_renders();' in item(poll_source, 'if p.is_pending()') lifetime_source = (production.parent / 'mmu' / 'lifetime.rs').read_text() is_closed_fn = item(lifetime_source, 'pub(crate) fn is_closed(') assert '.lock()' not in is_closed_fn, 'Vm::is_closed() must be lock-free' @@ -3142,6 +3360,24 @@ def module(text, name): source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() +for placeholder, source_text, declaration in ( + ('__WAKE_PUBLISH__', mod_source, 'pub(crate) fn wake_publish('), + ('__WAKE_CLOSED_VM_RECLAIM__', mod_source, 'pub(crate) fn wake_closed_vm_reclaim('), + ('__STANDBY__', resources_source, 'struct Standby {'), + ('__RELEASE_RESERVED__', resources_source, 'fn release_reserved('), + ('__RELEASE_RENDER_PASSES__', resources_source, 'fn release_render_passes('), + ('__RENDERS_UNPUBLISHED__', resources_source, 'pub(crate) fn renders_unpublished('), + ('__PREPARED__', resources_source, 'pub(crate) struct Prepared {'), + ('__DROP_PREPARED__', resources_source, 'impl Drop for Prepared'), + ('__COMMIT_RENDER__', resources_source, 'pub(crate) fn commit_render('), + ('__DISCARD_UNPUBLISHED__', resources_source, 'pub(crate) fn discard_unpublished_renders('), + ('__RECLAIM_CLOSED_VM_SLOTS__', poll_source, 'pub(crate) fn reclaim_closed_vm_slots('), +): + method = item(source_text, declaration) + # The host Arc wrapper uses Deref without the kernel's arbitrary self types. + source = source.replace(placeholder, method.replace('self: &Arc', '&self')) +source = source.replace('__SPARE_EPOCHS__', next( + line for line in resources_source.splitlines() if line.startswith('const SPARE_EPOCHS:'))) object_source = (production/'object.rs').read_text() # A firmware-cached object with an uncached GPU lower alias is cleaned to the point of # coherency after every host store; only that combination sets the flag. @@ -3218,9 +3454,10 @@ def module(text, name): (out/'resource-host.log').write_text(log) if result.returncode: raise SystemExit(result.returncode) -files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] +files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs', 'mod.rs', 'poll.rs', 'vm.rs'] +test_count = int(next(line.split()[3] for line in log.splitlines() if line.startswith('test result: ok.'))) (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 41, + 'result': 'pass', 'tests': test_count, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes',