From ebc3b149b8ece93b512bc6b5e980ba2e50b20e2c Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 06:43:21 -0500 Subject: [PATCH 1/7] drm/asahi: g16: keep compute UMA managers bound and ASC-cached A VM's shared compute UMA manager lived in a per-VM ASC-uncached object next to its host-written counter. The firmware saves and unbinds a manager whenever a command finishes with COMPLETED equal to the counter. A client with one job at a time (8 processes in compute.light procs) paid a save and a rebind on every job, with every access to the manager uncached. Map the managers as macOS 26B123 does. In the J773g Metal procs-d8 snapshot, each of the 8 compute managers sits alone on its own page with leaf 0x443 (ASC write-back), each counter is on a separate page, and an idle manager's counter equals COMPLETED. - Each hardware compute UMA slot gets two device-lifetime manager records, ASC-cached on their own pages and never freed: 1 MiB for all 32 slots, allocated on a slot's first use. The host rewrites only a record that the firmware's slot table cannot name, so each slot needs a second record. - The counter stays on an uncached page of its own. While the manager has commands in flight it runs one past the submissions, so the firmware never saves the manager. When the manager's last command retires, the counter drops back to the submission count. An idle manager stays bound with its cursors in the hardware, and its counter equals COMPLETED, as on macOS. - The firmware's bind loads only the incoming record and never saves the outgoing manager. In 26B123, the save runs only past the COMPLETED == *counter gate. So the host tracks which manager each slot holds: - The same manager keeps its record, with no host write. - Any other return waits for the manager's own commands to retire. That covers another VM's manager or a private SCS unit taking the slot, an idle power-down, a sleep and a recovery. The host then rebuilds a record the slot table does not name, and reseeds the drained freelist and pool rows with it. - A private unit waits for shared commands in its slot. - The slot ledger keeps only identities and counts. As before, a closed VM's manager, pool and live-VM charge go when its last flight retires. - The host never reads the cached manager. Retirement uses two receipts: the service stamp, which the firmware stores after its last access to the command's work, microsequence and manager; and the GPU end tick. The firmware powers the GPU down after an idle delay, and that drops the hardware state of a manager left bound. The host checks for this only at a publication pass where it has nothing in flight and a shared manager may be bound. It reads the firmware's powered flag, which 26B123 and the T6030 firmware record, and treats every binding as stale unless the flag shows the GPU powered. Firmware without the flag keeps the GPU powered while it runs. Passes with work in flight and render-only work read nothing. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/boot.rs | 16 + drivers/gpu/drm/asahi/g16/encode.rs | 4 +- drivers/gpu/drm/asahi/g16/encode/compute.rs | 11 - drivers/gpu/drm/asahi/g16/engine.rs | 82 +++- drivers/gpu/drm/asahi/g16/object.rs | 9 + drivers/gpu/drm/asahi/g16/poll.rs | 41 +- drivers/gpu/drm/asahi/g16/recovery.rs | 1 + drivers/gpu/drm/asahi/g16/resources.rs | 188 ++++++--- drivers/gpu/drm/asahi/g16/sleep.rs | 4 +- drivers/gpu/drm/asahi/g16/slots.rs | 209 +++++++++- .../drivers/gpu/asahi-m4/check-abi-26b123.rs | 41 +- .../drivers/gpu/asahi-m4/test-publication.py | 44 +++ .../drivers/gpu/asahi-m4/test-resources.py | 365 +++++++++++++++++- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 57 +-- 14 files changed, 936 insertions(+), 136 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index 5864452f42fa3..7a9b7d39d130a 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -536,6 +536,22 @@ impl Session { read(&self.regs).map(Some) } + /// Whether the GPU may be powered down now: the firmware powers it down while idle and its + /// powered flag, read without the PPL handoff lock as a hint that can change right after, + /// does not show it powered. A firmware that records no flag keeps the GPU powered while it + /// runs. + pub(crate) fn may_be_powered_down(&self) -> bool { + let Some(offset) = self.adt.layout.powered else { + return false; + }; + self.handoff.as_ref().is_none_or(|page| { + !page + .io() + .try_read8(offset) + .is_ok_and(|powered| powered != 0) + }) + } + /// The engine receipts of a running firmware, or `None` while the GPU is powered down. pub(crate) fn engine_state(&self) -> Result> { self.while_powered(regs::Regs::engine_state) diff --git a/drivers/gpu/drm/asahi/g16/encode.rs b/drivers/gpu/drm/asahi/g16/encode.rs index ba235f4ffe596..33fa638acb765 100644 --- a/drivers/gpu/drm/asahi/g16/encode.rs +++ b/drivers/gpu/drm/asahi/g16/encode.rs @@ -99,8 +99,8 @@ use compute_encoder::put_generation; #[allow(unused_imports)] // Pure encoder utilities are exercised by the host ABI harness. pub(crate) use compute_encoder::{ encode_compute, encode_compute_for, encode_compute_rt, init_compute_pool, - preserve_compute_descriptor, validate_compute_descriptor, validate_shared_compute_descriptor, - ComputeEncodeError, ComputeRefs, ComputeRt, COMPUTE_SCS_DRIVER_WORD, + preserve_compute_descriptor, validate_compute_descriptor, ComputeEncodeError, ComputeRefs, + ComputeRt, COMPUTE_SCS_DRIVER_WORD, }; /// Tiling geometry and register words of a render (accelerator count 2). diff --git a/drivers/gpu/drm/asahi/g16/encode/compute.rs b/drivers/gpu/drm/asahi/g16/encode/compute.rs index 564e084d79fd1..c886a40da83f3 100644 --- a/drivers/gpu/drm/asahi/g16/encode/compute.rs +++ b/drivers/gpu/drm/asahi/g16/encode/compute.rs @@ -225,17 +225,6 @@ pub(crate) fn validate_compute_descriptor( validate_compute_descriptor_inner(r, old, submitted_before, true, r.work) } -/// Validates a retained VM-shared compute UMA manager descriptor at an idle boundary before reuse. -/// Unlike a per-unit descriptor whose `WORK` header holds the unit's work image VA, a VM-shared -/// descriptor anchors `WORK` to its own `descriptor_fw` VA (matching render's shared UMA manager). -pub(crate) fn validate_shared_compute_descriptor( - r: &ComputeRefs, - old: &[u8; compute::DESCRIPTOR_SIZE], - submitted_before: u64, -) -> Result { - validate_compute_descriptor_inner(r, old, submitted_before, true, r.descriptor_fw) -} - /// Restores the complete allocator descriptor into a newly encoded, unpublished work after /// the engine has proved A retired, distinct B displaced A in the same UMA slot, and B retired. /// Numeric checks here do not establish that ownership proof. The old descriptor's completion diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index d96936e9a98d1..067411a13ca19 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1095,6 +1095,9 @@ impl Firmware { self.engine.held_wait = false; self.engine.handoff_avoid_pipes = 0; self.engine.coalesce_deadline_ns = 0; + if !self.engine.pending.is_empty() { + self.note_gpu_idle_if_any(); + } while self.recovery.failed().is_none() && !self.engine.frozen && !self.engine.pending.is_empty() @@ -2120,6 +2123,23 @@ impl Firmware { Ok(waits) } + /// Once per publication pass, before anything is posted. A firmware that powers the GPU + /// down while idle drops the hardware allocator state of compute UMA managers left bound + /// under the hold; with the powered flag not showing the GPU powered, trust none of them. + /// The GPU powers up only for work this host publishes, so a powered GPU has not cycled + /// power since its last work. It powers down only after its idle delay, and every pass + /// first retires the flights whose receipts are visible, so with a flight still in flight + /// it has not powered down either. That keeps the flag read off passes with work in flight + /// and off every pass while no shared manager is held (render-only work). + fn note_gpu_idle_if_any(&mut self) { + if self.engine.flights.is_empty() + && self.slots.compute_uma_held() + && self.session.may_be_powered_down() + { + self.slots.invalidate_compute_uma(); + } + } + /// Whether `queue`'s recent or active compute work is heavy enough to benefit from 2-pipe /// CDM fanout rather than 1-pipe affinity and horizon folding: /// - per-queue retired CDM GPU duration EWMA `>= COMPUTE_HEAVY_EMA_US`, or @@ -3337,7 +3357,15 @@ impl Firmware { if f.claims.slot_count != 0 { let tail_sub = f.csubmitted[(f.claims.slot_count - 1) as usize]; shared.submitted.store(tail_sub, Ordering::Release); - shared.counter.w64(0, tail_sub)?; + // The in-flight hold keeps the manager bound between its jobs: *counter + // stays one past the submissions, so the firmware does not save and + // unbind the manager when this command finishes, and its next job finds + // the cursors still in the hardware (`Slots::bind_compute_uma`). + // `retire_oldest` writes the counter back once the manager drained, so + // an idle manager's counter equals COMPLETED, as in the macOS 26B123 + // procs-d8 snapshot (all eight managers). `prefix_compute` reserved the + // count. + shared.counter.w64(0, tail_sub.saturating_add(1))?; } } else { for m in 0..f.claims.slot_count as usize { @@ -3411,6 +3439,11 @@ impl Firmware { })(); if publication.is_ok() { self.slots.note_published(&f.claims); + if let Some(shared) = job.resources.shared_compute_uma() { + self.slots + .note_compute_uma_published(&f.claims, shared, f.computes); + } + self.slots.note_private_uma_published(&f.claims); } // From the first counter/WRITE onward an error is uncertain. Keep the complete // retained flight even when a later channel store or doorbell fails. @@ -3540,12 +3573,29 @@ impl Firmware { uma_slot, seeds, ) = if let Some(shared) = resources.shared_compute_uma() { + // The slot record this flight's commands name (`Slots::bind_compute_uma`, once per + // flight: every attempt starts from fresh claims); none yet: wait (a retirement on + // the slot repolls publication). + let rec = if f.claims.uma_rec != super::slots::NO_UMA_RECORD { + f.claims.uma_rec as usize + } else { + let Some(rec) = self.slots.bind_compute_uma(shared)? else { + self.engine.slot_wait = true; + return Err(EAGAIN); + }; + rec + }; + f.claims.uma_rec = rec as u8; + f.claims.uma_slot = shared.uma_slot_idx as u8; let base = shared.submitted.load(Ordering::Acquire); pf.uma_delta = pf.uma_delta.checked_add(1).ok_or(EOVERFLOW)?; + let submitted = base.checked_add(pf.uma_delta).ok_or(EOVERFLOW)?; + // Room for the in-flight hold on top of this submission (publication below). + submitted.checked_add(1).ok_or(EOVERFLOW)?; ( base, - base.checked_add(pf.uma_delta).ok_or(EOVERFLOW)?, - shared.descriptor.va, + submitted, + shared.records[rec].va, shared.counter.va, shared.pool_state.gva.ok_or(EINVAL)?, shared.page_list.gva.ok_or(EINVAL)?, @@ -3554,6 +3604,13 @@ impl Firmware { ) } else { let u = s.private_uma()?; + // Its own descriptor replaces whatever the slot holds: never while a shared + // manager's commands run there. + if !self.slots.compute_uma_private_ready(u.uma_slot_idx()) { + self.engine.slot_wait = true; + return Err(EAGAIN); + } + f.claims.uma_private |= 1u32 << u.uma_slot_idx(); let b = u.counter.r64(0)?; ( b, @@ -3626,21 +3683,10 @@ impl Firmware { let full_work = self.slots.compute_needs_full_work(index) || before == 0; if full_work { if before != 0 { - if let Some(shared) = resources.shared_compute_uma() { - // Validate the VM-shared UMA descriptor at idle boundaries (when no other - // flight of this VM is mutating `COMPLETED`). - if pf.uma_delta == 1 && before == shared.retired.load(Ordering::Acquire) { - let mut descriptor = [0u8; work::compute::DESCRIPTOR_SIZE]; - shared.descriptor.read(0, &mut descriptor)?; - if encode::validate_shared_compute_descriptor(&refs, &descriptor, before) - .is_err() - { - self.slots.quarantine(&mut f.claims); - self.sync_quarantine_hints(); - return Err(EIO); - } - } - } else { + // A VM-shared manager is a slot record the host initialised itself + // (`Slots::bind_compute_uma`) whose firmware-owned words are ASC-cached and not + // host-readable: only per-unit descriptors are validated in place. + if resources.shared_compute_uma().is_none() { // Slots::claim_compute proved a different fully retired unit displaced this // descriptor in the same hardware slot. Validate it in place. let mut descriptor = [0u8; work::compute::DESCRIPTOR_SIZE]; diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 887d40ad1c1d6..19ac61bcb1c71 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -492,6 +492,15 @@ impl Factory { pub(crate) fn compute_cmds(&self, k: usize) -> Result { self.compute_cmds.get(self, k) } + + /// The device-lifetime UMA manager records of hardware compute UMA slot `k`, shared by every + /// VM whose shared compute UMA uses slot `k`. + pub(crate) fn compute_uma_records( + &self, + k: usize, + ) -> Result<[Arc; super::slots::UMA_RECORDS]> { + self.compute_cmds.uma_records(self, k) + } } /// The firmware object allocator and the set of retained objects. diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 295b7b359d550..e9e39f4d02ae4 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1304,16 +1304,10 @@ impl Firmware { full &= count != 0 && count == f.computes as usize; if full { if f.job.resources.has_shared_compute_uma() { - let last_vm_flight = !self.engine.flights.iter().enumerate().any(|(idx, o)| { - idx != index && o.computes != 0 && Arc::ptr_eq(&o.job.vm, &f.job.vm) - }); - if !f - .job - .resources - .compute_uma_retired(f.computes, last_vm_flight)? - { - full = false; - } + // The VM-shared manager record is ASC-cached: its COMPLETED word is not + // host-readable. The service stamp above, stored after the firmware's last + // access to the command's work, microsequence and manager, and the GPU's end + // tick below are the receipt. if full { for m in 0..count { let k = f.claims.slot[m] as usize; @@ -1563,7 +1557,32 @@ impl Firmware { return; } if f.computes != 0 { - f.job.resources.note_compute_uma_retired(f.computes); + // UMA residency: this manager's commands (or this flight's private units) are + // done. A drained manager drops `*counter` from the in-flight hold to its + // submissions, so an idle manager's counter equals COMPLETED; it stays bound + // until another record or descriptor takes the slot (`Slots::bind_compute_uma`). + let drained = f.job.resources.shared_compute_uma().is_some_and(|shared| { + self.slots + .retire_compute_uma(×tamp_claims, shared, f.computes) + }); + self.slots.retire_private_uma(×tamp_claims); + let released = f + .job + .resources + .shared_compute_uma() + .filter(|_| drained) + .map(|shared| { + shared + .counter + .w64(0, shared.submitted.load(Ordering::Acquire)) + }); + if let Some(Err(error)) = released { + self.retain(&f.job); + complete(done, &f.job, Err(error)); + self.fail_stop(error, done); + core::mem::forget(f); + return; + } let p = (f.compute_pipe as usize).min(super::hw::sizes::COMPUTE_PIPES - 1); for &stamp in &f.cstamp[..(f.computes as usize).min(f.cstamp.len())] { self.recovery.last_retired.push(p, stamp); diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index ee64e0e687698..e1c6beab5ddfe 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -597,6 +597,7 @@ impl Firmware { // writes the fault-bank selector so it must not run against active FW). self.pools.invalidate(); self.slots.invalidate_scrub(); + self.slots.invalidate_compute_uma(); self.events.grow.clear(); let stage = self.recovery_snapshot()?; // Powered down, the GPU holds no fault to read. diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index ffc660744bab8..ee0e471c0f38d 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -87,6 +87,14 @@ struct PersistentUnitCmds { finished: bool, } +/// One hardware compute UMA slot's device-lifetime manager records and the allocator that maps +/// them, never dropped for the same reason as [`PersistentPassCmds`]. +struct PersistentUmaRecords { + objects: core::mem::ManuallyDrop, + records: [Option>; super::slots::UMA_RECORDS], + finished: bool, +} + /// The firmware-cached compute command records (work image, microsequence, and barrier records) /// of every hardware compute unit (`0..COMPUTE_UNITS`), created on first use and kept until /// reboot. A hardware compute unit is device-global and claimed by one flight at a time, so every @@ -96,6 +104,9 @@ struct PersistentUnitCmds { pub(crate) struct ComputeCmds { #[pin] sets: Mutex<[Option>; super::hw::sizes::COMPUTE_UNITS]>, + /// The ASC-cached UMA manager records of every hardware compute UMA slot. + #[pin] + uma: Mutex<[Option>; super::hw::sizes::COMPUTE_UMA_SLOTS]>, } impl ComputeCmds { @@ -106,6 +117,10 @@ impl ComputeCmds { [const { None }; super::hw::sizes::COMPUTE_UNITS], "g16::compute_cmds" ), + uma <- new_mutex!( + [const { None }; super::hw::sizes::COMPUTE_UMA_SLOTS], + "g16::compute_uma_records" + ), }), GFP_KERNEL, ) @@ -149,6 +164,50 @@ impl ComputeCmds { set.finished = true; Ok(cmds) } + + /// The manager records of hardware compute UMA slot `slot`, allocated from `factory` on + /// first use: each alone on its own ASC-cached page (`Class::FwCoherent`, leaf 0x443). + pub(crate) fn uma_records( + &self, + factory: &Factory, + slot: usize, + ) -> Result<[Arc; super::slots::UMA_RECORDS]> { + let mut sets = self.uma.lock(); + let entry = sets.get_mut(slot).ok_or(EINVAL)?; + if entry.is_none() { + let set = KBox::::new_uninit(GFP_KERNEL)?; + *entry = Some(KBox::write( + set, + PersistentUmaRecords { + objects: core::mem::ManuallyDrop::new(factory.persistent_objects()), + records: [const { None }; super::slots::UMA_RECORDS], + finished: false, + }, + )); + } + let set: &mut PersistentUmaRecords = &mut **entry.as_mut().ok_or(EINVAL)?; + if !set.finished { + // A partial failure keeps what was mapped; a retry finishes the set. + for record in set.records.iter_mut() { + if record.is_none() { + *record = Some(super::graph::alloc( + &mut set.objects, + super::fw::work::compute::DESCRIPTOR_SIZE, + super::object::Class::FwCoherent, + None, + 0, + false, + )?); + } + } + set.objects.finish_private()?; + set.finished = true; + } + Ok([ + set.records[0].clone().ok_or(EINVAL)?, + set.records[1].clone().ok_or(EINVAL)?, + ]) + } } /// Never-exposed PB epochs an open VM keeps on standby after bursts drain. @@ -158,13 +217,21 @@ impl ComputeCmds { /// avoids allocating and mapping fresh epochs whenever submission depth rises. const SPARE_EPOCHS: usize = 32; -/// Per-VM shared compute UMA manager descriptor, submission counter, and 32 MiB backing pool. +/// Per-VM shared compute UMA manager: submission counter, freelist and 32 MiB backing pool. +/// +/// All non-SCS compute units (`0..COMPUTE_UNITS`) of a VM use one manager in one hardware UMA +/// slot (`COMPUTE_UMA_SLOT + uma_slot_idx`), matching macOS 26B123, so the firmware keeps the +/// slot bound across consecutive and multi-pipe compute dispatches while `*counter > COMPLETED` +/// instead of tearing down and rebinding UMA on every dispatch. /// -/// All non-SCS compute units (`0..COMPUTE_UNITS`) of a VM reference this single descriptor and -/// hardware UMA slot (`COMPUTE_UMA_SLOT + uma_slot_idx`), matching macOS 26B123 so firmware keeps -/// the hardware UMA slot bound across consecutive and multi-pipe compute dispatches while -/// `*counter > COMPLETED` instead of tearing down and rebinding UMA on every dispatch. +/// The manager words themselves live in the slot's device-lifetime ASC-cached records +/// ([`super::slots::Slots::bind_compute_uma`]), as macOS 26B123 maps its compute managers: in the +/// J773g procs-d8 snapshot every manager is alone on its own page with leaf 0x443 and its counter +/// is on a separate page. The host-written counter stays on an uncached page of its own. pub(crate) struct SharedComputeUma(crate::cleanup::Deferred); + +/// Identity of a [`SharedComputeUma`] in the slot records it was initialised in (0: none). +static NEXT_SHARED_UMA_ID: AtomicU64 = AtomicU64::new(1); impl core::ops::Deref for SharedComputeUma { type Target = SharedComputeUmaInner; fn deref(&self) -> &Self::Target { @@ -172,7 +239,12 @@ impl core::ops::Deref for SharedComputeUma { } } pub(crate) struct SharedComputeUmaInner { - pub(crate) descriptor: Arc, + /// The device-lifetime manager records of hardware slot `uma_slot_idx`. + pub(crate) records: [Arc; super::slots::UMA_RECORDS], + /// This manager's identity in those records. + pub(crate) id: u64, + /// Set once a record was first initialised for this manager. + bound: AtomicBool, pub(crate) counter: Arc, pub(crate) pool: Arc, pub(crate) pool_state: Arc, @@ -182,7 +254,8 @@ pub(crate) struct SharedComputeUmaInner { pub(crate) uma_slot_idx: usize, pub(crate) seeds: u32, pub(crate) submitted: AtomicU64, - pub(crate) retired: AtomicU64, + /// Commands published and not yet cleanly retired (changed under the device lock). + outstanding: AtomicU32, _objects: Objects, _bind: mmu::VmBind, _live: Arc, @@ -208,11 +281,9 @@ impl SharedComputeUma { let state = placement.state(va_idx); let seeds = placement.seeds(); let uma_slot = super::hw::engine::COMPUTE_UMA_SLOT + uma_slot_idx as u32; + let records = factory.compute_uma_records(uma_slot_idx)?; let mut fw = factory.fw_objects(); - let uma_page = - super::graph::alloc(&mut fw, 0x200, super::object::Class::Fw, None, 0, false)?; - let descriptor = FwObject::view(&uma_page, 0, super::fw::work::compute::DESCRIPTOR_SIZE)?; - let counter = FwObject::view(&uma_page, 0x100, 0x80)?; + let counter = super::graph::alloc(&mut fw, 8, super::object::Class::Fw, None, 0, false)?; let uma_lease = super::object::FwLease::new(fw)?; let mut objects = factory.objects(vm); let pool = objects.alloc(super::object::Request { @@ -242,21 +313,11 @@ impl SharedComputeUma { )?; objects.finish_private()?; super::slots::init_uma_pool(&pool_state, &page_list, pool.gva.ok_or(EINVAL)?, seeds)?; - descriptor.write( - 0, - &super::fw::buffer::compute_uma_manager_image( - descriptor.va, - uma_slot, - pool_state.gva.ok_or(EINVAL)?, - page_list.gva.ok_or(EINVAL)?, - counter.va, - seeds, - super::rt::freelist_records(seeds), - ), - )?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(SharedComputeUmaInner { - descriptor, + records, + id: NEXT_SHARED_UMA_ID.fetch_add(1, Ordering::Relaxed), + bound: AtomicBool::new(false), counter, pool, pool_state, @@ -266,7 +327,7 @@ impl SharedComputeUma { uma_slot_idx, seeds, submitted: AtomicU64::new(0), - retired: AtomicU64::new(0), + outstanding: AtomicU32::new(0), _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -276,6 +337,59 @@ impl SharedComputeUma { } } +impl SharedComputeUmaInner { + /// Commands of this manager published and not yet cleanly retired. + pub(crate) fn outstanding(&self) -> u32 { + self.outstanding.load(Ordering::Acquire) + } + + /// `count` commands were published. + pub(crate) fn note_published(&self, count: u32) { + self.outstanding.fetch_add(count, Ordering::AcqRel); + } + + /// `count` commands retired cleanly; returns whether that drained the manager. + pub(crate) fn note_retired(&self, count: u32) -> bool { + let left = self.outstanding().saturating_sub(count); + self.outstanding.store(left, Ordering::Release); + left == 0 + } + + /// Initialises slot record `rec` for this manager, which has no command in flight: the + /// manager image with the allocator cursors at their seed and COMPLETED at the host's + /// submission count, so the firmware's next completion lines up with the next submission. + /// The firmware never writes a displaced or lost binding back (it saves a manager only at a + /// completion with COMPLETED equal to `*counter`, which the in-flight hold prevents), so the + /// freelist of a manager that ran before no longer matches any record. Its pool is drained: + /// seed the freelist and pool rows afresh with the cursors. + pub(crate) fn init_record(&self, rec: usize) -> Result { + let record = self.records.get(rec).ok_or(EINVAL)?; + let pool_state = self.pool_state.gva.ok_or(EINVAL)?; + let page_list = self.page_list.gva.ok_or(EINVAL)?; + if self.bound.swap(true, Ordering::AcqRel) { + super::slots::init_uma_pool( + &self.pool_state, + &self.page_list, + self.pool.gva.ok_or(EINVAL)?, + self.seeds, + )?; + } + let mut image = super::fw::buffer::compute_uma_manager_image( + record.va, + self.uma_slot, + pool_state, + page_list, + self.counter.va, + self.seeds, + super::rt::freelist_records(self.seeds), + ); + let completed = super::fw::graph::manager::COMPLETED; + image[completed..completed + 8] + .copy_from_slice(&self.submitted.load(Ordering::Acquire).to_le_bytes()); + record.write(0, &image) + } +} + /// Backing for one physical compute unit (`k`) of a VM, deferred-dropped independently so an /// undisplaced last-retired owner lease on one CDM pipe never pins the VM's other compute units. pub(crate) struct ComputeArena(crate::cleanup::Deferred); @@ -1857,30 +1971,6 @@ impl Prepared { self.compute_slot_mask().unwrap_or(0) } } - /// Whether the VM's shared compute UMA descriptor has completed at least `count` additional - /// commands beyond previously retired flights, and matches the host counter exactly when - /// `last_vm_flight` drains the VM idle. - pub(crate) fn compute_uma_retired(&self, count: u32, last_vm_flight: bool) -> Result { - let Some(uma) = &self.compute_uma else { - return Ok(false); - }; - let needed = uma - .retired - .load(Ordering::Acquire) - .saturating_add(u64::from(count)); - let counter = uma.counter.r64(0)?; - let completed = uma.descriptor.r64(super::fw::graph::manager::COMPLETED)?; - Ok(counter >= needed - && completed >= needed - && (!last_vm_flight || completed == counter) - && uma.descriptor.r64(super::fw::graph::manager::COUNTER)? == uma.counter.va) - } - /// Records `count` cleanly retired compute commands against the VM's shared UMA descriptor. - pub(crate) fn note_compute_uma_retired(&self, count: u32) { - if let Some(uma) = &self.compute_uma { - uma.retired.fetch_add(u64::from(count), Ordering::AcqRel); - } - } /// Whether this job's renders use SCS-capable render allocators. pub(crate) fn render_scs(&self) -> bool { self.render_scs diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index b51556822b075..cfd0a6a63f85c 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -60,8 +60,10 @@ impl Firmware { /// The run bit and the RTKit handshake, with the firmware's state as it was left. fn sleep_restart(&mut self) -> Result { - // Start the next render on each pass slot fresh after the firmware restarts. + // Start the next render on each pass slot fresh after the firmware restarts, and the + // next compute of every UMA manager left bound from a reloaded record. self.pools.invalidate(); + self.slots.invalidate_compute_uma(); self.session.rtkit.warm_restart()?; let control = self.session.regs.asc_control()?; self.session.regs.set_asc_control(control | ASC_RUN)?; diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index d87f49e009fc4..d9d4ccf520e9a 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -716,6 +716,39 @@ impl PassSlot { } } +/// Device-lifetime UMA manager records per hardware compute UMA slot. The firmware's slot +/// table can still name one record (the shared manager it bound last); the host rewrites only +/// a record the table does not name, which takes a second record ([`Slots::bind_compute_uma`]). +pub(crate) const UMA_RECORDS: usize = 2; +const _: () = assert!(UMA_RECORDS == 2); +/// [`Claims::uma_rec`] of a flight that names no slot record. +pub(crate) const NO_UMA_RECORD: u8 = UMA_RECORDS as u8; + +/// What the firmware's compute UMA slot table names for one hardware slot, as far as the host +/// knows. The 26B123 firmware installs a manager there when a command naming it starts (bind +/// loads the incoming record only and never saves the outgoing manager) and clears the entry +/// when it saves a manager: after a command finishes with COMPLETED equal to `*counter`, it +/// copies the hardware allocator cursors back into the record. +#[derive(Copy, Clone, PartialEq, Eq)] +enum UmaBound { + /// Nothing: never used, or the last private unit there was saved. + None, + /// Record `0..UMA_RECORDS` of the slot. + Record(u8), + /// A private (SCS) unit's own descriptor. + Private, +} + +/// The shared manager bound in a slot. Its commands run under the in-flight hold, so the +/// firmware never saves it: its allocator cursors are only in the hardware, never in its record. +#[derive(Copy, Clone)] +struct UmaLive { + id: u64, + rec: u8, + /// [`ComputeOwners::uma_live_gen`] when it was bound. + gen: u64, +} + #[derive(Copy, Clone)] pub(crate) struct Claims { pub(crate) slot: [u32; sizes::COMPUTE_SLOTS], @@ -732,6 +765,12 @@ pub(crate) struct Claims { /// `Slots::scrub_gen` observed when these claims were published; a recovery invalidation /// advances `scrub_gen` so in-flight slots still force a full scrub after retiring. pub(crate) scrub_gen: u64, + /// The UMA manager record (`0..UMA_RECORDS`, else [`NO_UMA_RECORD`]) of hardware compute + /// UMA slot `uma_slot` the shared-UMA commands name, and the hardware compute UMA slots + /// whose own descriptors private (SCS) commands name. + pub(crate) uma_rec: u8, + pub(crate) uma_slot: u8, + pub(crate) uma_private: u32, } impl Claims { pub(crate) const fn new() -> Self { @@ -746,6 +785,9 @@ impl Claims { ct_count: 0, rotating: true, scrub_gen: 0, + uma_rec: NO_UMA_RECORD, + uma_slot: 0, + uma_private: 0, } } } @@ -788,10 +830,24 @@ pub(crate) struct ComputeOwners { /// descriptor when a later owner displaces it, after its VM's client closed. arena: [Option>; sizes::COMPUTE_UNITS], pending_arena: [Option>; sizes::COMPUTE_UNITS], - /// VM-free firmware leases keeping each hardware compute UMA slot's `descriptor` + `counter` - /// mapped in context-0 UAT across closed-VM reclaim until a later compute retirement - /// overwrites firmware `uma_mgr_table[COMPUTE_UMA_SLOT + slot]`. + /// VM-free firmware leases keeping each hardware compute UMA slot's `counter` (and a private + /// unit's `descriptor`; a shared manager's record is device-lifetime) mapped in context-0 UAT + /// across closed-VM reclaim until a later compute retirement overwrites firmware + /// `uma_mgr_table[COMPUTE_UMA_SLOT + slot]`. retained_uma: [Option>; sizes::COMPUTE_UMA_SLOTS], + /// Compute UMA residency per hardware slot ([`Slots::bind_compute_uma`]): what the firmware + /// slot table names, the shared manager bound there with its cursors in the hardware, and + /// the shared and private (SCS) commands in flight there. Only identities and counts are + /// kept: no VM storage stays alive for the ledger. + uma_bound: [UmaBound; sizes::COMPUTE_UMA_SLOTS], + uma_live: [Option; sizes::COMPUTE_UMA_SLOTS], + uma_shared_flights: [u32; sizes::COMPUTE_UMA_SLOTS], + uma_private_flights: [u32; sizes::COMPUTE_UMA_SLOTS], + /// Advanced whenever the hardware allocator state of bound managers may be gone + /// ([`Slots::invalidate_compute_uma`]). + uma_live_gen: u64, + /// A shared manager was bound since the last advance of [`Self::uma_live_gen`]. + uma_held: bool, pending_uma: [Option>; sizes::COMPUTE_UNITS], pending_uma_slot: [usize; sizes::COMPUTE_UNITS], /// In-flight VM-shared compute UMA backing (`None` for private/SCS units). Dropped on clean @@ -1086,6 +1142,12 @@ impl Slots { arena: [const { None }; sizes::COMPUTE_UNITS], pending_arena: [const { None }; sizes::COMPUTE_UNITS], retained_uma: [const { None }; sizes::COMPUTE_UMA_SLOTS], + uma_bound: [UmaBound::None; sizes::COMPUTE_UMA_SLOTS], + uma_live: [None; sizes::COMPUTE_UMA_SLOTS], + uma_shared_flights: [0; sizes::COMPUTE_UMA_SLOTS], + uma_private_flights: [0; sizes::COMPUTE_UMA_SLOTS], + uma_live_gen: 0, + uma_held: false, pending_uma: [const { None }; sizes::COMPUTE_UNITS], pending_uma_slot: [sizes::COMPUTE_UMA_SLOTS; sizes::COMPUTE_UNITS], pending_shared_uma: [const { None }; sizes::COMPUTE_UNITS], @@ -1934,6 +1996,147 @@ impl Slots { }) } + /// The slot record `shared`'s next command names, or `None` while it has to wait (a + /// retirement on the slot repolls publication). [`Self::note_compute_uma_published`] + /// records the use once it is visible. + /// + /// Every shared command is published under the in-flight hold, so the firmware never saves a + /// shared manager: while it is bound its allocator cursors are only in the hardware, and + /// binding another record or descriptor in the slot drops them. So, in order: + /// - The manager is still bound in this residency generation (its own commands are in + /// flight, or it drained and nothing since could have dropped the hardware state: see + /// [`Self::invalidate_compute_uma`]): keep its record and write nothing. + /// - Commands of another user of the slot (a private SCS unit, or this manager while its + /// binding is uncertain) are in flight: wait. Another VM's manager never runs in the slot + /// at the same time (the engine's UMA conflict check). + /// - Otherwise its cursors are gone (displaced, or lost over an idle power-down, a sleep or + /// a recovery): rebuild a record the slot table does not name + /// ([`super::resources::SharedComputeUmaInner::init_record`] reseeds the drained freelist + /// and pool rows and restarts the cursors and COMPLETED together). + pub(crate) fn bind_compute_uma( + &mut self, + shared: &Arc, + ) -> Result> { + let slot = shared.uma_slot_idx; + if slot >= sizes::COMPUTE_UMA_SLOTS { + return Err(EINVAL); + } + let c = &mut self.compute; + if let Some(live) = c.uma_live[slot] { + if live.id == shared.id && live.gen == c.uma_live_gen { + return Ok(Some(live.rec as usize)); + } + } + if shared.outstanding() != 0 || c.uma_private_flights[slot] != 0 { + return Ok(None); + } + let rec = (0..UMA_RECORDS) + .find(|&r| c.uma_bound[slot] != UmaBound::Record(r as u8)) + .ok_or(EINVAL)?; + shared.init_record(rec)?; + Ok(Some(rec)) + } + + /// Whether a private (SCS) command may bind its own descriptor in hardware compute UMA slot + /// `slot` now: no shared manager's commands are in flight there. + pub(crate) fn compute_uma_private_ready(&self, slot: usize) -> bool { + self.compute + .uma_shared_flights + .get(slot) + .is_some_and(|&flights| flights == 0) + } + + /// Records a visible publication of `count` commands of `shared` naming slot record + /// `f.uma_rec`. + pub(crate) fn note_compute_uma_published( + &mut self, + f: &Claims, + shared: &super::resources::SharedComputeUma, + count: u32, + ) { + let (slot, rec) = (f.uma_slot as usize, f.uma_rec as usize); + if rec >= UMA_RECORDS || slot >= sizes::COMPUTE_UMA_SLOTS || slot != shared.uma_slot_idx { + return; + } + let c = &mut self.compute; + c.uma_bound[slot] = UmaBound::Record(rec as u8); + c.uma_live[slot] = Some(UmaLive { + id: shared.id, + rec: rec as u8, + gen: c.uma_live_gen, + }); + c.uma_shared_flights[slot] = c.uma_shared_flights[slot].saturating_add(count); + c.uma_held = true; + shared.note_published(count); + } + + /// Records a visible publication of private (SCS) commands in the slots `f.uma_private`: + /// each binds its own descriptor there, displacing the shared manager bound there. + pub(crate) fn note_private_uma_published(&mut self, f: &Claims) { + let c = &mut self.compute; + let mut mask = f.uma_private & COMPUTE_UMA_MASK; + while mask != 0 { + let slot = mask.trailing_zeros() as usize; + mask &= mask - 1; + c.uma_private_flights[slot] = c.uma_private_flights[slot].saturating_add(1); + c.uma_bound[slot] = UmaBound::Private; + c.uma_live[slot] = None; + } + } + + /// Records the clean retirement of a flight whose `count` commands used `shared`. Returns + /// whether that drained the manager, so its counter has to drop from the in-flight hold to + /// its submission count. The manager stays bound, with its cursors in the hardware, until + /// another record or descriptor takes the slot. Aborted flights never come here: their slot + /// stays quarantined with the manager, outside this accounting, and no shared or private + /// command publishes in a quarantined slot again. + pub(crate) fn retire_compute_uma( + &mut self, + f: &Claims, + shared: &super::resources::SharedComputeUma, + count: u32, + ) -> bool { + let (slot, rec) = (f.uma_slot as usize, f.uma_rec as usize); + if rec >= UMA_RECORDS || slot >= sizes::COMPUTE_UMA_SLOTS || slot != shared.uma_slot_idx { + return false; + } + let c = &mut self.compute; + c.uma_shared_flights[slot] = c.uma_shared_flights[slot].saturating_sub(count); + shared.note_retired(count) + } + + /// Records the clean retirement of a flight with private (SCS) commands in the slots + /// `f.uma_private`. A private unit retires only once its counter and COMPLETED both equal + /// its submissions, so the firmware saved it and cleared the slot entry. + pub(crate) fn retire_private_uma(&mut self, f: &Claims) { + let c = &mut self.compute; + let mut mask = f.uma_private & COMPUTE_UMA_MASK; + while mask != 0 { + let slot = mask.trailing_zeros() as usize; + mask &= mask - 1; + c.uma_private_flights[slot] = c.uma_private_flights[slot].saturating_sub(1); + if c.uma_private_flights[slot] == 0 && c.uma_bound[slot] == UmaBound::Private { + c.uma_bound[slot] = UmaBound::None; + } + } + } + + /// The hardware allocator state of bound shared managers may be gone: the GPU powered down + /// while idle, a system sleep restarted the firmware, or a recovery reloaded or abandoned + /// slots. Trust none of them: each rebuilds a record the slot table does not name, with a + /// reseeded freelist, once its own commands have retired. + pub(crate) fn invalidate_compute_uma(&mut self) { + let c = &mut self.compute; + c.uma_live_gen = c.uma_live_gen.wrapping_add(1); + c.uma_held = false; + } + + /// Whether a shared manager may be bound with its cursors only in the hardware: one was + /// bound since the last [`Self::invalidate_compute_uma`]. + pub(crate) fn compute_uma_held(&self) -> bool { + self.compute.uma_held + } + /// Records a host transfer only after every queue producer and doorbell succeeded. /// Full wire retirement is a separate condition for hardware qualification. pub(crate) fn note_published(&mut self, f: &Claims) { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs index 710decfdd57f4..05e24bd47f8f5 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/check-abi-26b123.rs @@ -281,9 +281,9 @@ fn compute_work(out: &std::path::Path) { assert!(w[0x89b..0x8ab].iter().all(|&b| b == 0)); assert!(w[0x8e0..compute::SEQ_EMBEDDED].iter().all(|&b| b == 0), "beyond the cached prefix"); assert_eq!(&w[compute::SEQ_EMBEDDED..compute::SEQ_EMBEDDED + compute::SEQ_SIZE], &q[..]); - // Separate uncached descriptor_fw: work+0x86a and seq+0x160 point to descriptor_fw, + // Separate descriptor_fw: work+0x86a and seq+0x160 point to descriptor_fw, // compute_uma_manager_image matches the embedded descriptor layout, and displaced-reuse - // validation checks manager::INDEX against r.uma_slot. + // validation of private descriptors checks manager::INDEX against r.uma_slot. let r_sep = encode::ComputeRefs { descriptor_fw: f + 0x580000, ..r }; let (mut w_sep, mut q_sep) = ([0xa5; compute::WORK_SIZE], [0xa5; compute::SEQ_SIZE]); encode::encode_compute_for( @@ -306,25 +306,40 @@ fn compute_work(out: &std::path::Path) { bad_idx[fw::graph::manager::INDEX..fw::graph::manager::INDEX + 4] .copy_from_slice(&(r_sep.uma_slot + 1).to_le_bytes()); assert!(encode::validate_compute_descriptor(&r_sep, &bad_idx, r_sep.submitted - 1).is_err()); + // A VM-shared manager is a slot record the host fills before publication + // (`SharedComputeUmaInner::init_record`) and never reads back: WORK anchored to the record's + // own VA, the physical slot, the counter pointer, the allocator cursors and total at their + // seed, then COMPLETED at the host's submission count. let mut shared_desc = fw::buffer::compute_uma_manager_image( r_sep.descriptor_fw, r_sep.uma_slot, r_sep.pool_state_gva, r_sep.page_list_gva, r_sep.counter_fw, 8192, fw::graph::manager::UNK_1C_VALUE, ); + let word = |b: &[u8], o: usize| u32::from_le_bytes(b[o..o + 4].try_into().unwrap()); + assert_eq!(r64(&shared_desc, fw::graph::manager::WORK), r_sep.descriptor_fw, "self VA"); + assert_eq!(word(&shared_desc, fw::graph::manager::INDEX), r_sep.uma_slot, "physical slot"); + assert_eq!(r64(&shared_desc, fw::graph::manager::COUNTER), r_sep.counter_fw, "counter pointer"); + assert_eq!( + ( + word(&shared_desc, 0x20), + word(&shared_desc, 0x24), + word(&shared_desc, 0x28), + word(&shared_desc, 0x2c), + ), + (0, 8192, 0, 8192), + "head, tail, flag and total at their seed", + ); + assert_eq!(r64(&shared_desc, fw::graph::manager::COMPLETED), 0); shared_desc[fw::graph::manager::COMPLETED..fw::graph::manager::COMPLETED + 8] .copy_from_slice(&(r_sep.submitted - 1).to_le_bytes()); assert_eq!( - encode::validate_shared_compute_descriptor(&r_sep, &shared_desc, r_sep.submitted - 1), - Ok(r_sep.submitted), - ); - assert!( - encode::validate_shared_compute_descriptor(&r_sep, &desc, r_sep.submitted - 1).is_err() + r64(&shared_desc, fw::graph::manager::COMPLETED), + r_sep.submitted - 1, + "initial completion ordinal" ); - let mut bad_shared = shared_desc; - bad_shared[fw::graph::manager::INDEX..fw::graph::manager::INDEX + 4] - .copy_from_slice(&(r_sep.uma_slot + 1).to_le_bytes()); - assert!( - encode::validate_shared_compute_descriptor(&r_sep, &bad_shared, r_sep.submitted - 1) - .is_err() + assert_ne!( + &shared_desc[..8], + &desc[..8], + "a shared record is self-anchored, not work-anchored" ); for (name, (w, q)) in ["25g83", "26b123"].iter().zip(&images) { let mut all = w.to_vec(); all.extend(q); 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 eb610c5c55293..85dab5d7774d3 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -179,8 +179,15 @@ def item(declaration): } } struct Recovery{error:Option,publication_wait_deadline:Option}impl Recovery{fn failed(&self)->Option{self.error}} +// Compute UMA idle check (engine.rs `note_gpu_idle_if_any`): whether a shared manager is held +// (slots.rs residency, which test-resources.py covers), the powered-flag reads and invalidations. +#[derive(Copy,Clone)]struct UmaIdle{held:bool,down:bool,reads:u32,invalidations:u32} +thread_local!{static UMA_IDLE:std::cell::Cell=const{std::cell::Cell::new(UmaIdle{held:false,down:false,reads:0,invalidations:0})};} +impl Session{fn may_be_powered_down(&self)->bool{UMA_IDLE.with(|u|{let mut s=u.get();s.reads+=1;u.set(s);s.down})}} struct Slots{compute_exhausted:bool,render_exhausted:bool,releases:u32,quarantines:u32} impl Slots{ + fn compute_uma_held(&self)->bool{UMA_IDLE.with(|u|u.get().held)} + fn invalidate_compute_uma(&mut self){UMA_IDLE.with(|u|{let mut s=u.get();s.invalidations+=1;s.held=false;u.set(s);})} fn compute_exhausted(&self)->bool{self.compute_exhausted} fn render_exhausted(&self)->bool{self.render_exhausted} fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted}fn compute_exhausted_in_mask(&self,_mask:u32)->bool{self.compute_exhausted} @@ -271,6 +278,7 @@ def item(declaration): true } fn service_power(&self)->Result{Ok(())} + __NOTE_GPU_IDLE_IF_ANY__ fn drain_rings(&mut self)->Result{Ok(())} fn check_hangs(&mut self,_done:&mut Completions)->Result{Ok(())} fn retain(&mut self,job:&Arc){self.retained.push(job.id);} @@ -1282,6 +1290,41 @@ def item(declaration): assert_eq!(r2r, WaitTarget { stamp: 0x900, initbm: true }); assert_eq!(cross_engine_barrier_type(r2r.initbm, false), BarrierType::Hold); } + #[test]fn uma_idle_check_reads_the_powered_flag_only_for_a_held_manager_on_an_idle_engine(){ + let set=|held,down|UMA_IDLE.with(|u|u.set(UmaIdle{held,down,reads:0,invalidations:0})); + let seen=||UMA_IDLE.with(|u|{let s=u.get();(s.reads,s.invalidations)}); + let mut done=vec![]; + // No shared manager held (render-only work): no flag read on any pass. + set(false,true); + let mut fw=firmware(vec![job(1,true,0,Ok(()))],vec![(Ok(()),true)]); + fw.publish_checked(&mut done).unwrap(); + assert_eq!(fw.engine.flights.len(),1); + fw.allow_behind=true; + fw.engine.pending.push(job(2,true,0,Ok(()))); + fw.stages.push_back(Stage{result:Ok(()),visible:true}); + fw.publish_checked(&mut done).unwrap(); + assert_eq!(seen(),(0,0)); + // A held manager and a flight in flight: the GPU has not powered down, no read. + set(true,true); + fw.engine.pending.push(job(3,false,0,Ok(()))); + fw.stages.push_back(Stage{result:Ok(()),visible:true}); + fw.publish_checked(&mut done).unwrap(); + assert_eq!(seen(),(0,0)); + // A held manager on an idle engine: one read; powered down invalidates, powered keeps. + set(true,true); + let mut fw=firmware(vec![job(4,false,0,Ok(()))],vec![(Ok(()),true)]); + fw.publish_checked(&mut done).unwrap(); + assert_eq!(seen(),(1,1)); + set(true,false); + let mut fw=firmware(vec![job(5,false,0,Ok(()))],vec![(Ok(()),true)]); + fw.publish_checked(&mut done).unwrap(); + assert_eq!(seen(),(1,0)); + // Nothing pending: no pass work at all. + set(true,true); + let mut fw=firmware(vec![],vec![]); + fw.publish_checked(&mut done).unwrap(); + assert_eq!(seen(),(0,0)); + } #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); let mut done=vec![]; @@ -3245,6 +3288,7 @@ def item(declaration): '__PUBLISH_PREFIX__': 'fn publish_prefix(', '__PUBLISH__': 'pub(crate) fn publish(&mut self', '__PUBLISH_CHECKED__': 'pub(crate) fn publish_checked(&mut self', + '__NOTE_GPU_IDLE_IF_ANY__': 'fn note_gpu_idle_if_any(', '__NEEDS_ENGINE_DRAIN__': 'fn needs_engine_drain(', '__RENDER_CAN_PIPELINE__': 'fn render_can_pipeline(', '__HOLD_CAUSE__': 'enum HoldCause {', 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 ae24513eef697..ac101f9b9472e 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -136,6 +136,17 @@ def module(text, name): pub fn fw_objects(&self)->Objects{Objects::new()} pub fn persistent_objects(&self)->Objects{Objects::persistent()} pub fn persistent_objects_probe(&self)->Objects{Objects::persistent()} + // resources::ComputeCmds::uma_records: two FwCoherent records per hardware UMA slot, + // allocated once per test thread from the never-dropped allocator. + pub fn compute_uma_records(&self,k:usize)->Result<[Arc;crate::g16::slots::UMA_RECORDS]>{ + if let Some(r)=UMA_RECORD_SETS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return Ok(r);} + let r=PERSISTENT.with(|p|{ + let mut p=p.borrow_mut();let o=p.get_or_insert_with(Objects::persistent); + let mut rec=||crate::g16::graph::alloc(o,crate::g16::fw::work::compute::DESCRIPTOR_SIZE,Class::FwCoherent,None,0,false); + Ok::<_,crate::Error>([rec()?,rec()?]) + })?; + UMA_RECORD_SETS.with(|p|p.borrow_mut().push((k,r.clone())));Ok(r) + } } pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} @@ -172,6 +183,7 @@ def module(text, name): pub static PERSISTENT:std::cell::RefCell>=const{std::cell::RefCell::new(None)}; pub static PASS_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; pub static UNIT_CMDS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; + pub static UMA_RECORD_SETS:std::cell::RefCell;crate::g16::slots::UMA_RECORDS])>>=const{std::cell::RefCell::new(Vec::new())}; } pub fn test_cmds(k:u64)->crate::g16::slots::PassCmds{ if let Some(c)=PASS_CMDS.with(|p|p.borrow().iter().find(|e|e.0==k).map(|e|e.1.clone())){return c;} @@ -255,6 +267,15 @@ def module(text, name): pub struct Registry{pub live:std::sync::Arc}impl Registry{fn release(&self,_file:u64,_process:usize){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ + // A VM's live token charged to one file's admission count `live`. + pub fn test_live_token_in(live: &std::sync::Arc) -> (mmu::VmBind, Arc, std::sync::Arc) { + live.fetch_add(1, Ordering::AcqRel); + let released = std::sync::Arc::new(AtomicBool::new(false)); + let registry = Arc::new(Registry { live: live.clone() }, 0).unwrap(); + let bind = mmu::VmBind { live: live.clone(), released: released.clone() }; + let token = Arc::new(LiveToken { registry, bind: Some(bind.clone()), file_id: 0, process: 0 }, 0).unwrap(); + (bind, token, released) + } pub fn test_live_token() -> (mmu::VmBind, Arc, std::sync::Arc) { let live = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(1)); let released = std::sync::Arc::new(AtomicBool::new(false)); @@ -274,7 +295,7 @@ def module(text, name): } } pub mod resources { - use core::sync::atomic::{AtomicU32,AtomicU64,Ordering};use crate::*; + use core::sync::atomic::{AtomicBool,AtomicU32,AtomicU64,Ordering};use crate::*; use crate::sync::Arc; use super::object::{Factory,FwObject,Objects}; use super::slots::Placement; @@ -3414,17 +3435,20 @@ def module(text, name): } } __PERSISTENT_UNIT_CMDS__ + __PERSISTENT_UMA_RECORDS__ __COMPUTE_CMDS_STRUCT__ impl ComputeCmds { pub(crate) fn new() -> Result> { Arc::new( Self { sets: Mutex::new([const { None }; hw::sizes::COMPUTE_UNITS]), + uma: Mutex::new([const { None }; hw::sizes::COMPUTE_UMA_SLOTS]), }, GFP_KERNEL, ) } __COMPUTE_CMDS_GET__ + __COMPUTE_UMA_RECORDS_GET__ } #[test] fn failed_finish_private_retries_sync_and_failed_kbox_skips_persistent_objects() { @@ -3468,6 +3492,36 @@ def module(text, name): assert!(Arc::ptr_eq(&first.seq, &second.seq)); assert!(Arc::ptr_eq(&first.barrier, &second.barrier)); } + + #[test] + fn uma_records_allocate_once_per_slot_and_retry_a_failed_finish() { + let window = Arc::new(Mutex::new(Window::new()), GFP_KERNEL).unwrap(); + window.lock().fail_once.store(true, Ordering::Release); + let factory = Factory { window: window.clone(), persistent_calls: AtomicUsize::new(0) }; + let cmds = ComputeCmds::new().unwrap(); + crate::FAIL_KBOX_UNINIT.with(|f| f.set(true)); + assert_eq!(cmds.uma_records(&factory, 3).err(), Some(ENOMEM)); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 0); + let before = crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()); + assert_eq!(cmds.uma_records(&factory, 3).err(), Some(EIO)); + assert_eq!(crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()) - before, 2); + let first = cmds.uma_records(&factory, 3).unwrap(); + assert_eq!(crate::g16::object::ALL_OBJECTS.with(|a| a.borrow().len()) - before, 2, "retry maps nothing new"); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 2); + let again = cmds.uma_records(&factory, 3).unwrap(); + assert_eq!(window.lock().calls.load(Ordering::Relaxed), 2); + for (a, b) in first.iter().zip(again.iter()) { assert!(Arc::ptr_eq(a, b)); } + for r in &first { + assert_eq!(r.class, crate::g16::object::Class::FwCoherent); + assert_eq!(r.size, crate::g16::fw::work::compute::DESCRIPTOR_SIZE); + assert!(r.gva.is_none(), "firmware-only record"); + } + assert_ne!(first[0].va & !0x3fff, first[1].va & !0x3fff, "each record alone on its page"); + let other = cmds.uma_records(&factory, 4).unwrap(); + assert!(!Arc::ptr_eq(&other[0], &first[0])); + assert_eq!(factory.persistent_calls.load(Ordering::Relaxed), 2); + assert_eq!(cmds.uma_records(&factory, hw::sizes::COMPUTE_UMA_SLOTS).err(), Some(EINVAL)); + } } #[test] @@ -3695,6 +3749,302 @@ def module(text, name): drop(uma_a); } + // Compute UMA residency (slots.rs `bind_compute_uma`): the 26B123 firmware binds a manager by + // loading its record only, never writes a displaced binding back, and saves a manager (copying + // the hardware cursors into its record) only at a completion with COMPLETED == *counter, which + // the in-flight hold prevents for shared managers. + mod uma_residency { + use super::*; + use std::sync::atomic::{AtomicU32, Ordering}; + use g16::fw::graph::manager; + use g16::resources::SharedComputeUma; + type Uma = sync::Arc; + pub(super) fn rd64(o: &g16::object::FwObject, off: usize) -> u64 { + let d = o.snapshot(); + u64::from_le_bytes(d[o.offset + off..o.offset + off + 8].try_into().unwrap()) + } + fn writes(o: &g16::object::FwObject) -> usize { + o.write_bytes.load(Ordering::Relaxed) + } + // Host writes to a manager's slot records, freelist and pool rows. + fn uma_writes(u: &SharedComputeUma) -> usize { + u.records.iter().map(|r| writes(r)).sum::() + writes(&u.pool_state) + writes(&u.page_list) + } + fn new_uma(id: u64, slot: usize) -> (Uma, sync::Arc, crate::mmu::VmBind, sync::Arc) { + let v = vm(id); + let (bind, live, _) = g16::vm::test_live_token(); + let u = SharedComputeUma::new(&g16::object::Factory, &bind, &v.vm, &live, slot, 0).unwrap(); + (u, v, bind, live) + } + // prefix_compute + the publication closure (counter under the in-flight hold) + + // note_compute_uma_published. + pub(super) fn publish(s: &mut Slots, u: &Uma, count: u32) -> Option { + let rec = s.bind_compute_uma(u).unwrap()?; + let mut c = Claims::new(); + c.uma_rec = rec as u8; + c.uma_slot = u.uma_slot_idx as u8; + let sub = u.submitted.load(Ordering::Acquire).checked_add(u64::from(count)).unwrap(); + let held = sub.checked_add(1).unwrap(); + u.submitted.store(sub, Ordering::Release); + u.counter.w64(0, held).unwrap(); + s.note_compute_uma_published(&c, u, count); + Some(c) + } + // poll::retire_oldest: a drained manager drops its counter to its submissions. + pub(super) fn retire(s: &mut Slots, u: &SharedComputeUma, c: &Claims, count: u32) -> bool { + let drained = s.retire_compute_uma(c, u, count); + if drained { + u.counter.w64(0, u.submitted.load(Ordering::Acquire)).unwrap(); + } + drained + } + // The record the host built for `u` before publishing `published` commands: the manager + // image with the cursors at their seed and COMPLETED at the earlier submissions. + fn assert_rebuilt(u: &SharedComputeUma, rec: usize, published: u64) { + let r = &u.records[rec]; + let mut want = g16::fw::buffer::compute_uma_manager_image( + r.va, u.uma_slot, u.pool_state.gva.unwrap(), u.page_list.gva.unwrap(), u.counter.va, + u.seeds, g16::rt::freelist_records(u.seeds), + ); + want[manager::COMPLETED..manager::COMPLETED + 8] + .copy_from_slice(&(u.submitted.load(Ordering::Acquire) - published).to_le_bytes()); + let d = r.snapshot(); + assert_eq!(&d[r.offset..r.offset + manager::SIZE], &want[..]); + let w = |o: usize| u32::from_le_bytes(d[r.offset + o..r.offset + o + 4].try_into().unwrap()); + assert_eq!((w(0x20), w(0x24), w(0x28), w(0x2c)), (0, u.seeds, 0, u.seeds)); + } + // Freelist seed pattern and pool rows as `init_uma_pool` writes them. + fn assert_seeded(u: &SharedComputeUma) { + let pool = u.pool.gva.unwrap(); + for i in [0usize, 1, 63, 64, u.seeds as usize - 1] { + assert_eq!(rd64(&u.pool_state, i * 8), pool + i as u64 * 0x1000, "freelist seed {i}"); + } + assert_eq!(rd64(&u.page_list, 0), (1u64 << 61) | pool); + } + // What the firmware leaves behind while it runs a manager: allocations moved its + // freelist, and its hardware cursors are ahead of its record. + fn run_on_gpu(u: &SharedComputeUma) { + u.pool_state.w64(0, 0xdead_0000).unwrap(); + u.pool_state.w64(8 * 64, 0xdead_1000).unwrap(); + u.page_list.w64(0, 0).unwrap(); + } + + #[test] + fn return_after_displacement_rebuilds_record_and_reseeds_freelist() { + let mut s = Slots::new().unwrap(); + let (a, _va, _ba, _la) = new_uma(3001, 5); + let (b, _vb, _bb, _lb) = new_uma(3002, 5); + // A runs under the hold: the firmware keeps it bound and never saves it. + let ca = publish(&mut s, &a, 2).unwrap(); + let ra = ca.uma_rec; + assert_rebuilt(&a, ra as usize, 2); + assert_eq!(rd64(&a.counter, 0), 3); + run_on_gpu(&a); + assert!(retire(&mut s, &a, &ca, 2), "drained"); + assert_eq!(rd64(&a.counter, 0), 2, "counter back at the submissions"); + // B (a 33rd VM sharing the slot) binds a record the slot table does not name, + // displacing A's binding: A's cursors are lost with it. + let cb = publish(&mut s, &b, 1).unwrap(); + assert_ne!(cb.uma_rec, ra, "the record the slot table names is never rewritten"); + assert_rebuilt(&b, cb.uma_rec as usize, 1); + assert!(retire(&mut s, &b, &cb, 1)); + // A returns: its record and its whole freelist are rebuilt. + let before = (writes(&a.pool_state), writes(&a.page_list)); + let ca2 = publish(&mut s, &a, 1).unwrap(); + assert_ne!(ca2.uma_rec, cb.uma_rec, "B's binding keeps its record"); + assert_rebuilt(&a, ca2.uma_rec as usize, 1); + assert_seeded(&a); + assert_eq!(writes(&a.pool_state) - before.0, a.seeds as usize * 8, "whole freelist reseeded"); + assert_eq!(writes(&a.page_list) - before.1, (a.seeds / g16::rt::SEEDS_PER_ROW) as usize * 8, "every pool row"); + assert_eq!(rd64(&a.counter, 0), 4); + assert!(retire(&mut s, &a, &ca2, 1)); + // B returns after A: rebuilt as well. + run_on_gpu(&b); + let wb = uma_writes(&b); + let cb2 = publish(&mut s, &b, 1).unwrap(); + assert_ne!(cb2.uma_rec, ca2.uma_rec); + assert!(uma_writes(&b) > wb); + assert_rebuilt(&b, cb2.uma_rec as usize, 1); + assert_seeded(&b); + } + + #[test] + fn same_manager_returns_without_writes() { + let mut s = Slots::new().unwrap(); + let (a, _v, _b, _l) = new_uma(3011, 2); + let c1 = publish(&mut s, &a, 1).unwrap(); + // Overlapping jobs of the bound manager: same record, nothing written. + let w = uma_writes(&a); + let c2 = publish(&mut s, &a, 3).unwrap(); + assert_eq!(c2.uma_rec, c1.uma_rec); + assert_eq!(uma_writes(&a), w); + assert_eq!(rd64(&a.counter, 0), 5); + assert!(!retire(&mut s, &a, &c1, 1)); + assert_eq!(rd64(&a.counter, 0), 5, "still held while commands run"); + assert!(retire(&mut s, &a, &c2, 3)); + assert_eq!(rd64(&a.counter, 0), 4); + // Drained and still bound in this residency generation: one job at a time keeps + // the binding with no host write to the record, freelist or pool rows. + for n in 0..4u64 { + let c = publish(&mut s, &a, 1).unwrap(); + assert_eq!(c.uma_rec, c1.uma_rec); + assert_eq!(rd64(&a.counter, 0), 6 + n); + assert!(retire(&mut s, &a, &c, 1)); + assert_eq!(rd64(&a.counter, 0), 5 + n); + } + assert_eq!(uma_writes(&a), w); + } + + #[test] + fn private_unit_displaces_shared_manager_and_waits_for_it() { + let mut s = Slots::new().unwrap(); + let (a, _v, _b, _l) = new_uma(3021, 7); + let slot = a.uma_slot_idx; + let ca = publish(&mut s, &a, 1).unwrap(); + assert!(!s.compute_uma_private_ready(slot), "SCS waits for shared commands in the slot"); + assert!(s.compute_uma_private_ready(slot + 1)); + assert!(retire(&mut s, &a, &ca, 1)); + assert!(s.compute_uma_private_ready(slot)); + // An SCS unit binds its own descriptor in the slot. + let mut p = Claims::new(); + p.uma_private = 1u32 << slot; + s.note_private_uma_published(&p); + assert_eq!(s.bind_compute_uma(&a).unwrap(), None, "shared waits for the private unit"); + s.retire_private_uma(&p); + run_on_gpu(&a); + let ca2 = publish(&mut s, &a, 1).unwrap(); + assert_rebuilt(&a, ca2.uma_rec as usize, 1); + assert_seeded(&a); + assert!(retire(&mut s, &a, &ca2, 1)); + // Every private unit in between costs the next shared job a rebuild. + s.note_private_uma_published(&p); + s.retire_private_uma(&p); + let w = uma_writes(&a); + let ca3 = publish(&mut s, &a, 1).unwrap(); + assert!(uma_writes(&a) > w); + assert_rebuilt(&a, ca3.uma_rec as usize, 1); + } + + #[test] + fn invalidation_rebuilds_once_own_commands_retire() { + let mut s = Slots::new().unwrap(); + let (a, _v, _b, _l) = new_uma(3031, 3); + let (b, _vb, _bb, _lb) = new_uma(3032, 4); + assert!(!s.compute_uma_held(), "no idle check until a shared manager is bound"); + let ca = publish(&mut s, &a, 1).unwrap(); + assert!(s.compute_uma_held()); + let cb = publish(&mut s, &b, 1).unwrap(); + assert!(retire(&mut s, &a, &ca, 1)); + assert!(retire(&mut s, &b, &cb, 1)); + assert!(s.compute_uma_held(), "drained managers stay bound"); + // An idle power-down, a sleep or a recovery: no binding is trusted. Each rebuilds + // in the record the slot table does not name. + s.invalidate_compute_uma(); + assert!(!s.compute_uma_held()); + run_on_gpu(&a); + run_on_gpu(&b); + let (wa, wb) = (uma_writes(&a), uma_writes(&b)); + let ca2 = publish(&mut s, &a, 1).unwrap(); + let cb2 = publish(&mut s, &b, 1).unwrap(); + assert!(uma_writes(&a) > wa && uma_writes(&b) > wb); + assert_ne!(ca2.uma_rec, ca.uma_rec); + assert_ne!(cb2.uma_rec, cb.uma_rec); + assert_rebuilt(&a, ca2.uma_rec as usize, 1); + assert_rebuilt(&b, cb2.uma_rec as usize, 1); + assert_seeded(&a); + assert_seeded(&b); + // Invalidated while its own commands run: it waits for them, then rebuilds. + s.invalidate_compute_uma(); + assert_eq!(s.bind_compute_uma(&a).unwrap(), None); + assert!(retire(&mut s, &a, &ca2, 1)); + let ca3 = publish(&mut s, &a, 1).unwrap(); + assert_ne!(ca3.uma_rec, ca2.uma_rec); + assert_rebuilt(&a, ca3.uma_rec as usize, 1); + // The same generation again: back on the fast path. + assert!(retire(&mut s, &a, &ca3, 1)); + let w = uma_writes(&a); + let ca4 = publish(&mut s, &a, 1).unwrap(); + assert_eq!(ca4.uma_rec, ca3.uma_rec); + assert_eq!(uma_writes(&a), w); + } + + #[test] + fn mixed_shared_and_private_retirement() { + let mut s = Slots::new().unwrap(); + let (a, _v, _b, _l) = new_uma(3041, 1); + let (c, _vc, _bc, _lc) = new_uma(3042, 6); + // Flight 1: one shared command of A in slot 1 and an SCS unit in slot 6. + let mut f1 = publish(&mut s, &a, 1).unwrap(); + f1.uma_private = 1u32 << 6; + s.note_private_uma_published(&f1); + assert_eq!(rd64(&a.counter, 0), 2); + // Flight 2: one more shared command of A. + let f2 = publish(&mut s, &a, 1).unwrap(); + assert_eq!(f2.uma_rec, f1.uma_rec); + assert_eq!(a.outstanding(), 2); + assert_eq!(rd64(&a.counter, 0), 3); + assert!(!s.compute_uma_private_ready(1), "A's commands are in flight in slot 1"); + assert!(s.compute_uma_private_ready(6)); + assert_eq!(s.bind_compute_uma(&c).unwrap(), None, "the SCS unit holds slot 6"); + // Flight 2 retires first (another pipe): A is not drained, its counter stays. + assert!(!retire(&mut s, &a, &f2, 1)); + assert_eq!((a.outstanding(), rd64(&a.counter, 0)), (1, 3)); + assert!(!s.compute_uma_private_ready(1)); + // Flight 1 retires: A drains, the SCS unit leaves slot 6. + assert!(retire(&mut s, &a, &f1, 1)); + s.retire_private_uma(&f1); + assert_eq!((a.outstanding(), rd64(&a.counter, 0)), (0, 2)); + assert!(s.compute_uma_private_ready(1)); + let fc = publish(&mut s, &c, 1).unwrap(); + assert_rebuilt(&c, fc.uma_rec as usize, 1); + } + + #[test] + fn closed_vms_release_admission_after_retirement() { + use g16::hw::sizes::COMPUTE_UNITS; + use g16::resources::ComputeArena; + const MAX_VMS_PER_FILE: u32 = __MAX_VMS_PER_FILE__; + let mut s = Slots::new().unwrap(); + let file = std::sync::Arc::new(AtomicU32::new(0)); + let mut last_rec = None; + for i in 0..(MAX_VMS_PER_FILE as u64 + 4) { + assert!(file.load(Ordering::Acquire) < MAX_VMS_PER_FILE, "ENOSPC on create {}", i + 1); + let v = vm(3100 + i); + let (bind, live, released) = g16::vm::test_live_token_in(&file); + let u = SharedComputeUma::new(&g16::object::Factory, &bind, &v.vm, &live, 0, 0).unwrap(); + let mut o = Objects::new(); + let mut units = KVec::new(); + for k in 0..COMPUTE_UNITS { + units.push(g16::slots::ComputeSlot::new_shared_in(&mut o, k as u64, &g16::object::test_unit_cmds(k as u64)).unwrap(), 0).unwrap(); + } + let prep = ComputeArena { compute: units, render: None, hw_slots: None, shared_uma: Some(u.clone()) }; + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + s.hold_compute_slot(k, &v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + // Each VM is a new manager in the same slot: it never takes over the record + // the previous VM's binding holds. + let cu = publish(&mut s, &u, 1).unwrap(); + if let Some(r) = last_rec { assert_ne!(cu.uma_rec, r); } + last_rec = Some(cu.uma_rec); + c.uma_rec = cu.uma_rec; + c.uma_slot = cu.uma_slot; + assert!(retire(&mut s, &u, &c, 1)); + s.retire(&mut c).unwrap(); + // Close: the residency ledger keeps no VM storage alive. + drop(prep); + assert_eq!(sync::Arc::strong_count(&u), 1, "nothing outside the VM holds its manager"); + drop(u); + drop(o); + drop(bind); + v.vm.close(); + drop(v); + drop(live); + assert!(released.load(Ordering::Acquire), "VM {} released its address space", i + 1); + assert_eq!(file.load(Ordering::Acquire), 0, "VM {} released its admission", i + 1); + } + } + } } ''' poll_source = (production/'poll.rs').read_text() @@ -3791,12 +4141,16 @@ def module(text, name): assert alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range(') < alloc_private_in_fn.index('self.mappings.push_within_capacity(firmware)'), 'alloc_private_in must commit mappings infallibly after firmware map' shared_uma_code = ( 'pub(crate) struct SharedComputeUma(crate::cleanup::Deferred);\n' + + next(line for line in resources_source.splitlines() if line.startswith('static NEXT_SHARED_UMA_ID:')) + + '\n' + item(resources_source, 'impl core::ops::Deref for SharedComputeUma {') + '\n' + item(resources_source, 'pub(crate) struct SharedComputeUmaInner {') + '\n' + item(resources_source, 'impl SharedComputeUma {') .replace('fn new(', 'pub(crate) fn new(') + + '\n' + + item(resources_source, 'impl SharedComputeUmaInner {') ) occ_code = ( 'pub(crate) ' + item(resources_source, 'struct ComputeUmaOccupancy {') @@ -3812,7 +4166,11 @@ def module(text, name): .replace('__FINISH_PRIVATE__', item(object_source, 'pub(crate) fn finish_private(')) .replace('__PERSISTENT_UNIT_CMDS__', item(resources_source, 'struct PersistentUnitCmds {')) .replace('__COMPUTE_CMDS_STRUCT__', item(resources_source, 'pub(crate) struct ComputeCmds {').replace('#[pin]\n', '').replace('super::hw::', 'hw::')) - .replace('__COMPUTE_CMDS_GET__', item(resources_source, 'pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result {'))) + .replace('__COMPUTE_CMDS_GET__', item(resources_source, 'pub(crate) fn get(&self, factory: &Factory, k: usize) -> Result {')) + .replace('__PERSISTENT_UMA_RECORDS__', item(resources_source, 'struct PersistentUmaRecords {').replace('super::slots::', 'crate::g16::slots::')) + .replace('__COMPUTE_UMA_RECORDS_GET__', item(resources_source, 'pub(crate) fn uma_records(') + .replace('super::slots::', 'crate::g16::slots::').replace('super::graph::', 'crate::g16::graph::') + .replace('super::fw::', 'crate::g16::fw::').replace('super::object::', 'crate::g16::object::'))) ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 render_burst_lines = ( @@ -3852,6 +4210,9 @@ def module(text, name): source = source.replace('__GRAPH_TYPES__', graph_types) source = source.replace('__ALLOC__',item(graph_source,'pub(crate) fn alloc(')).replace('__ALLOC_WORK__',item(graph_source,'pub(crate) fn alloc_work(')) source = source.replace('__HW__','\n'.join([module(hw,n) for n in ('client','sizes','engine','tuning','pte')] + [l for l in hw.splitlines() if l.startswith('pub(crate) const PAGE: u64')])).replace('__ROOT__',str(production)).replace('__PRIVATE_RW__',hex(private_rw)+'u64').replace('__CLIENT__', '#[derive(Copy,Clone)]\n'+item(graph_source, 'pub(crate) struct Client {')+'\n'+item(graph_source, 'impl Client {')) +vm_rs = (production/'vm.rs').read_text() +max_vms_per_file = next(line for line in vm_rs.splitlines() if line.startswith('const MAX_VMS_PER_FILE: u32 = ')).split('=')[1].strip().rstrip(';') +source = source.replace('__MAX_VMS_PER_FILE__', max_vms_per_file) (out/'check-resources.rs').write_text(source) log = '' for command in [ diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py index 9e57a7d79f349..e9e517c06db3b 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stamp-wrap.py @@ -23,7 +23,6 @@ def function(text, name): #![allow(dead_code)] use std::cell::Cell; use std::collections::BTreeMap; -use std::sync::atomic::{AtomicU64, Ordering}; struct Arc; impl Arc { fn ptr_eq(a:&Vm,b:&Vm)->bool{a.slot==b.slot} } #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); @@ -44,12 +43,11 @@ def function(text, name): mod notifier_page {pub const TA_STAMP:usize=8;pub const FS_STAMP:usize=12;pub const FS_RECORD:usize=32;} mod notifier {pub const CONTEXT:usize=16;} pub mod manager {pub const COUNTER:usize=0x4c;pub const COMPLETED:usize=0x54;} -mod fw { pub mod graph { pub use crate::manager; } } #[derive(Default)]struct CGraph{fw_stamp:Object,qstate:Object,qinfo:Object,notifier:Object,user_stamp:Object} struct RGraph{fw_stamp:[Object;2],qstate:[Object;2],qinfo:[Object;2],notifier:Object} struct Graph{compute:[CGraph;hw::sizes::COMPUTE_PIPES],render:RGraph} struct Vm{slot:u32}struct Job{vm:Vm,resources:Resources} -struct SharedComputeUma{retired:AtomicU64,counter:Object,descriptor:Object} +struct SharedComputeUma{counter:Object,descriptor:Object} struct Resources{compute:Vec,passes:Vec,pools:Pools,compute_uma:Option} impl Resources{ fn compute(&self)->Result<&Self>{Ok(self)} @@ -59,7 +57,6 @@ def function(text, name): fn pb_retired(&self,k:usize)->Result{self.pools.retired(k)} fn pb_retired_at(&self,k:usize,target:u64)->Result{self.pools.retired_at(k,target)} fn has_shared_compute_uma(&self)->bool{self.compute_uma.is_some()} - __COMPUTE_UMA_RETIRED__ } struct Claims{slot:[u32;16],slot_count:u32,pass:[u32;4]} struct Flight{computes:u32,renders:u32,compute_pipe:u8,target:u32,ta_target:u32,fs_target:u32,job:Job,claims:Claims,head:u32,ta_head:u32,fs_head:u32,rec:[u32;3],chan_settled:bool,pb_slot:u32,uma_submitted:u64,csubmitted:[u64;16],recovery_suspect:bool,recovery_started_ns:u64,gate_passed_ns:Option,unsettled_polls:u32,doomed:bool} @@ -683,52 +680,60 @@ def function(text, name): } } -#[test]fn shared_compute_uma_retires_out_of_order_and_checks_idle_conservation(){ - // Exercise production `Prepared::compute_uma_retired()` extracted from resources.rs. - let mk_uma=|retired:u64,ctr:u64,comp:u64|{ +#[test]fn shared_compute_uma_receipts_never_read_the_cached_manager(){ + // The VM-shared manager is an ASC-cached slot record: its COMPLETED word and counter + // pointer are not host-readable, so production receipts rely on the service stamp, the + // queue/channel receipt and the GPU ticks alone. + let mk_uma=|ctr:u64,comp:u64|{ let mut counter=Object::default(); counter.set(0,ctr); let mut descriptor=Object::default(); descriptor.set(manager::COMPLETED,comp); descriptor.set(manager::COUNTER,counter.va); - SharedComputeUma{retired:AtomicU64::new(retired),counter,descriptor} + SharedComputeUma{counter,descriptor} }; - // Two flights of the same VM share one UMA descriptor across pipe 0 and pipe 1: - // counter == 2, COMPLETED == 1. Flight 1 (pipe 1) retires immediately while flight 0 - // is still active (`last_vm_flight == false`). + // Two flights of one manager across pipes 0 and 1 (counter 3 under the hold, COMPLETED + // lagging at 1 as a cached record can): the pipe-1 flight retires Full while pipe 0 runs. let mut f=firmware(false,1); - f.engine.flights[0].job.resources.compute_uma=Some(mk_uma(0,2,1)); + f.engine.flights[0].job.resources.compute_uma=Some(mk_uma(3,1)); let mut second=firmware(false,2).engine.flights.pop().unwrap(); second.compute_pipe=1; - second.job.resources.compute_uma=Some(mk_uma(0,2,1)); + second.job.resources.compute_uma=Some(mk_uma(3,1)); f.graph.compute[1].fw_stamp.set(0,u64::from(second.target)); f.graph.compute[1].user_stamp.set(0,u64::from(second.target)); f.engine.target[1]=second.target; f.engine.flights.push(second); assert_eq!(f.retired_at(1),Ok(Retirement::Full)); - // With only flight 0 left (`last_vm_flight == true`), even when `needed == 1 <= COMPLETED` - // (retired == 0, count == 1, counter == 2, COMPLETED == 1), idle conservation MUST reject - // `COMPLETED != counter` so an unretired earlier command cannot be missed. + let reads=|f:&Firmware,i:usize|{let u=f.engine.flights[i].job.resources.compute_uma.as_ref().unwrap();u.counter.reads.get()+u.descriptor.reads.get()}; + assert_eq!(reads(&f,1),0,"no CPU read of the cached manager or its counter"); + // The manager's last flight: Full with COMPLETED lagging and with a changed COUNTER pointer. f.engine.flights.pop(); - assert_eq!(f.retired_at(0),Ok(Retirement::Pending)); - // Advancing `retired == 1` (`needed == 2 > COMPLETED == 1`) also stays Pending. - f.engine.flights[0].job.resources.compute_uma.as_ref().unwrap().retired.store(1,Ordering::Release); - assert_eq!(f.retired_at(0),Ok(Retirement::Pending)); - // Matching `COMPLETED == counter == 2` retires Full. - f.engine.flights[0].job.resources.compute_uma.as_mut().unwrap().descriptor.set(manager::COMPLETED,2); assert_eq!(f.retired_at(0),Ok(Retirement::Full)); - // Mismatched descriptor COUNTER pointer stays Pending. f.engine.flights[0].job.resources.compute_uma.as_mut().unwrap().descriptor.set(manager::COUNTER,0x9999); + assert_eq!(f.retired_at(0),Ok(Retirement::Full)); + assert_eq!(reads(&f,0),0,"no CPU read of the cached manager or its counter"); + // Missing service stamp, queue/channel receipt or valid ticks keep it Pending. + let target=f.engine.flights[0].target; + f.graph.compute[0].user_stamp.set(0,u64::from(target.wrapping_sub(0x100))); assert_eq!(f.retired_at(0),Ok(Retirement::Pending)); + f.graph.compute[0].user_stamp.set(0,u64::from(target)); + f.queue_passed=false; + assert_eq!(f.retired_at(0),Ok(Retirement::Pending)); + f.queue_passed=true; + f.engine.flights[0].job.resources.compute[0].its.set(0,0); + assert_eq!(f.retired_at(0),Ok(Retirement::Pending)); + f.engine.flights[0].job.resources.compute[0].its.set(0,102); + assert_eq!(f.retired_at(0),Ok(Retirement::Pending),"end before start"); + f.engine.flights[0].job.resources.compute[0].its.set(0,100); + assert_eq!(f.retired_at(0),Ok(Retirement::Full)); + assert_eq!(reads(&f,0),0); } '''.replace('__LOGIC__', str(backend/'recovery/logic.rs')) -for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RING_RECEIPT__','poll.rs','queue_ring_receipt'),('__QUEUE_RING_PASSED__','poll.rs','queue_ring_passed'),('__CHANNEL_RECEIPT__','poll.rs','channel_receipt'),('__LATCH_COMPUTE_CHANNEL_RECEIPTS__','poll.rs','latch_compute_channel_receipts'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached'),('__COMPUTE_UMA_RETIRED__','resources.rs','compute_uma_retired')]: +for token, path, name in [('__STAMP_SEED__','encode.rs','stamp_seed'),('__STAMP__','encode.rs','stamp'),('__RETIRED__','poll.rs','retired'),('__RETIRED_AT__','poll.rs','retired_at'),('__RETIRED_FLIGHT__','poll.rs','retired_flight'),('__RETIRED_FLIGHT_CLASSES__','poll.rs','retired_flight_classes'),('__RETIRED_SNAPSHOT__','poll.rs','retired_snapshot'),('__RETIRED_SNAPSHOT_AT__','poll.rs','retired_snapshot_at'),('__QUEUE_RING_RECEIPT__','poll.rs','queue_ring_receipt'),('__QUEUE_RING_PASSED__','poll.rs','queue_ring_passed'),('__CHANNEL_RECEIPT__','poll.rs','channel_receipt'),('__LATCH_COMPUTE_CHANNEL_RECEIPTS__','poll.rs','latch_compute_channel_receipts'),('__QUEUE_RECEIPT__','poll.rs','queue_receipt'),('__QUEUE_PASSED__','poll.rs','queue_passed'),('__GRAPH_FW__','graph.rs','graph_fw'),('__QINFO_CACHED__','graph.rs','qinfo_cached')]: body = function((backend/path).read_text(),name) if token in ('__RETIRED_FLIGHT__', '__RETIRED_FLIGHT_CLASSES__', '__RETIRED_SNAPSHOT_AT__'): body = body.replace('super::hw::', 'hw::') - if token == '__COMPUTE_UMA_RETIRED__': - body = body.replace('super::fw::', 'fw::') harness=harness.replace(token, body) hw_text=(backend/'hw.rs').read_text() def mod_block(text, name): From bb0df446c55ce6946690aa08371539835ffe83dd Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 08:32:12 -0500 Subject: [PATCH 2/7] drm/asahi: g16: verify the GPU powered flag while idle On J516s (T6030) the compute UMA idle check invalidated the held managers at nearly every publication from an empty engine. The G15S handoff byte at +0x638 does not read nonzero there while the GPU is powered, so each such job rebuilt its manager record and reseeded its 64 KiB freelist. compute.light procs d2 went from 43.6 to 56.6 us. The driver stats show the cost: about 5 us more prefix time per publication, and 14 us more for each publication after the engine drained. On J773g the byte reads 1 while the GPU is powered, so J773g was not affected. Trust the flag only after it has read nonzero at a publication pass with nothing in flight. The GPU is then idle and powered, and only a flag that tracks GPU power shows that. A flag that stays zero, or one set only while work runs, never earns trust and invalidates nothing, as on firmware without the flag. Bindings on such firmware rely on the GPU staying powered while the firmware runs, which holds on J516s and J773g today, and on the invalidation at system sleep and recovery. A change that makes such firmware power the GPU down must first make the flag earn trust. Report the residency in aurora-g16/stats as "compute_uma: rebuilds N invalidations M powered_flag 0|1". Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/boot.rs | 20 ++-- drivers/gpu/drm/asahi/g16/engine.rs | 34 ++++--- drivers/gpu/drm/asahi/g16/poll.rs | 7 ++ drivers/gpu/drm/asahi/g16/slots.rs | 6 ++ .../drivers/gpu/asahi-m4/test-publication.py | 92 ++++++++++++++----- .../drivers/gpu/asahi-m4/test-resources.py | 4 + 6 files changed, 118 insertions(+), 45 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index 7a9b7d39d130a..c80b685018dde 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -536,20 +536,16 @@ impl Session { read(&self.regs).map(Some) } - /// Whether the GPU may be powered down now: the firmware powers it down while idle and its - /// powered flag, read without the PPL handoff lock as a hint that can change right after, - /// does not show it powered. A firmware that records no flag keeps the GPU powered while it - /// runs. - pub(crate) fn may_be_powered_down(&self) -> bool { - let Some(offset) = self.adt.layout.powered else { - return false; - }; - self.handoff.as_ref().is_none_or(|page| { - !page - .io() + /// The firmware's powered flag, read without the PPL handoff lock as a hint that can change + /// right after: whether it reads nonzero (a failed read counts as zero), or `None` for a + /// firmware that records no flag because it keeps the GPU powered while it runs. + pub(crate) fn powered_flag(&self) -> Option { + let offset = self.adt.layout.powered?; + Some(self.handoff.as_ref().is_some_and(|page| { + page.io() .try_read8(offset) .is_ok_and(|powered| powered != 0) - }) + })) } /// The engine receipts of a running firmware, or `None` while the GPU is powered down. diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 067411a13ca19..c72368ebf3e3b 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -699,6 +699,9 @@ pub(crate) struct Engine { /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing /// (0 when no batch is held). pub(crate) coalesce_deadline_ns: u64, + /// The firmware's powered flag read nonzero with nothing in flight on this boot, so it + /// tracks GPU power (`note_gpu_idle_if_any`). + pub(crate) powered_flag_proven: bool, /// Progress tracking of the oldest compute pipes `0..COMPUTE_PIPES` and render flights. pub(crate) progress_flight: [u64; sizes::COMPUTE_PIPES + 1], pub(crate) progress: [Option; sizes::COMPUTE_PIPES + 2], @@ -749,6 +752,7 @@ impl Engine { housekeeping_owed: false, held_wait: false, coalesce_deadline_ns: 0, + powered_flag_proven: false, progress_flight: [0; sizes::COMPUTE_PIPES + 1], progress: [None; sizes::COMPUTE_PIPES + 2], stats: KBox::zeroed(GFP_KERNEL)?, @@ -2125,18 +2129,26 @@ impl Firmware { /// Once per publication pass, before anything is posted. A firmware that powers the GPU /// down while idle drops the hardware allocator state of compute UMA managers left bound - /// under the hold; with the powered flag not showing the GPU powered, trust none of them. - /// The GPU powers up only for work this host publishes, so a powered GPU has not cycled - /// power since its last work. It powers down only after its idle delay, and every pass - /// first retires the flights whose receipts are visible, so with a flight still in flight - /// it has not powered down either. That keeps the flag read off passes with work in flight - /// and off every pass while no shared manager is held (render-only work). + /// under the hold; with the powered flag showing the GPU down, trust none of them. The GPU + /// powers up only for work this host publishes, so a powered GPU has not cycled power since + /// its last work. It powers down only after its idle delay, and every pass first retires + /// the flights whose receipts are visible, so with a flight still in flight it has not + /// powered down either. That keeps the flag read off passes with work in flight and off + /// every pass while no shared manager is held (render-only work). + /// + /// The flag is trusted only once it has read nonzero here, with nothing in flight: the GPU + /// is then idle and powered, which only a flag that tracks GPU power shows. Until then (a + /// flag that stays zero, or one set only while work runs) it invalidates nothing, as for a + /// firmware without the flag: such bindings rely on the GPU staying powered while the + /// firmware runs, and on the invalidation at system sleep and recovery. fn note_gpu_idle_if_any(&mut self) { - if self.engine.flights.is_empty() - && self.slots.compute_uma_held() - && self.session.may_be_powered_down() - { - self.slots.invalidate_compute_uma(); + if !self.engine.flights.is_empty() || !self.slots.compute_uma_held() { + return; + } + match self.session.powered_flag() { + Some(true) => self.engine.powered_flag_proven = true, + Some(false) if self.engine.powered_flag_proven => self.slots.invalidate_compute_uma(), + _ => {} } } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e9e39f4d02ae4..24f03f03b207a 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -2249,6 +2249,13 @@ impl Firmware { "resources: compute_cross_vm {} render_cross_vm {}", slots.cross_vm_retargets[0], slots.cross_vm_retargets[1] )?; + writeln!( + f, + "compute_uma: rebuilds {} invalidations {} powered_flag {}", + slots.uma_rebuilds, + slots.uma_invalidations, + u8::from(self.engine.powered_flag_proven) + )?; writeln!( f, "recovery_receipts: affected_full {} aborted {}", diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index d9d4ccf520e9a..b8df48db002c3 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -818,6 +818,10 @@ pub(crate) struct SlotStats { pub(crate) tpc_clear_bytes: u64, pub(crate) tilemap_clear_bytes: u64, pub(crate) pass_scrubs: u64, + /// Shared compute UMA manager records rebuilt (freelist reseeded) and residency + /// invalidations ([`Slots::bind_compute_uma`], [`Slots::invalidate_compute_uma`]). + pub(crate) uma_rebuilds: u64, + pub(crate) uma_invalidations: u64, } /// Displacement ledger and VM leases of the compute units (see [`Slots`]). @@ -2034,6 +2038,7 @@ impl Slots { .find(|&r| c.uma_bound[slot] != UmaBound::Record(r as u8)) .ok_or(EINVAL)?; shared.init_record(rec)?; + self.stats.uma_rebuilds = self.stats.uma_rebuilds.saturating_add(1); Ok(Some(rec)) } @@ -2129,6 +2134,7 @@ impl Slots { let c = &mut self.compute; c.uma_live_gen = c.uma_live_gen.wrapping_add(1); c.uma_held = false; + self.stats.uma_invalidations = self.stats.uma_invalidations.saturating_add(1); } /// Whether a shared manager may be bound with its cursors only in the hardware: one was 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 85dab5d7774d3..689b59b0c9f75 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -161,7 +161,7 @@ def item(declaration): __SCS_COMPUTE_CONFLICT__ __COMPUTE_UMA_CONFLICT__ __MSAA_RENDER_CONFLICT__ -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,held_wait:bool,handoff_avoid_pipes:u32,coalesce_deadline_ns:u64} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,held_wait:bool,handoff_avoid_pipes:u32,coalesce_deadline_ns:u64,powered_flag_proven:bool} impl Engine { __PICK__ __UNPEND__ @@ -181,9 +181,9 @@ def item(declaration): struct Recovery{error:Option,publication_wait_deadline:Option}impl Recovery{fn failed(&self)->Option{self.error}} // Compute UMA idle check (engine.rs `note_gpu_idle_if_any`): whether a shared manager is held // (slots.rs residency, which test-resources.py covers), the powered-flag reads and invalidations. -#[derive(Copy,Clone)]struct UmaIdle{held:bool,down:bool,reads:u32,invalidations:u32} -thread_local!{static UMA_IDLE:std::cell::Cell=const{std::cell::Cell::new(UmaIdle{held:false,down:false,reads:0,invalidations:0})};} -impl Session{fn may_be_powered_down(&self)->bool{UMA_IDLE.with(|u|{let mut s=u.get();s.reads+=1;u.set(s);s.down})}} +#[derive(Copy,Clone)]struct UmaIdle{held:bool,flag:Option,reads:u32,invalidations:u32} +thread_local!{static UMA_IDLE:std::cell::Cell=const{std::cell::Cell::new(UmaIdle{held:false,flag:None,reads:0,invalidations:0})};} +impl Session{fn powered_flag(&self)->Option{UMA_IDLE.with(|u|{let mut s=u.get();s.reads+=1;u.set(s);s.flag})}} struct Slots{compute_exhausted:bool,render_exhausted:bool,releases:u32,quarantines:u32} impl Slots{ fn compute_uma_held(&self)->bool{UMA_IDLE.with(|u|u.get().held)} @@ -328,7 +328,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, - engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,held_wait:false,handoff_avoid_pipes:0,coalesce_deadline_ns:0}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,held_wait:false,handoff_avoid_pipes:0,coalesce_deadline_ns:0,powered_flag_proven:false}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false, @@ -1290,12 +1290,20 @@ def item(declaration): assert_eq!(r2r, WaitTarget { stamp: 0x900, initbm: true }); assert_eq!(cross_engine_barrier_type(r2r.initbm, false), BarrierType::Hold); } + fn uma_set(held:bool,flag:Option){UMA_IDLE.with(|u|u.set(UmaIdle{held,flag,reads:0,invalidations:0}));} + fn uma_flag(flag:Option){UMA_IDLE.with(|u|{let mut s=u.get();s.flag=flag;u.set(s);});} + fn uma_seen()->(u32,u32){UMA_IDLE.with(|u|{let s=u.get();(s.reads,s.invalidations)})} + // One publication pass that publishes `job` from an idle engine, then its retirement. + fn idle_pass(fw:&mut Firmware,id:u32,done:&mut Completions){ + fw.engine.pending.push(job(id,false,0,Ok(()))); + fw.stages.push_back(Stage{result:Ok(()),visible:true}); + fw.publish_checked(done).unwrap(); + fw.engine.flights.clear(); + } #[test]fn uma_idle_check_reads_the_powered_flag_only_for_a_held_manager_on_an_idle_engine(){ - let set=|held,down|UMA_IDLE.with(|u|u.set(UmaIdle{held,down,reads:0,invalidations:0})); - let seen=||UMA_IDLE.with(|u|{let s=u.get();(s.reads,s.invalidations)}); let mut done=vec![]; // No shared manager held (render-only work): no flag read on any pass. - set(false,true); + uma_set(false,Some(false)); let mut fw=firmware(vec![job(1,true,0,Ok(()))],vec![(Ok(()),true)]); fw.publish_checked(&mut done).unwrap(); assert_eq!(fw.engine.flights.len(),1); @@ -1303,27 +1311,67 @@ def item(declaration): fw.engine.pending.push(job(2,true,0,Ok(()))); fw.stages.push_back(Stage{result:Ok(()),visible:true}); fw.publish_checked(&mut done).unwrap(); - assert_eq!(seen(),(0,0)); + assert_eq!(uma_seen(),(0,0)); // A held manager and a flight in flight: the GPU has not powered down, no read. - set(true,true); + uma_set(true,Some(false)); fw.engine.pending.push(job(3,false,0,Ok(()))); fw.stages.push_back(Stage{result:Ok(()),visible:true}); fw.publish_checked(&mut done).unwrap(); - assert_eq!(seen(),(0,0)); - // A held manager on an idle engine: one read; powered down invalidates, powered keeps. - set(true,true); - let mut fw=firmware(vec![job(4,false,0,Ok(()))],vec![(Ok(()),true)]); - fw.publish_checked(&mut done).unwrap(); - assert_eq!(seen(),(1,1)); - set(true,false); - let mut fw=firmware(vec![job(5,false,0,Ok(()))],vec![(Ok(()),true)]); - fw.publish_checked(&mut done).unwrap(); - assert_eq!(seen(),(1,0)); + assert_eq!(uma_seen(),(0,0)); // Nothing pending: no pass work at all. - set(true,true); let mut fw=firmware(vec![],vec![]); fw.publish_checked(&mut done).unwrap(); - assert_eq!(seen(),(0,0)); + assert_eq!(uma_seen(),(0,0)); + } + #[test]fn uma_powered_flag_never_nonzero_at_idle_never_invalidates(){ + let mut done=vec![]; + // A flag that stays zero: read on every idle pass, never trusted, nothing invalidated. + uma_set(true,Some(false)); + let mut fw=firmware(vec![],vec![]); + for id in 1..=4{idle_pass(&mut fw,id,&mut done);} + assert_eq!(uma_seen(),(4,0)); + assert!(!fw.engine.powered_flag_proven); + // A flag set only while work runs: passes with work in flight never read it, and at idle + // it reads zero, so it is never trusted either. + fw.allow_behind=true; + fw.engine.pending.push(job(5,false,0,Ok(()))); + fw.stages.push_back(Stage{result:Ok(()),visible:true}); + fw.publish_checked(&mut done).unwrap(); + uma_flag(Some(true)); + fw.engine.pending.push(job(6,false,0,Ok(()))); + fw.stages.push_back(Stage{result:Ok(()),visible:true}); + fw.publish_checked(&mut done).unwrap(); + fw.engine.flights.clear(); + uma_flag(Some(false)); + idle_pass(&mut fw,7,&mut done); + assert_eq!(uma_seen(),(6,0)); + assert!(!fw.engine.powered_flag_proven); + // A firmware without the flag keeps the GPU powered: never trusted, nothing invalidated. + uma_set(true,None); + let mut fw=firmware(vec![],vec![]); + idle_pass(&mut fw,8,&mut done); + assert_eq!(uma_seen(),(1,0)); + assert!(!fw.engine.powered_flag_proven); + } + #[test]fn uma_powered_flag_seen_nonzero_at_idle_invalidates_after_power_down(){ + let mut done=vec![]; + // Idle and powered: the flag reads nonzero, so it tracks GPU power from now on. + uma_set(true,Some(true)); + let mut fw=firmware(vec![],vec![]); + idle_pass(&mut fw,1,&mut done); + assert_eq!(uma_seen(),(1,0)); + assert!(fw.engine.powered_flag_proven); + // Powered down at the next idle pass: every held binding is invalidated. + uma_flag(Some(false)); + idle_pass(&mut fw,2,&mut done); + assert_eq!(uma_seen(),(2,1)); + // Invalidation drops the held state: no read until a shared manager is bound again. + idle_pass(&mut fw,3,&mut done); + assert_eq!(uma_seen(),(2,1)); + UMA_IDLE.with(|u|{let mut s=u.get();s.held=true;u.set(s);}); + idle_pass(&mut fw,4,&mut done); + assert_eq!(uma_seen(),(3,2)); + assert!(fw.engine.powered_flag_proven,"trust stays for the boot"); } #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); 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 ac101f9b9472e..de66c2c277195 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -3937,10 +3937,12 @@ def module(text, name): assert!(retire(&mut s, &a, &ca, 1)); assert!(retire(&mut s, &b, &cb, 1)); assert!(s.compute_uma_held(), "drained managers stay bound"); + assert_eq!((s.stats.uma_rebuilds, s.stats.uma_invalidations), (2, 0), "first records"); // An idle power-down, a sleep or a recovery: no binding is trusted. Each rebuilds // in the record the slot table does not name. s.invalidate_compute_uma(); assert!(!s.compute_uma_held()); + assert_eq!(s.stats.uma_invalidations, 1); run_on_gpu(&a); run_on_gpu(&b); let (wa, wb) = (uma_writes(&a), uma_writes(&b)); @@ -3960,12 +3962,14 @@ def module(text, name): let ca3 = publish(&mut s, &a, 1).unwrap(); assert_ne!(ca3.uma_rec, ca2.uma_rec); assert_rebuilt(&a, ca3.uma_rec as usize, 1); + assert_eq!((s.stats.uma_rebuilds, s.stats.uma_invalidations), (5, 2)); // The same generation again: back on the fast path. assert!(retire(&mut s, &a, &ca3, 1)); let w = uma_writes(&a); let ca4 = publish(&mut s, &a, 1).unwrap(); assert_eq!(ca4.uma_rec, ca3.uma_rec); assert_eq!(uma_writes(&a), w); + assert_eq!(s.stats.uma_rebuilds, 5, "the fast path rebuilds nothing"); } #[test] From 11b31056fea4f9d16f4bfeab331430d2c9987e2d Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 08:37:48 -0500 Subject: [PATCH 3/7] drm/asahi: g16: fail folded compute jobs on UMA counter write error The error path after the compute UMA counter write-back completed only the flight's own job with the error. Compute jobs folded into the flight's group were left with fences that never signal. Complete them with the error like the other fail-stop paths in retire_oldest. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/poll.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 24f03f03b207a..50b089dfd9dc2 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1579,6 +1579,10 @@ impl Firmware { if let Some(Err(error)) = released { self.retain(&f.job); complete(done, &f.job, Err(error)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, Err(error)); + } self.fail_stop(error, done); core::mem::forget(f); return; From e85c6d2ee6a01cea0693061fb59d43ec19a48403 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 08:54:49 -0500 Subject: [PATCH 4/7] drm/asahi: g16: invalidate held compute UMA managers when the GPU may power off Compute UMA managers stay bound across short idle gaps under the in-flight hold, so their allocator cursors live only in the hardware, and a GPU power-off drops them. The previous check trusted the firmware's powered byte once it had read nonzero at idle. That byte is not a validated witness of continuous power: it reads zero on G15S, so nothing was ever invalidated there, and a byte seen high once does not prove that the GPU stayed powered. Decide from the power policy that boot actually sends instead. The session records it with the final boot control. START with a zero argument asks the firmware to wake the GPU and hold it powered, and the firmware then never powers the GPU off on its own while idle (measured on main: 0 of 16 checks off at 250 ms on J773g and J516s). Under that hold a bound manager cannot be lost while idle, so nothing is invalidated and the managers keep their fast reuse. System sleep and recovery still invalidate, as before. When a policy lets the firmware power the GPU off on its own, there is no qualified power-loss witness yet (a firmware power-loss generation, or a power hold that spans this check through the firmware's consumption of the next kick). So every publication pass that finds nothing in flight after retiring what it can, with a shared manager held, invalidates the held managers. Their next commands rebuild into the slot record that the firmware's slot table does not name. A pass with work in flight invalidates nothing, because a flight in flight keeps the GPU busy. A later change can replace this with a qualified witness. The change that releases the power hold must set the flag where it sends that policy. The flag is set next to the START control, so such a change conflicts with this one visibly instead of silently. Drop the powered-byte heuristic and its stat. The stats line becomes "compute_uma: rebuilds N invalidations M idle_invalidations K". Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/boot.rs | 23 +-- drivers/gpu/drm/asahi/g16/engine.rs | 45 +++-- drivers/gpu/drm/asahi/g16/poll.rs | 6 +- .../drivers/gpu/asahi-m4/test-publication.py | 157 ++++++++++-------- 4 files changed, 121 insertions(+), 110 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index c80b685018dde..02f9eafdc9bf5 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -487,6 +487,9 @@ pub(crate) struct Session { handoff: Option, /// True once cold boot (`START`) has completed and the firmware may idle-power-off the GPU. booted: bool, + /// The boot power policy sent in [`run`] lets the firmware power the GPU off on its own + /// while idle; false while it holds the GPU powered. + idle_power_off: bool, } impl Session { @@ -536,16 +539,11 @@ impl Session { read(&self.regs).map(Some) } - /// The firmware's powered flag, read without the PPL handoff lock as a hint that can change - /// right after: whether it reads nonzero (a failed read counts as zero), or `None` for a - /// firmware that records no flag because it keeps the GPU powered while it runs. - pub(crate) fn powered_flag(&self) -> Option { - let offset = self.adt.layout.powered?; - Some(self.handoff.as_ref().is_some_and(|page| { - page.io() - .try_read8(offset) - .is_ok_and(|powered| powered != 0) - })) + /// Whether the boot power policy lets the firmware power the GPU off on its own while + /// idle. False while the firmware holds the GPU powered, so it cannot cycle power between + /// commands. + pub(crate) fn idle_power_off(&self) -> bool { + self.idle_power_off } /// The engine receipts of a running firmware, or `None` while the GPU is powered down. @@ -916,6 +914,10 @@ fn run( scheduler.w32(scheduler_word, 1)?; } regs::wmb(); + // START with a zero argument asks the firmware to wake the GPU and hold it powered, so it + // never powers the GPU off on its own while idle. Held compute UMA managers rely on that + // (`Firmware::note_gpu_idle_if_any`): a policy that releases the hold must say so here. + session.idle_power_off = false; devctl_op(session, channels, events, init, devctl.start)?; wait_boot_control(session, channels, events, init, base + 2, 2000)?; let receive_kick = if g15s_channels { @@ -1107,6 +1109,7 @@ pub(crate) fn start( uat, handoff, booted: false, + idle_power_off: false, }; let mut events = Events::new(); let mut built = None; diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index c72368ebf3e3b..940a2efc9bf14 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -551,6 +551,9 @@ pub(crate) struct Stats { pub(crate) behind: u64, /// Most flights in flight at once. pub(crate) max_flights: u64, + /// Publication passes that found the GPU quiescent with a compute UMA manager held while + /// the firmware may power the GPU off, and invalidated the held managers. + pub(crate) uma_idle_invalidations: u64, } /// Host-side phase timers of publication and polling, on with `debug_flags` bit 49 @@ -699,9 +702,6 @@ pub(crate) struct Engine { /// Absolute deadline (`ktime_get_ns`) for busy-state same-queue horizon micro-coalescing /// (0 when no batch is held). pub(crate) coalesce_deadline_ns: u64, - /// The firmware's powered flag read nonzero with nothing in flight on this boot, so it - /// tracks GPU power (`note_gpu_idle_if_any`). - pub(crate) powered_flag_proven: bool, /// Progress tracking of the oldest compute pipes `0..COMPUTE_PIPES` and render flights. pub(crate) progress_flight: [u64; sizes::COMPUTE_PIPES + 1], pub(crate) progress: [Option; sizes::COMPUTE_PIPES + 2], @@ -752,7 +752,6 @@ impl Engine { housekeeping_owed: false, held_wait: false, coalesce_deadline_ns: 0, - powered_flag_proven: false, progress_flight: [0; sizes::COMPUTE_PIPES + 1], progress: [None; sizes::COMPUTE_PIPES + 2], stats: KBox::zeroed(GFP_KERNEL)?, @@ -2127,29 +2126,29 @@ impl Firmware { Ok(waits) } - /// Once per publication pass, before anything is posted. A firmware that powers the GPU - /// down while idle drops the hardware allocator state of compute UMA managers left bound - /// under the hold; with the powered flag showing the GPU down, trust none of them. The GPU - /// powers up only for work this host publishes, so a powered GPU has not cycled power since - /// its last work. It powers down only after its idle delay, and every pass first retires - /// the flights whose receipts are visible, so with a flight still in flight it has not - /// powered down either. That keeps the flag read off passes with work in flight and off - /// every pass while no shared manager is held (render-only work). + /// Once per publication pass, before anything is posted. A compute UMA manager left bound + /// under the in-flight hold keeps its allocator cursors only in the hardware + /// (`Slots::bind_compute_uma`), so a GPU power-off drops them. /// - /// The flag is trusted only once it has read nonzero here, with nothing in flight: the GPU - /// is then idle and powered, which only a flag that tracks GPU power shows. Until then (a - /// flag that stays zero, or one set only while work runs) it invalidates nothing, as for a - /// firmware without the flag: such bindings rely on the GPU staying powered while the - /// firmware runs, and on the invalidation at system sleep and recovery. + /// Under the boot policy that holds the GPU powered (`Session::idle_power_off` false), + /// the GPU cannot lose a bound manager while idle: nothing is invalidated here, and only a + /// system sleep or a recovery invalidates. When the firmware may power the GPU off on its + /// own, there is no qualified witness of a power loss yet (such as a firmware power-loss + /// generation, or a power hold spanning this check through the firmware's consumption of + /// the next kick). So every pass that finds nothing in flight, after retiring what it can, + /// with a shared manager held, invalidates them all, and their next commands rebuild their + /// records. A flight in flight keeps the GPU busy, so a pass with work in flight + /// invalidates nothing, nor does one while no shared manager is held (render-only work). fn note_gpu_idle_if_any(&mut self) { - if !self.engine.flights.is_empty() || !self.slots.compute_uma_held() { + if !self.session.idle_power_off() + || !self.engine.flights.is_empty() + || !self.slots.compute_uma_held() + { return; } - match self.session.powered_flag() { - Some(true) => self.engine.powered_flag_proven = true, - Some(false) if self.engine.powered_flag_proven => self.slots.invalidate_compute_uma(), - _ => {} - } + self.slots.invalidate_compute_uma(); + let s = &mut self.engine.stats; + s.uma_idle_invalidations = s.uma_idle_invalidations.saturating_add(1); } /// Whether `queue`'s recent or active compute work is heavy enough to benefit from 2-pipe diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 50b089dfd9dc2..8d8e070af6e69 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -2255,10 +2255,8 @@ impl Firmware { )?; writeln!( f, - "compute_uma: rebuilds {} invalidations {} powered_flag {}", - slots.uma_rebuilds, - slots.uma_invalidations, - u8::from(self.engine.powered_flag_proven) + "compute_uma: rebuilds {} invalidations {} idle_invalidations {}", + slots.uma_rebuilds, slots.uma_invalidations, s.uma_idle_invalidations )?; writeln!( f, 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 689b59b0c9f75..e96984e9c184c 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -98,6 +98,19 @@ def item(declaration): assert 'let pipe_fold_cap = if heavy_compute && c_waits == [None; sizes::COMPUTE_PIPES]' in publish_prefix_body_fn, 'pipe_fold_cap must only apply to heavy barrier-free compute' +# The boot code records the GPU power policy it sends with the final boot control (`run` in +# boot.rs), so held compute UMA managers are invalidated whenever that policy lets the firmware +# power the GPU off on its own (`note_gpu_idle_if_any`). +boot_run_fn = item_in((production.parent / 'boot.rs').read_text(), 'fn run(') +assert boot_run_fn.count('session.idle_power_off = ') == 1, boot_run_fn +assert ( + boot_run_fn.index('session.idle_power_off = ') + < boot_run_fn.index('wait_boot_control(session, channels, events, init, base + 2') +), 'the power policy flag must be set where the final boot control is sent' +note_gpu_idle_fn = item('fn note_gpu_idle_if_any(') +assert 'self.session.idle_power_off()' in note_gpu_idle_fn, note_gpu_idle_fn + + harness = r''' #![allow(dead_code, unused_variables)] #[path = "__USAGE__"] @@ -154,14 +167,14 @@ def item(declaration): #[derive(Copy, Clone, Debug, PartialEq, Eq)] __HOLD_CAUSE__ __HOLD_CAUSE_IMPL__ -#[derive(Default)]struct Stats{hold:[u64;3],hold_causes:[u64;HoldCause::COUNT],grouped:u64} +#[derive(Default)]struct Stats{hold:[u64;3],hold_causes:[u64;HoldCause::COUNT],grouped:u64,uma_idle_invalidations:u64} struct Claims; struct Flight{job:Arc,claims:Claims,group:Vec>,computes:u32,renders:u32,compute_pipe:u8,rt_compute:bool,compute_uma_mask:u32,doomed:bool,recovery_suspect:bool,initbm:bool} impl Flight{fn new(job:Arc)->Self{Self{job,claims:Claims,group:vec![],computes:0,renders:0,compute_pipe:0,rt_compute:false,compute_uma_mask:0,doomed:false,recovery_suspect:false,initbm:false}}} __SCS_COMPUTE_CONFLICT__ __COMPUTE_UMA_CONFLICT__ __MSAA_RENDER_CONFLICT__ -struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,held_wait:bool,handoff_avoid_pipes:u32,coalesce_deadline_ns:u64,powered_flag_proven:bool} +struct Engine{ordinal:u64,draw:u64,pending:Vec>,flights:Vec,frozen:bool,turn:u64,stats:Stats,chan_wait:bool,slot_wait:bool,held_wait:bool,handoff_avoid_pipes:u32,coalesce_deadline_ns:u64} impl Engine { __PICK__ __UNPEND__ @@ -179,11 +192,12 @@ def item(declaration): } } struct Recovery{error:Option,publication_wait_deadline:Option}impl Recovery{fn failed(&self)->Option{self.error}} -// Compute UMA idle check (engine.rs `note_gpu_idle_if_any`): whether a shared manager is held -// (slots.rs residency, which test-resources.py covers), the powered-flag reads and invalidations. -#[derive(Copy,Clone)]struct UmaIdle{held:bool,flag:Option,reads:u32,invalidations:u32} -thread_local!{static UMA_IDLE:std::cell::Cell=const{std::cell::Cell::new(UmaIdle{held:false,flag:None,reads:0,invalidations:0})};} -impl Session{fn powered_flag(&self)->Option{UMA_IDLE.with(|u|{let mut s=u.get();s.reads+=1;u.set(s);s.flag})}} +// Compute UMA idle check (engine.rs `note_gpu_idle_if_any`): the boot power policy, whether a +// shared manager is held (slots.rs residency, which test-resources.py covers), the invalidations +// and how many of them preceded the last hardware publication. +#[derive(Copy,Clone)]struct UmaIdle{power_off:bool,held:bool,invalidations:u32,before_post:u32} +thread_local!{static UMA_IDLE:std::cell::Cell=const{std::cell::Cell::new(UmaIdle{power_off:false,held:false,invalidations:0,before_post:0})};} +impl Session{fn idle_power_off(&self)->bool{UMA_IDLE.with(|u|u.get().power_off)}} struct Slots{compute_exhausted:bool,render_exhausted:bool,releases:u32,quarantines:u32} impl Slots{ fn compute_uma_held(&self)->bool{UMA_IDLE.with(|u|u.get().held)} @@ -293,6 +307,7 @@ def item(declaration): // dependency selection and error isolation execute verbatim above and below it. fn publish_prefix_into(&mut self,job:&Arc,_flight:&mut Flight,visible:&mut bool,pending_rings:&mut u8)->Result{ self.attempted.push(job.id); + UMA_IDLE.with(|u|{let mut s=u.get();s.before_post=s.invalidations;u.set(s);}); let stage=self.stages.pop_front().expect("unexpected hardware publication"); *visible=stage.visible; if stage.result.is_ok(){ @@ -328,7 +343,7 @@ def item(declaration): } fn firmware(jobs:Vec>,stages:Vec<(Result,bool)>)->Firmware{ Firmware{session:Session{shared:Shared{sleeping:AtomicBool::new(false)},rings:vec![],ring_fail:false,checks:AtomicU32::new(0),transports:AtomicU32::new(0)},objects:Checks,recovery:Recovery{error:None,publication_wait_deadline:None}, - engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,held_wait:false,handoff_avoid_pipes:0,coalesce_deadline_ns:0,powered_flag_proven:false}, + engine:Engine{ordinal:0,draw:0,pending:jobs,flights:vec![],frozen:false,turn:0,stats:Stats::default(),chan_wait:false,slot_wait:false,held_wait:false,handoff_avoid_pipes:0,coalesce_deadline_ns:0}, slots:Slots{compute_exhausted:false,render_exhausted:false,releases:0,quarantines:0},pools:Pools{exhausted:false,exhausted_vm:None,block_pipeline_vm:None},power:Power::default(), unavailable:vec![],stages:stages.into_iter().map(|(result,visible)|Stage{result,visible}).collect(), retained:vec![],attempted:vec![],fail_stops:0,allow_behind:false,block_render_behind:false,block_compute_behind:false, @@ -1290,9 +1305,10 @@ def item(declaration): assert_eq!(r2r, WaitTarget { stamp: 0x900, initbm: true }); assert_eq!(cross_engine_barrier_type(r2r.initbm, false), BarrierType::Hold); } - fn uma_set(held:bool,flag:Option){UMA_IDLE.with(|u|u.set(UmaIdle{held,flag,reads:0,invalidations:0}));} - fn uma_flag(flag:Option){UMA_IDLE.with(|u|{let mut s=u.get();s.flag=flag;u.set(s);});} - fn uma_seen()->(u32,u32){UMA_IDLE.with(|u|{let s=u.get();(s.reads,s.invalidations)})} + fn uma_set(power_off:bool,held:bool){UMA_IDLE.with(|u|u.set(UmaIdle{power_off,held,invalidations:0,before_post:0}));} + fn uma_hold(){UMA_IDLE.with(|u|{let mut s=u.get();s.held=true;u.set(s);});} + fn uma_seen()->(u32,bool){UMA_IDLE.with(|u|{let s=u.get();(s.invalidations,s.held)})} + fn uma_before_post()->u32{UMA_IDLE.with(|u|u.get().before_post)} // One publication pass that publishes `job` from an idle engine, then its retirement. fn idle_pass(fw:&mut Firmware,id:u32,done:&mut Completions){ fw.engine.pending.push(job(id,false,0,Ok(()))); @@ -1300,78 +1316,73 @@ def item(declaration): fw.publish_checked(done).unwrap(); fw.engine.flights.clear(); } - #[test]fn uma_idle_check_reads_the_powered_flag_only_for_a_held_manager_on_an_idle_engine(){ + #[test]fn uma_held_managers_stay_bound_while_the_boot_policy_holds_power(){ let mut done=vec![]; - // No shared manager held (render-only work): no flag read on any pass. - uma_set(false,Some(false)); - let mut fw=firmware(vec![job(1,true,0,Ok(()))],vec![(Ok(()),true)]); - fw.publish_checked(&mut done).unwrap(); - assert_eq!(fw.engine.flights.len(),1); - fw.allow_behind=true; - fw.engine.pending.push(job(2,true,0,Ok(()))); - fw.stages.push_back(Stage{result:Ok(()),visible:true}); - fw.publish_checked(&mut done).unwrap(); - assert_eq!(uma_seen(),(0,0)); - // A held manager and a flight in flight: the GPU has not powered down, no read. - uma_set(true,Some(false)); - fw.engine.pending.push(job(3,false,0,Ok(()))); - fw.stages.push_back(Stage{result:Ok(()),visible:true}); - fw.publish_checked(&mut done).unwrap(); - assert_eq!(uma_seen(),(0,0)); - // Nothing pending: no pass work at all. + // The firmware holds the GPU powered: idle passes with a manager held invalidate nothing. + uma_set(false,true); let mut fw=firmware(vec![],vec![]); - fw.publish_checked(&mut done).unwrap(); - assert_eq!(uma_seen(),(0,0)); + for id in 1..=4{idle_pass(&mut fw,id,&mut done);} + assert_eq!(uma_seen(),(0,true)); + assert_eq!(fw.engine.stats.uma_idle_invalidations,0); + assert_eq!(fw.attempted,[1,2,3,4]); } - #[test]fn uma_powered_flag_never_nonzero_at_idle_never_invalidates(){ + #[test]fn uma_idle_pass_invalidates_before_posting_when_the_gpu_may_power_off(){ let mut done=vec![]; - // A flag that stays zero: read on every idle pass, never trusted, nothing invalidated. - uma_set(true,Some(false)); + // The firmware may power the GPU off: a pass with nothing in flight and a manager held + // invalidates, before it posts the pass's first command. + uma_set(true,true); let mut fw=firmware(vec![],vec![]); - for id in 1..=4{idle_pass(&mut fw,id,&mut done);} - assert_eq!(uma_seen(),(4,0)); - assert!(!fw.engine.powered_flag_proven); - // A flag set only while work runs: passes with work in flight never read it, and at idle - // it reads zero, so it is never trusted either. - fw.allow_behind=true; - fw.engine.pending.push(job(5,false,0,Ok(()))); - fw.stages.push_back(Stage{result:Ok(()),visible:true}); - fw.publish_checked(&mut done).unwrap(); - uma_flag(Some(true)); - fw.engine.pending.push(job(6,false,0,Ok(()))); - fw.stages.push_back(Stage{result:Ok(()),visible:true}); + idle_pass(&mut fw,1,&mut done); + assert_eq!(uma_seen(),(1,false)); + assert_eq!(uma_before_post(),1); + assert_eq!(fw.engine.stats.uma_idle_invalidations,1); + // Nothing held since: nothing to invalidate. + idle_pass(&mut fw,2,&mut done); + assert_eq!(uma_seen(),(1,false)); + // Every quiescent pass with a manager bound again invalidates again: no timing applies. + for id in 3..=5{uma_hold();idle_pass(&mut fw,id,&mut done);} + assert_eq!(uma_seen(),(4,false)); + assert_eq!(fw.engine.stats.uma_idle_invalidations,4); + assert_eq!(fw.attempted,[1,2,3,4,5]); + } + #[test]fn uma_no_idle_invalidation_with_work_in_flight(){ + let mut done=vec![]; + // A flight in flight keeps the GPU busy, also when it may power off while idle. + uma_set(true,false); + let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); fw.publish_checked(&mut done).unwrap(); + assert_eq!(fw.engine.flights.len(),1); + uma_hold(); + fw.allow_behind=true; + for id in 2..=3{ + fw.engine.pending.push(job(id,false,0,Ok(()))); + fw.stages.push_back(Stage{result:Ok(()),visible:true}); + fw.publish_checked(&mut done).unwrap(); + } + assert_eq!(fw.attempted,[1,2,3]); + assert_eq!(fw.engine.flights.len(),3); + assert_eq!(uma_seen(),(0,true)); + assert_eq!(fw.engine.stats.uma_idle_invalidations,0); + // Once the flights retired, the next pass invalidates. fw.engine.flights.clear(); - uma_flag(Some(false)); - idle_pass(&mut fw,7,&mut done); - assert_eq!(uma_seen(),(6,0)); - assert!(!fw.engine.powered_flag_proven); - // A firmware without the flag keeps the GPU powered: never trusted, nothing invalidated. - uma_set(true,None); - let mut fw=firmware(vec![],vec![]); - idle_pass(&mut fw,8,&mut done); - assert_eq!(uma_seen(),(1,0)); - assert!(!fw.engine.powered_flag_proven); + idle_pass(&mut fw,4,&mut done); + assert_eq!(uma_seen(),(1,false)); } - #[test]fn uma_powered_flag_seen_nonzero_at_idle_invalidates_after_power_down(){ + #[test]fn uma_no_idle_invalidation_without_a_held_shared_manager(){ let mut done=vec![]; - // Idle and powered: the flag reads nonzero, so it tracks GPU power from now on. - uma_set(true,Some(true)); + // Render-only (or private-only) work holds no shared manager: nothing to invalidate. + uma_set(true,false); + let mut fw=firmware(vec![job(1,true,0,Ok(()))],vec![(Ok(()),true)]); + fw.publish_checked(&mut done).unwrap(); + fw.engine.flights.clear(); + for id in 2..=3{idle_pass(&mut fw,id,&mut done);} + assert_eq!(uma_seen(),(0,false)); + assert_eq!(fw.engine.stats.uma_idle_invalidations,0); + // Nothing pending: no pass work at all, even with a manager held. + uma_set(true,true); let mut fw=firmware(vec![],vec![]); - idle_pass(&mut fw,1,&mut done); - assert_eq!(uma_seen(),(1,0)); - assert!(fw.engine.powered_flag_proven); - // Powered down at the next idle pass: every held binding is invalidated. - uma_flag(Some(false)); - idle_pass(&mut fw,2,&mut done); - assert_eq!(uma_seen(),(2,1)); - // Invalidation drops the held state: no read until a shared manager is bound again. - idle_pass(&mut fw,3,&mut done); - assert_eq!(uma_seen(),(2,1)); - UMA_IDLE.with(|u|{let mut s=u.get();s.held=true;u.set(s);}); - idle_pass(&mut fw,4,&mut done); - assert_eq!(uma_seen(),(3,2)); - assert!(fw.engine.powered_flag_proven,"trust stays for the boot"); + fw.publish_checked(&mut done).unwrap(); + assert_eq!(uma_seen(),(0,true)); } #[test]fn publish_checked_uses_transport_without_repeating_session_check(){ let mut fw=firmware(vec![job(1,false,0,Ok(()))],vec![(Ok(()),true)]); From 61d33810c21377716c86e62ce2f7fe2ada64c572 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 10:22:35 -0500 Subject: [PATCH 5/7] drm/asahi: g16: rebuild a drained compute UMA manager without reseeding its pool When a shared compute UMA manager's binding may be gone (it was displaced, or the GPU may have powered off while idle), its next command rebuilds its manager record. The rebuild also rewrote all 8192 freelist records (64 KiB of uncached writes) and the 16 pool-table rows. When the firmware may power the GPU off on its own, every publication with nothing in flight invalidates the held managers, so nearly every job after an idle gap paid for that. The freelist is a ring of 16384 records. The hardware takes pages at the head cursor and returns them at the tail cursor, and both wrap at the record count that bind loads with them. A rebuild restarts the cursors at their seed: head 0, tail 8192. Taking a page only reads its record; returning one writes the record at the tail. So after a restart, returns fill the records from 8192 upwards, and none reaches the first 8192 records before one has written the last record of the ring. Until then the first 8192 records still hold the seed, every page exactly once, and cursors at their seed describe the drained pool exactly, wherever the hardware cursors were. Pages the hardware still held when its cursors were lost do not matter: they are in the seed, and with no command in flight no page is in use. So the rebuild now reads two freelist records before it decides. The last record reads zero until a return reaches it: the freelist is zeroed when it is allocated, and a returned record holds a page address. The first record still holds the first seed unless taking a page wrote its record. If both hold, the rebuild writes only the 160-byte manager record and the 16 pool-row words. Otherwise it reseeds the freelist as before and clears the last record, so that a later rebuild can trust the seed again. Some events do not show in the freelist. A system sleep, a recovery, and a shared command that failed or was aborted advance a seed generation in the slot ledger, and the next rebuild of every manager then reseeds, whatever its freelist shows. Sleep and recovery call the new restart_compute_uma(), which also invalidates the bindings; the idle path still calls only invalidate_compute_uma(). On J773g, with #3695 and #3697 combined, skipping the reseed unconditionally (idle invalidations unchanged, about 179k per boot) measured: row as is no reseed no invalidation idle.wake 2/20/200 ms 175/272/539 145/193/458 142/192/458 compute queue d1 121.5 99.1 101.2 compute procs d2 67.9 59.0 58.3 That run passed the CRC smoke test 10/10 and the idle.wake stress with checked compute, with the GPU physically off in 16 of 16 checks and no faults. The reseed was the whole cost of the idle rebuild. This change skips it only while the ring has not reached its end since the last seed, which a run of short jobs between idle gaps never does. The stats line gains the reseed count: "compute_uma: rebuilds N invalidations M idle_invalidations K reseeds R". Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/poll.rs | 7 +- drivers/gpu/drm/asahi/g16/recovery.rs | 2 +- drivers/gpu/drm/asahi/g16/resources.rs | 39 +++- drivers/gpu/drm/asahi/g16/sleep.rs | 2 +- drivers/gpu/drm/asahi/g16/slots.rs | 110 +++++++-- .../drivers/gpu/asahi-m4/test-resources.py | 213 ++++++++++++++++-- 6 files changed, 322 insertions(+), 51 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 8d8e070af6e69..92c05577149f9 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -2255,8 +2255,11 @@ impl Firmware { )?; writeln!( f, - "compute_uma: rebuilds {} invalidations {} idle_invalidations {}", - slots.uma_rebuilds, slots.uma_invalidations, s.uma_idle_invalidations + "compute_uma: rebuilds {} invalidations {} idle_invalidations {} reseeds {}", + slots.uma_rebuilds, + slots.uma_invalidations, + s.uma_idle_invalidations, + slots.uma_reseeds )?; writeln!( f, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index e1c6beab5ddfe..b41a20e1b3393 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -597,7 +597,7 @@ impl Firmware { // writes the fault-bank selector so it must not run against active FW). self.pools.invalidate(); self.slots.invalidate_scrub(); - self.slots.invalidate_compute_uma(); + self.slots.restart_compute_uma(); self.events.grow.clear(); let stage = self.recovery_snapshot()?; // Powered down, the GPU holds no fault to read. diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index ee0e471c0f38d..022b97d6b358e 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -245,6 +245,9 @@ pub(crate) struct SharedComputeUmaInner { pub(crate) id: u64, /// Set once a record was first initialised for this manager. bound: AtomicBool, + /// The slot ledger's seed generation when `init_record` last seeded or checked the + /// freelist. + seed_gen: AtomicU64, pub(crate) counter: Arc, pub(crate) pool: Arc, pub(crate) pool_state: Arc, @@ -318,6 +321,7 @@ impl SharedComputeUma { records, id: NEXT_SHARED_UMA_ID.fetch_add(1, Ordering::Relaxed), bound: AtomicBool::new(false), + seed_gen: AtomicU64::new(0), counter, pool, pool_state, @@ -360,20 +364,30 @@ impl SharedComputeUmaInner { /// submission count, so the firmware's next completion lines up with the next submission. /// The firmware never writes a displaced or lost binding back (it saves a manager only at a /// completion with COMPLETED equal to `*counter`, which the in-flight hold prevents), so the - /// freelist of a manager that ran before no longer matches any record. Its pool is drained: - /// seed the freelist and pool rows afresh with the cursors. - pub(crate) fn init_record(&self, rec: usize) -> Result { + /// hardware cursors of a manager that ran before are gone. Its pool is drained, and cursors + /// at their seed describe its freelist exactly while the freelist still holds the seed + /// ([`super::slots::uma_seed_intact`]) and the slot ledger's seed generation `seed_gen` + /// has not advanced since the last seed or check. Otherwise seed the freelist afresh with + /// the cursors. The pool rows are rewritten either way. Returns whether the freelist was + /// seeded. + pub(crate) fn init_record(&self, rec: usize, seed_gen: u64) -> Result { let record = self.records.get(rec).ok_or(EINVAL)?; let pool_state = self.pool_state.gva.ok_or(EINVAL)?; let page_list = self.page_list.gva.ok_or(EINVAL)?; - if self.bound.swap(true, Ordering::AcqRel) { - super::slots::init_uma_pool( - &self.pool_state, - &self.page_list, - self.pool.gva.ok_or(EINVAL)?, - self.seeds, - )?; - } + let pool = self.pool.gva.ok_or(EINVAL)?; + let reseed = if !self.bound.swap(true, Ordering::AcqRel) { + // `new` seeded the freelist and pool rows, and nothing ran on them since. + false + } else if self.seed_gen.load(Ordering::Acquire) == seed_gen + && super::slots::uma_seed_intact(&self.pool_state, pool, self.seeds)? + { + super::slots::init_uma_rows(&self.page_list, pool, self.seeds)?; + false + } else { + super::slots::reseed_uma_pool(&self.pool_state, &self.page_list, pool, self.seeds)?; + true + }; + self.seed_gen.store(seed_gen, Ordering::Release); let mut image = super::fw::buffer::compute_uma_manager_image( record.va, self.uma_slot, @@ -386,7 +400,8 @@ impl SharedComputeUmaInner { let completed = super::fw::graph::manager::COMPLETED; image[completed..completed + 8] .copy_from_slice(&self.submitted.load(Ordering::Acquire).to_le_bytes()); - record.write(0, &image) + record.write(0, &image)?; + Ok(reseed) } } diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index cfd0a6a63f85c..99dcf9ca4febf 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -63,7 +63,7 @@ impl Firmware { // Start the next render on each pass slot fresh after the firmware restarts, and the // next compute of every UMA manager left bound from a reloaded record. self.pools.invalidate(); - self.slots.invalidate_compute_uma(); + self.slots.restart_compute_uma(); self.session.rtkit.warm_restart()?; let control = self.session.regs.asc_control()?; self.session.regs.set_asc_control(control | ASC_RUN)?; diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index b8df48db002c3..83fe22b16a20d 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -201,10 +201,10 @@ const _: () = assert!( && super::rt::window_bytes(super::rt::MAX_SCS_SEEDS) <= client::SCS_POOL_WINDOW ); -/// Initializes the private pool exactly once, before it is exposed. Never called on reuse. -/// `seeds` 4-KiB freelist entries and their 2-MiB pool-table rows; 8192 is the 32 MiB pool -/// every unit had before SCS. The freelist `state` holds every seed, the pool table `list` -/// every row. +/// Initializes a pool before it is first exposed, or reseeds a drained shared pool +/// ([`reseed_uma_pool`]). `seeds` 4-KiB freelist entries and their 2-MiB pool-table rows; 8192 +/// is the 32 MiB pool every unit had before SCS. The freelist `state` holds every seed in its +/// first `seeds` records, the pool table `list` every row. pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: u32) -> Result { let seeds = seeds as usize; let rows = seeds / super::rt::SEEDS_PER_ROW as usize; @@ -224,8 +224,57 @@ pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: } state.write(first * 8, &chunk)?; } + init_uma_rows(list, pool, seeds as u32) +} + +/// Writes the pool-table rows of a pool of `seeds` entries at `pool` into `list`. +pub(crate) fn init_uma_rows(list: &FwObject, pool: u64, seeds: u32) -> Result { + use super::fw::buffer::uma_pools::{row, POOL_SIZE, POOL_TABLE_STRIDE}; + let rows = (seeds / super::rt::SEEDS_PER_ROW) as usize; + if rows * POOL_TABLE_STRIDE > list.size { + return Err(EINVAL); + } for i in 0..rows { - list.w64(i * 64, (1u64 << 61) | (pool + i as u64 * 0x200000))?; + list.w64(i * POOL_TABLE_STRIDE, row(pool + i as u64 * POOL_SIZE))?; + } + Ok(()) +} + +/// Byte offset of the last record of the freelist of a pool of `seeds` entries. +const fn last_uma_record(seeds: u32) -> usize { + (super::rt::freelist_records(seeds) as usize - 1) * super::rt::RECORD_BYTES as usize +} + +/// Whether the freelist `state` of a drained pool of `seeds` entries at `pool` still holds its +/// seed in its first `seeds` records. Then allocator cursors restarted at their seed (head 0, +/// tail `seeds`) name every page of the pool exactly once, wherever the hardware cursors were. +/// +/// The freelist is a ring of [`super::rt::freelist_records`] records, more than the pool's +/// seeds. The hardware takes pages at the head cursor (+0x20) and returns them at the tail +/// cursor (+0x24). Both wrap at the record count (+0x1c) that bind loads with them. Only a +/// return writes a record. So after a restart, returns fill the records from `seeds` upwards, +/// and none reaches the first `seeds` records before one has written the last record of the +/// ring. That record reads zero until then: the freelist is zeroed when it is allocated, +/// [`reseed_uma_pool`] clears it, the seed stops short of it, and a returned record holds the +/// address of a page. +/// +/// The first record is checked too. Every restart puts the head on it, so if taking a page +/// wrote its record, the first record would show it. +/// +/// What the hardware held when its cursors were lost (pages it had taken, returns it had not +/// written yet) does not matter: the first `seeds` records hold every page exactly once either +/// way, and with no command in flight no page is in use. +pub(crate) fn uma_seed_intact(state: &FwObject, pool: u64, seeds: u32) -> Result { + Ok(state.r64(last_uma_record(seeds))? == 0 && state.r64(0)? == pool) +} + +/// Seeds a drained pool afresh ([`init_uma_pool`]), and clears the last record of its +/// freelist if returns reached it, so that [`uma_seed_intact`] can trust the seed again. +pub(crate) fn reseed_uma_pool(state: &FwObject, list: &FwObject, pool: u64, seeds: u32) -> Result { + init_uma_pool(state, list, pool, seeds)?; + let last = last_uma_record(seeds); + if state.r64(last)? != 0 { + state.w64(last, 0)?; } Ok(()) } @@ -818,9 +867,11 @@ pub(crate) struct SlotStats { pub(crate) tpc_clear_bytes: u64, pub(crate) tilemap_clear_bytes: u64, pub(crate) pass_scrubs: u64, - /// Shared compute UMA manager records rebuilt (freelist reseeded) and residency - /// invalidations ([`Slots::bind_compute_uma`], [`Slots::invalidate_compute_uma`]). + /// Shared compute UMA manager records rebuilt, those of them that reseeded their freelist, + /// and residency invalidations ([`Slots::bind_compute_uma`], + /// [`Slots::invalidate_compute_uma`]). pub(crate) uma_rebuilds: u64, + pub(crate) uma_reseeds: u64, pub(crate) uma_invalidations: u64, } @@ -852,6 +903,11 @@ pub(crate) struct ComputeOwners { uma_live_gen: u64, /// A shared manager was bound since the last advance of [`Self::uma_live_gen`]. uma_held: bool, + /// Advanced whenever no drained shared freelist is trusted to hold its seed, whatever it + /// shows ([`super::resources::SharedComputeUmaInner::init_record`]): after a system sleep + /// or a recovery ([`Slots::restart_compute_uma`]), or a shared command that failed + /// ([`Slots::mark_dirty`]) or was aborted ([`Slots::quarantine`]). + uma_seed_gen: u64, pending_uma: [Option>; sizes::COMPUTE_UNITS], pending_uma_slot: [usize; sizes::COMPUTE_UNITS], /// In-flight VM-shared compute UMA backing (`None` for private/SCS units). Dropped on clean @@ -1152,6 +1208,7 @@ impl Slots { uma_private_flights: [0; sizes::COMPUTE_UMA_SLOTS], uma_live_gen: 0, uma_held: false, + uma_seed_gen: 0, pending_uma: [const { None }; sizes::COMPUTE_UNITS], pending_uma_slot: [sizes::COMPUTE_UMA_SLOTS; sizes::COMPUTE_UNITS], pending_shared_uma: [const { None }; sizes::COMPUTE_UNITS], @@ -1531,9 +1588,13 @@ impl Slots { self.scrub.clear_all_clean(); } - /// Forces a full scrub on the next claim of the units in `f` (after an affected error). + /// Forces a full scrub on the next claim of the units in `f` (after an affected error) and, + /// if `f` ran shared compute commands, a reseed at the next rebuild of every shared manager. #[allow(dead_code)] pub(crate) fn mark_dirty(&mut self, f: &Claims) { + if f.uma_rec != NO_UMA_RECORD { + self.distrust_compute_uma_seeds(); + } for &k in &f.slot[..(f.slot_count as usize).min(f.slot.len())] { if let Some(dirty) = self.compute.scrub_full.get_mut(k as usize) { *dirty = true; @@ -2015,8 +2076,9 @@ impl Slots { /// at the same time (the engine's UMA conflict check). /// - Otherwise its cursors are gone (displaced, or lost over an idle power-down, a sleep or /// a recovery): rebuild a record the slot table does not name - /// ([`super::resources::SharedComputeUmaInner::init_record`] reseeds the drained freelist - /// and pool rows and restarts the cursors and COMPLETED together). + /// ([`super::resources::SharedComputeUmaInner::init_record`] restarts the cursors and + /// COMPLETED together, and reseeds the drained freelist only if it may no longer hold + /// its seed). pub(crate) fn bind_compute_uma( &mut self, shared: &Arc, @@ -2037,8 +2099,11 @@ impl Slots { let rec = (0..UMA_RECORDS) .find(|&r| c.uma_bound[slot] != UmaBound::Record(r as u8)) .ok_or(EINVAL)?; - shared.init_record(rec)?; + let reseeded = shared.init_record(rec, c.uma_seed_gen)?; self.stats.uma_rebuilds = self.stats.uma_rebuilds.saturating_add(1); + if reseeded { + self.stats.uma_reseeds = self.stats.uma_reseeds.saturating_add(1); + } Ok(Some(rec)) } @@ -2126,10 +2191,9 @@ impl Slots { } } - /// The hardware allocator state of bound shared managers may be gone: the GPU powered down - /// while idle, a system sleep restarted the firmware, or a recovery reloaded or abandoned - /// slots. Trust none of them: each rebuilds a record the slot table does not name, with a - /// reseeded freelist, once its own commands have retired. + /// The hardware allocator state of bound shared managers may be gone: the GPU may have + /// powered down while idle. Trust none of them: each rebuilds a record the slot table does + /// not name once its own commands have retired. pub(crate) fn invalidate_compute_uma(&mut self) { let c = &mut self.compute; c.uma_live_gen = c.uma_live_gen.wrapping_add(1); @@ -2137,6 +2201,18 @@ impl Slots { self.stats.uma_invalidations = self.stats.uma_invalidations.saturating_add(1); } + /// A system sleep restarted the firmware, or a recovery reloaded or abandoned slots: as + /// [`Self::invalidate_compute_uma`], and each manager's rebuild also reseeds its freelist. + pub(crate) fn restart_compute_uma(&mut self) { + self.invalidate_compute_uma(); + self.distrust_compute_uma_seeds(); + } + + /// Makes the next rebuild of every shared manager reseed its freelist, whatever it shows. + fn distrust_compute_uma_seeds(&mut self) { + self.compute.uma_seed_gen = self.compute.uma_seed_gen.wrapping_add(1); + } + /// Whether a shared manager may be bound with its cursors only in the hardware: one was /// bound since the last [`Self::invalidate_compute_uma`]. pub(crate) fn compute_uma_held(&self) -> bool { @@ -2447,6 +2523,10 @@ impl Slots { Ok(()) } pub(crate) fn quarantine(&mut self, f: &mut Claims) { + // The aborted manager stays quarantined with its slot; no other rebuild trusts a seed. + if f.uma_rec != NO_UMA_RECORD { + self.distrust_compute_uma_seeds(); + } for &k in &f.slot[..f.slot_count as usize] { self.compute.lifetime.quarantine(k as usize); let slot = self.compute.pending_uma_slot[k as usize]; 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 de66c2c277195..95df4f148b4e8 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -121,6 +121,7 @@ def module(text, name): pub fn w32(&self,o:usize,v:u32)->Result{self.write(o,&v.to_le_bytes())} pub fn w64(&self,o:usize,v:u64)->Result{self.write(o,&v.to_le_bytes())} pub fn r32(&self,o:usize)->Result{let d=self.data.lock().unwrap();Ok(u32::from_le_bytes(d[self.offset+o..self.offset+o+4].try_into().unwrap()))} + pub fn r64(&self,o:usize)->Result{let d=self.data.lock().unwrap();Ok(u64::from_le_bytes(d[self.offset+o..self.offset+o+8].try_into().unwrap()))} pub fn snapshot(&self)->Vec{self.data.lock().unwrap().clone()} } pub struct FwLease(pub crate::cleanup::Deferred); @@ -3821,25 +3822,41 @@ def module(text, name): } assert_eq!(rd64(&u.page_list, 0), (1u64 << 61) | pool); } - // What the firmware leaves behind while it runs a manager: allocations moved its - // freelist, and its hardware cursors are ahead of its record. - fn run_on_gpu(u: &SharedComputeUma) { - u.pool_state.w64(0, 0xdead_0000).unwrap(); - u.pool_state.w64(8 * 64, 0xdead_1000).unwrap(); - u.page_list.w64(0, 0).unwrap(); + // What the hardware leaves in a manager's freelist ring after `returns` pages came back + // since its record was built (slots.rs `uma_seed_intact`): taking a page reads its + // record at the head; returning one writes the record at the tail, from record `seeds` + // upwards, wrapping at the record count into the seed. Pages come back in another order + // than they went out. Its hardware cursors are ahead of its record. + fn run_on_gpu(u: &SharedComputeUma, returns: usize) { + let records = g16::rt::freelist_records(u.seeds) as usize; + let pool = u.pool.gva.unwrap(); + for i in 0..returns { + let page = (i * 7 + 3) % u.seeds as usize; + let at = (u.seeds as usize + i) % records; + u.pool_state.w64(at * 8, pool + page as u64 * 0x1000).unwrap(); + } + } + // Returns past the end of the ring, `into` records into the seed. + fn wrap_on_gpu(u: &SharedComputeUma, into: usize) { + run_on_gpu(u, (g16::rt::freelist_records(u.seeds) - u.seeds) as usize + into); + } + fn record_writes(u: &SharedComputeUma) -> usize { + u.records.iter().map(|r| writes(r)).sum() } #[test] - fn return_after_displacement_rebuilds_record_and_reseeds_freelist() { + fn return_after_displacement_rebuilds_record() { let mut s = Slots::new().unwrap(); let (a, _va, _ba, _la) = new_uma(3001, 5); let (b, _vb, _bb, _lb) = new_uma(3002, 5); - // A runs under the hold: the firmware keeps it bound and never saves it. + // A runs under the hold: the firmware keeps it bound and never saves it. Its + // returns wrap around the ring into the seed. let ca = publish(&mut s, &a, 2).unwrap(); let ra = ca.uma_rec; assert_rebuilt(&a, ra as usize, 2); assert_eq!(rd64(&a.counter, 0), 3); - run_on_gpu(&a); + wrap_on_gpu(&a, 64); + a.page_list.w64(0, 0).unwrap(); assert!(retire(&mut s, &a, &ca, 2), "drained"); assert_eq!(rd64(&a.counter, 0), 2, "counter back at the submissions"); // B (a 33rd VM sharing the slot) binds a record the slot table does not name, @@ -3848,24 +3865,30 @@ def module(text, name): assert_ne!(cb.uma_rec, ra, "the record the slot table names is never rewritten"); assert_rebuilt(&b, cb.uma_rec as usize, 1); assert!(retire(&mut s, &b, &cb, 1)); - // A returns: its record and its whole freelist are rebuilt. + // A returns: its record and its whole freelist are rebuilt, and the last record of + // its ring is cleared. let before = (writes(&a.pool_state), writes(&a.page_list)); let ca2 = publish(&mut s, &a, 1).unwrap(); assert_ne!(ca2.uma_rec, cb.uma_rec, "B's binding keeps its record"); assert_rebuilt(&a, ca2.uma_rec as usize, 1); assert_seeded(&a); - assert_eq!(writes(&a.pool_state) - before.0, a.seeds as usize * 8, "whole freelist reseeded"); + assert_eq!(writes(&a.pool_state) - before.0, a.seeds as usize * 8 + 8, "whole freelist reseeded"); assert_eq!(writes(&a.page_list) - before.1, (a.seeds / g16::rt::SEEDS_PER_ROW) as usize * 8, "every pool row"); + assert_eq!(rd64(&a.pool_state, (g16::rt::freelist_records(a.seeds) as usize - 1) * 8), 0); assert_eq!(rd64(&a.counter, 0), 4); assert!(retire(&mut s, &a, &ca2, 1)); - // B returns after A: rebuilt as well. - run_on_gpu(&b); - let wb = uma_writes(&b); + // B returns after A: rebuilt as well. Its returns stayed short of the end of the + // ring, so its freelist still holds the seed and only its record and rows are + // written. + run_on_gpu(&b, 20); + let wb = (record_writes(&b), writes(&b.pool_state)); let cb2 = publish(&mut s, &b, 1).unwrap(); assert_ne!(cb2.uma_rec, ca2.uma_rec); - assert!(uma_writes(&b) > wb); + assert_eq!(record_writes(&b) - wb.0, manager::SIZE); + assert_eq!(writes(&b.pool_state), wb.1, "no freelist record written"); assert_rebuilt(&b, cb2.uma_rec as usize, 1); assert_seeded(&b); + assert_eq!((s.stats.uma_rebuilds, s.stats.uma_reseeds), (4, 1)); } #[test] @@ -3911,7 +3934,7 @@ def module(text, name): s.note_private_uma_published(&p); assert_eq!(s.bind_compute_uma(&a).unwrap(), None, "shared waits for the private unit"); s.retire_private_uma(&p); - run_on_gpu(&a); + run_on_gpu(&a, 40); let ca2 = publish(&mut s, &a, 1).unwrap(); assert_rebuilt(&a, ca2.uma_rec as usize, 1); assert_seeded(&a); @@ -3938,13 +3961,13 @@ def module(text, name): assert!(retire(&mut s, &b, &cb, 1)); assert!(s.compute_uma_held(), "drained managers stay bound"); assert_eq!((s.stats.uma_rebuilds, s.stats.uma_invalidations), (2, 0), "first records"); - // An idle power-down, a sleep or a recovery: no binding is trusted. Each rebuilds - // in the record the slot table does not name. + // An idle power-down: no binding is trusted. Each rebuilds in the record the slot + // table does not name. s.invalidate_compute_uma(); assert!(!s.compute_uma_held()); assert_eq!(s.stats.uma_invalidations, 1); - run_on_gpu(&a); - run_on_gpu(&b); + run_on_gpu(&a, 100); + run_on_gpu(&b, 100); let (wa, wb) = (uma_writes(&a), uma_writes(&b)); let ca2 = publish(&mut s, &a, 1).unwrap(); let cb2 = publish(&mut s, &b, 1).unwrap(); @@ -3970,6 +3993,156 @@ def module(text, name): assert_eq!(ca4.uma_rec, ca3.uma_rec); assert_eq!(uma_writes(&a), w); assert_eq!(s.stats.uma_rebuilds, 5, "the fast path rebuilds nothing"); + assert_eq!(s.stats.uma_reseeds, 0, "no freelist ever wrapped"); + } + + // Each rebuild restarts the cursors at their seed, so the returns between two rebuilds + // fill the ring from record `seeds` again. As long as they stay short of its last + // record, a rebuild after an idle invalidation writes the record and the pool rows and + // no freelist record, however many returns there were in all. + #[test] + fn idle_rebuild_of_a_drained_manager_keeps_its_freelist() { + let mut s = Slots::new().unwrap(); + let (a, _v, _b, _l) = new_uma(3051, 9); + let past_seed = (g16::rt::freelist_records(a.seeds) - a.seeds) as usize; + let rows = (a.seeds / g16::rt::SEEDS_PER_ROW) as usize * 8; + let mut c = publish(&mut s, &a, 1).unwrap(); + for round in 0..4u64 { + run_on_gpu(&a, past_seed - 1); + a.page_list.w64(0, 0).unwrap(); + assert!(retire(&mut s, &a, &c, 1)); + s.invalidate_compute_uma(); + let before = (record_writes(&a), writes(&a.pool_state), writes(&a.page_list)); + c = publish(&mut s, &a, 1).unwrap(); + assert_rebuilt(&a, c.uma_rec as usize, 1); + assert_eq!(record_writes(&a) - before.0, manager::SIZE, "the record"); + assert_eq!(writes(&a.pool_state), before.1, "no freelist record"); + assert_eq!(writes(&a.page_list) - before.2, rows, "the pool rows"); + assert_seeded(&a); + assert_eq!((s.stats.uma_rebuilds, s.stats.uma_reseeds), (2 + round, 0)); + } + } + + // Returns that reached the last record of the ring may continue into the seed, and a + // take that wrote its record would show in the first: the next rebuild reseeds the + // freelist and clears the last record, and the one after trusts the seed again. + #[test] + fn rebuild_reseeds_a_freelist_that_may_have_left_its_seed() { + let mut s = Slots::new().unwrap(); + let (a, _v, _b, _l) = new_uma(3061, 10); + let records = g16::rt::freelist_records(a.seeds) as usize; + let last = (records - 1) * 8; + let whole = a.seeds as usize * 8; + let mut c = publish(&mut s, &a, 1).unwrap(); + let cases: [fn(&SharedComputeUma); 3] = [ + // Up to the last record: no proof the next return stays out of the seed. + |u| run_on_gpu(u, (g16::rt::freelist_records(u.seeds) - u.seeds) as usize), + // Around the ring and 3 records into the seed. + |u| wrap_on_gpu(u, 3), + // A take that wrote the first record. + |u| u.pool_state.w64(0, 0).unwrap(), + ]; + for (n, ran) in cases.into_iter().enumerate() { + ran(&a); + let cleared = if rd64(&a.pool_state, last) != 0 { 8 } else { 0 }; + assert!(retire(&mut s, &a, &c, 1)); + s.invalidate_compute_uma(); + let w = writes(&a.pool_state); + c = publish(&mut s, &a, 1).unwrap(); + assert_rebuilt(&a, c.uma_rec as usize, 1); + assert_eq!(writes(&a.pool_state) - w, whole + cleared, "case {n}"); + assert_eq!(rd64(&a.pool_state, last), 0, "case {n}"); + assert_seeded(&a); + assert_eq!(s.stats.uma_reseeds, n as u64 + 1); + } + run_on_gpu(&a, 5); + assert!(retire(&mut s, &a, &c, 1)); + s.invalidate_compute_uma(); + let w = writes(&a.pool_state); + publish(&mut s, &a, 1).unwrap(); + assert_eq!(writes(&a.pool_state), w, "trusted again"); + assert_eq!((s.stats.uma_rebuilds, s.stats.uma_reseeds), (5, 3)); + } + + // A system sleep or a recovery (`Slots::restart_compute_uma`): every manager's next + // rebuild reseeds its freelist, however intact it looks, once. + #[test] + fn rebuild_after_sleep_or_recovery_reseeds() { + let mut s = Slots::new().unwrap(); + let (a, _va, _ba, _la) = new_uma(3071, 11); + let (b, _vb, _bb, _lb) = new_uma(3072, 12); + let whole = a.seeds as usize * 8; + let ca = publish(&mut s, &a, 1).unwrap(); + let cb = publish(&mut s, &b, 1).unwrap(); + run_on_gpu(&a, 10); + run_on_gpu(&b, 10); + assert!(retire(&mut s, &a, &ca, 1)); + s.restart_compute_uma(); + assert!(!s.compute_uma_held()); + assert_eq!(s.stats.uma_invalidations, 1); + let w = writes(&a.pool_state); + let ca2 = publish(&mut s, &a, 1).unwrap(); + assert_ne!(ca2.uma_rec, ca.uma_rec); + assert_rebuilt(&a, ca2.uma_rec as usize, 1); + assert_eq!(writes(&a.pool_state) - w, whole); + assert_seeded(&a); + // B's command was in flight: it waits for it, then reseeds as well. + assert_eq!(s.bind_compute_uma(&b).unwrap(), None); + assert!(retire(&mut s, &b, &cb, 1)); + let w = writes(&b.pool_state); + let cb2 = publish(&mut s, &b, 1).unwrap(); + assert_eq!(writes(&b.pool_state) - w, whole); + assert_eq!(s.stats.uma_reseeds, 2); + // An idle rebuild after it trusts the new seed. + run_on_gpu(&a, 10); + assert!(retire(&mut s, &a, &ca2, 1)); + assert!(retire(&mut s, &b, &cb2, 1)); + s.invalidate_compute_uma(); + let w = (writes(&a.pool_state), writes(&b.pool_state)); + publish(&mut s, &a, 1).unwrap(); + publish(&mut s, &b, 1).unwrap(); + assert_eq!((writes(&a.pool_state), writes(&b.pool_state)), w); + assert_eq!((s.stats.uma_rebuilds, s.stats.uma_reseeds), (6, 2)); + } + + // A shared command that failed with a full receipt (`Slots::mark_dirty`) or was aborted + // (`Slots::quarantine`): no rebuild after it trusts a seed. The aborted manager stays + // with its quarantined slot; the other managers reseed. + #[test] + fn failed_or_aborted_shared_command_forces_a_reseed() { + let mut s = Slots::new().unwrap(); + let (a, _va, _ba, _la) = new_uma(3081, 13); + let (b, _vb, _bb, _lb) = new_uma(3082, 14); + let whole = a.seeds as usize * 8; + let cb = publish(&mut s, &b, 1).unwrap(); + assert!(retire(&mut s, &b, &cb, 1)); + let ca = publish(&mut s, &a, 1).unwrap(); + assert!(retire(&mut s, &a, &ca, 1)); + s.mark_dirty(&ca); + s.invalidate_compute_uma(); + let w = (writes(&a.pool_state), writes(&b.pool_state)); + let ca2 = publish(&mut s, &a, 1).unwrap(); + let cb2 = publish(&mut s, &b, 1).unwrap(); + assert_eq!((writes(&a.pool_state) - w.0, writes(&b.pool_state) - w.1), (whole, whole)); + assert_eq!(s.stats.uma_reseeds, 2); + assert!(retire(&mut s, &b, &cb2, 1)); + // A's next command is aborted. + let mut aborted = ca2; + s.quarantine(&mut aborted); + s.invalidate_compute_uma(); + assert_eq!(s.bind_compute_uma(&a).unwrap(), None, "the aborted manager never rebuilds"); + let w = writes(&b.pool_state); + let cb3 = publish(&mut s, &b, 1).unwrap(); + assert_eq!(writes(&b.pool_state) - w, whole); + assert_eq!(s.stats.uma_reseeds, 3); + assert!(retire(&mut s, &b, &cb3, 1)); + // A failed command that named no shared manager distrusts nothing. + s.mark_dirty(&Claims::new()); + s.invalidate_compute_uma(); + let w = writes(&b.pool_state); + publish(&mut s, &b, 1).unwrap(); + assert_eq!(writes(&b.pool_state), w); + assert_eq!(s.stats.uma_reseeds, 3); } #[test] From 421240d70a4adc382be29c6ba8aceab1a8d90e57 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 11:32:21 -0500 Subject: [PATCH 6/7] drm/asahi: g16: fail compute in a quarantined UMA slot before waiting A recovery quarantines an aborted flight instead of retiring it, so its commands stay counted in the compute UMA ledger of its slot for good: uma_shared_flights, uma_private_flights and the manager's outstanding count. prefix_compute waits on those counts before publish_prefix_body checks the slot quarantine. An SCS command in a slot where a shared flight was aborted, and a shared manager rebuilding in a slot where a private flight was aborted, both returned EAGAIN forever. With nothing else in flight the publication deadline then expired with ETIMEDOUT and the whole GPU fail-stopped, where the job alone used to fail with EIO. Check the quarantine with the other admission checks at the top of publish_prefix_body, before any wait. A job's UMA mask is fixed when it is prepared and nothing in between changes the quarantine, so a job in a healthy slot takes the same path as before. The host tests run those admission checks over the real slot ledger after a shared and after a private flight is aborted in a slot. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/engine.rs | 12 +- drivers/gpu/drm/asahi/g16/slots.rs | 5 +- .../drivers/gpu/asahi-m4/test-publication.py | 1 - .../drivers/gpu/asahi-m4/test-resources.py | 140 ++++++++++++++++++ 4 files changed, 152 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 940a2efc9bf14..2c3bde33f7dae 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2690,6 +2690,15 @@ impl Firmware { } { return Err(EIO); } + // An aborted flight never retires, so its commands stay counted in the compute UMA + // ledger of its quarantined slot, and the waits on that ledger in `prefix_compute` + // would never end. Fail before any of them. + if !render { + let uma_mask = job.resources.compute_uma_mask(); + if self.slots.compute_uma_quarantined(uma_mask) { + return Err(EIO); + } + } let channels: &[Channel] = if render { &[Channel::Fs, Channel::Ta] } else { @@ -3322,9 +3331,6 @@ impl Firmware { if self.recovery_pending()? { return Err(EAGAIN); } - if !render && self.slots.compute_uma_quarantined(f.compute_uma_mask) { - return Err(EIO); - } if render { f.pb.as_ref() .ok_or(EINVAL)? diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index b8df48db002c3..08105f0d8f576 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -2093,8 +2093,9 @@ impl Slots { /// whether that drained the manager, so its counter has to drop from the in-flight hold to /// its submission count. The manager stays bound, with its cursors in the hardware, until /// another record or descriptor takes the slot. Aborted flights never come here: their slot - /// stays quarantined with the manager, outside this accounting, and no shared or private - /// command publishes in a quarantined slot again. + /// stays quarantined with the manager and their commands stay counted for good, so + /// `publish_prefix_body` fails a job naming a quarantined slot before it waits on these + /// counts, and no shared or private command publishes there again. pub(crate) fn retire_compute_uma( &mut self, f: &Claims, 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 e96984e9c184c..c92a38944495d 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -3137,7 +3137,6 @@ def item(declaration): fn pick_pass_in_for(&self, _r: &Resources, _g: &Geometry, picked: u64, _vm: Option) -> Option { (0..48).find(|k| (self.pass_busy | picked) & (1u64 << k) == 0) } - fn compute_uma_quarantined(&self, _mask: u32) -> bool { unreachable!("render-only fixture") } fn verify_held(&self, _c: &Claims) -> Result { Ok(()) } fn publish(&mut self, _c: &mut Claims) -> Result { if self.publish_fails { Err(EIO) } else { Ok(()) } } } 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 de66c2c277195..200f845cf0a1d 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -352,6 +352,7 @@ def module(text, name): pub fn shared_compute_uma(&self)->Option<&crate::sync::Arc>{ self.shared_uma.as_ref() } + __COMPUTE_UMA_MASK__ pub fn compute_uma_slot_for(&self,k:usize)->Option{ if let Some(u)=&self.shared_uma { Some(u.uma_slot_idx) @@ -4003,6 +4004,127 @@ def module(text, name): assert_rebuilt(&c, fc.uma_rec as usize, 1); } + // The admission checks at the top of engine.rs `publish_prefix_body`, verbatim, over the + // real slot ledger: what a job meets before `prefix_compute` waits on that ledger. + struct GateStatus(u32); + impl GateStatus { + fn get(&self) -> u32 { + self.0 + } + } + struct GateVm { + status: GateStatus, + } + struct GateJob<'a> { + vm: GateVm, + resources: &'a g16::resources::Prepared, + } + struct GatePools; + impl GatePools { + fn exhausted(&self) -> bool { + false + } + } + struct Gate<'a> { + slots: &'a Slots, + pools: GatePools, + } + impl Gate<'_> { + fn admit(&self, job: &GateJob<'_>, render: bool) -> Result { + __PREFIX_ADMISSION__ + Ok(()) + } + } + fn admit(s: &Slots, resources: &g16::resources::Prepared, render: bool) -> Result { + let job = GateJob { vm: GateVm { status: GateStatus(0) }, resources }; + Gate { slots: s, pools: GatePools }.admit(&job, render) + } + fn scs_arena(o: &mut Objects, units: [usize; 2]) -> g16::resources::ComputeArena { + use g16::resources::ComputeArena; + let mut compute = KVec::new(); + for k in units { + let cmds = g16::object::test_unit_cmds(k as u64); + compute.push(g16::slots::ComputeSlot::new(o, &g16::object::Factory, k as u64, &cmds).unwrap(), 0).unwrap(); + } + ComputeArena { compute, render: None, hw_slots: Some(units), shared_uma: None } + } + + // A recovery aborts a flight with a shared command in UMA slot 0 on compute unit 6 (poll.rs + // quarantines its claims; it never retires). Its command stays counted in slot 0 for + // good, so an SCS command there and a rebuild of the manager would each wait forever. + // Both fail with EIO before they wait; other slots and render work are admitted. + #[test] + fn aborted_shared_flight_fails_later_compute_in_its_slot() { + use g16::hw::sizes::{COMPUTE_UNITS, PIPE1_COMPUTE_START}; + use g16::resources::ComputeArena; + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + let (a, va, _ba, _la) = new_uma(3051, 0); + let mut units = KVec::new(); + for k in 0..COMPUTE_UNITS { + let cmds = g16::object::test_unit_cmds(k as u64); + units.push(g16::slots::ComputeSlot::new_shared_in(&mut o, k as u64, &cmds).unwrap(), 0).unwrap(); + } + let prep_a = ComputeArena { compute: units, render: None, hw_slots: None, shared_uma: Some(a.clone()) }; + let scs01 = scs_arena(&mut o, [0, 1]); + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep_a, &mut c, Some(va.id), 1).unwrap().unwrap(); + assert!(k >= PIPE1_COMPUTE_START); + s.hold_compute_slot(k, &va, &prep_a).unwrap(); + s.publish(&mut c).unwrap(); + let cu = publish(&mut s, &a, 1).unwrap(); + c.uma_rec = cu.uma_rec; + c.uma_slot = cu.uma_slot; + assert_eq!(admit(&s, &prep_a, false), Ok(())); + assert_eq!(admit(&s, &scs01, false), Ok(())); + s.quarantine(&mut c); + s.invalidate_compute_uma(); + assert!(s.compute_uma_quarantined(1u32 << 0)); + assert!(!s.compute_exhausted_in_mask(0b11), "units 0 and 1 stay claimable"); + assert_eq!(a.outstanding(), 1, "the aborted command stays counted"); + assert!(!s.compute_uma_private_ready(0), "an SCS command in slot 0 would wait for good"); + assert_eq!(s.bind_compute_uma(&a).unwrap(), None, "a rebuild of A would wait for good"); + assert_eq!(admit(&s, &scs01, false), Err(EIO)); + assert_eq!(admit(&s, &prep_a, false), Err(EIO), "A's jobs prepared for slot 0"); + // Unchanged elsewhere: another VM's manager in slot 2, SCS units 2 and 3, render. + let (b, _vb, _bb, _lb) = new_uma(3052, 2); + let prep_b = ComputeArena { compute: KVec::new(), render: None, hw_slots: None, shared_uma: Some(b.clone()) }; + assert_eq!(admit(&s, &prep_b, false), Ok(())); + assert!(publish(&mut s, &b, 1).is_some()); + assert_eq!(admit(&s, &scs_arena(&mut o, [2, 3]), false), Ok(())); + assert_eq!(admit(&s, &prep_a, true), Ok(())); + } + + // The same with an aborted SCS command in slot 4: a shared manager whose jobs were + // prepared for slot 4 before the abort would wait for good to rebuild there. + #[test] + fn aborted_private_flight_fails_later_shared_jobs_in_its_slot() { + use g16::resources::ComputeArena; + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + let (b, _vb, _bb, _lb) = new_uma(3061, 4); + let prep_b = ComputeArena { compute: KVec::new(), render: None, hw_slots: None, shared_uma: Some(b.clone()) }; + let cb = publish(&mut s, &b, 1).unwrap(); + assert!(retire(&mut s, &b, &cb, 1)); + let scs = scs_arena(&mut o, [4, 5]); + let v = vm(3062); + let mut c = Claims::new(); + let k = s.claim_compute_for(&scs, &mut c, Some(v.id)).unwrap().unwrap(); + assert_eq!(k, 4); + s.hold_compute_slot(k, &v, &scs).unwrap(); + s.publish(&mut c).unwrap(); + c.uma_private = 1u32 << 4; + s.note_private_uma_published(&c); + assert_eq!(admit(&s, &prep_b, false), Ok(())); + s.quarantine(&mut c); + s.invalidate_compute_uma(); + assert!(s.compute_uma_quarantined(1u32 << 4)); + assert_eq!(s.bind_compute_uma(&b).unwrap(), None, "a rebuild of B would wait for good"); + assert_eq!(admit(&s, &prep_b, false), Err(EIO)); + assert_eq!(admit(&s, &scs, false), Err(EIO)); + assert_eq!(admit(&s, &scs_arena(&mut o, [2, 3]), false), Ok(())); + } + #[test] fn closed_vms_release_admission_after_retirement() { use g16::hw::sizes::COMPUTE_UNITS; @@ -4134,6 +4256,24 @@ def module(text, name): assert 'seq: s.seq.va,' in prefix_compute_fn, 'prefix_compute must point ComputeRefs::seq at firmware-cached s.seq' assert 's.seq.write(0, q)?;' in prefix_compute_fn, 'prefix_compute must write encoded sequence into s.seq' assert '&w[work::compute::BODY_ACTIVE_START..work::compute::SEQ_EMBEDDED]' in prefix_compute_fn, 'clean compute reuse must skip embedded sequence copy into WC work' +# A job naming a quarantined compute UMA slot fails before any wait on that slot's ledger, where +# an aborted flight's commands stay counted for good (`uma_residency` runs these checks). +assert 'self.slots.bind_compute_uma(' in prefix_compute_fn +assert 'self.slots.compute_uma_private_ready(' in prefix_compute_fn +publish_prefix_body_fn = item(engine_source, 'fn publish_prefix_body(') +admission_start = publish_prefix_body_fn.index(' if job.vm.status.get() != 0 {') +admission_end = publish_prefix_body_fn.index(' let channels: &[Channel] = if render {') +prefix_admission = publish_prefix_body_fn[admission_start:admission_end] +assert 'let uma_mask = job.resources.compute_uma_mask();' in prefix_admission +assert 'self.slots.compute_uma_quarantined(uma_mask)' in prefix_admission +assert publish_prefix_body_fn.count('compute_uma_quarantined(') == 1 +for wait in ('self.wait_compute_stamps_for(', 'self.choose_compute_pipe(', 'self.prefix_compute('): + assert admission_end < publish_prefix_body_fn.index(wait), wait + ' must follow the quarantine check' +compute_uma_mask_fn = item(resources_source, 'pub(crate) fn compute_uma_mask(') +assert compute_uma_mask_fn.count('self.compute_uma') == 1, compute_uma_mask_fn +source = (source + .replace('__PREFIX_ADMISSION__', prefix_admission) + .replace('__COMPUTE_UMA_MASK__', compute_uma_mask_fn.replace('self.compute_uma', 'self.shared_uma'))) graphs_finish_fn = item(graph_source, 'pub(crate) fn finish(') assert 'core::mem::ManuallyDrop::new(factory.persistent_objects_probe())' in graphs_finish_fn, 'Graphs::finish must keep probe-time FwCoherent ring allocator in ManuallyDrop' assert 'ring_objects.finish_private()?;' in graphs_finish_fn, 'Graphs::finish must publish persistent ring mappings' From e8a8a9bcb43f3865b3897c0bc48f0accb24d9668 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Wed, 2 Dec 2026 20:26:01 -0500 Subject: [PATCH 7/7] selftests: asahi-m4: pin the UMA hold and the restart after sleep and recovery Dropping the in-flight hold at publication, or the freelist distrust in sleep_restart() or recover(), left every case passing. Check the three call sites and their order. Signed-off-by: DjDeveloperr --- .../drivers/gpu/asahi-m4/test-publication.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) 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 dfee91b08e327..2f61eb12e9196 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -178,6 +178,20 @@ def item(declaration): ), 'the final boot control must follow the power policy the idle check reads' note_gpu_idle_fn = item('fn note_gpu_idle_if_any(') assert 'self.session.idle_power_off()' in note_gpu_idle_fn, note_gpu_idle_fn +# A shared manager runs under the in-flight hold, and no seeded freelist is trusted past a firmware +# restart or a recovery: both callers come before the firmware can run work again. +assert publish_prefix_body_fn.count('shared.counter.w64(0, tail_sub.saturating_add(1))?;') == 1 +sleep_restart_fn = item_in((production.parent / 'sleep.rs').read_text(), 'fn sleep_restart(') +assert ( + sleep_restart_fn.index('self.slots.restart_compute_uma();') + < sleep_restart_fn.index('self.session.rtkit.warm_restart()?;') +), sleep_restart_fn +recover_fn = item_in((production.parent / 'recovery.rs').read_text(), 'fn recover(') +assert ( + recover_fn.index('RecoveryAction::MarkAndAcknowledge => {') + < recover_fn.index('self.slots.restart_compute_uma();') + < recover_fn.index('self.firmware_w32(self.init.firmware_data().phase, 2)?;') +), recover_fn harness = r'''