diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index 8debfbc5ea1e9..d90e8213ea5da 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -536,6 +536,13 @@ impl Session { read(&self.regs).map(Some) } + /// Whether the boot power policy sent in [`run`] 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.adt.layout.powered.is_some() + } + /// 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) @@ -905,8 +912,9 @@ fn run( } regs::wmb(); let mut policy = DevCtl::op(devctl.start); - if session.adt.layout.powered.is_some() { + if session.idle_power_off() { // Let the firmware manage idle at the normal boot policy boundary (Globals +0x30 = 1). + // Held compute UMA managers follow the same policy (`Firmware::note_gpu_idle_if_any`). policy.words[1] = 1; } channel::devctl_submit(session, channels, events, init, &policy, true)?; 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 90c3f360c2411..9021a4be96da3 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -593,6 +593,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, /// Render prefixes published per render pair, and those published while another VM's /// renders were in flight on another pair (`render_pairs:` in `aurora-g16/stats`). pub(crate) render_pair_publications: [u64; sizes::RENDER_PAIRS], @@ -1192,6 +1195,9 @@ impl Firmware { self.engine.handoff_avoid_pipes = 0; self.engine.handoff_avoid_pairs = 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() @@ -2264,6 +2270,31 @@ impl Firmware { Ok(waits) } + /// 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. + /// + /// 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.session.idle_power_off() + || !self.engine.flights.is_empty() + || !self.slots.compute_uma_held() + { + return; + } + 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 /// CDM fanout rather than 1-pipe affinity and horizon folding: /// - per-queue retired CDM GPU duration EWMA `>= COMPUTE_HEAVY_EMA_US`, or @@ -2827,6 +2858,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 { @@ -3475,9 +3515,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)? @@ -3522,7 +3559,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 { @@ -3601,6 +3646,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. @@ -3736,12 +3786,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)?, @@ -3750,6 +3817,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, @@ -3822,21 +3896,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 e42c97150c9b2..831a334aca06e 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -502,6 +502,15 @@ impl Factory { pub(crate) fn pb_record_pool(&self) -> &Arc { &self.pb_record_pool } + + /// 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 ce210b9b7b382..a499ea5e5a849 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1352,16 +1352,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; @@ -1663,7 +1657,36 @@ 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)); + for j2 in f.group.iter() { + self.retain(j2); + complete(done, j2, 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); @@ -2361,6 +2384,11 @@ 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 {} idle_invalidations {}", + slots.uma_rebuilds, slots.uma_invalidations, s.uma_idle_invalidations + )?; writeln!( f, "recovery_receipts: affected_full {} aborted {}", diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 6d5f7384b1786..9623f5ec95f48 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -605,6 +605,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 1738847a7dd4f..7dca65f2abbff 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 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. +/// 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. +/// +/// 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(), @@ -870,6 +931,59 @@ impl Drop for PbRecordLease { } } +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); @@ -2606,30 +2720,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 3ed752c0e7806..57ddfa38cd92a 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -88,8 +88,10 @@ impl Firmware { /// The run bit and the RTKit handshake, with the firmware's state as it was left. `held`: /// the stop masked the mailbox's receive interrupt, which comes back with the receive path. fn sleep_restart(&mut self, held: bool) -> 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()?; if held { // SAFETY: The RTKit handle lasts until reboot; the stop masked the interrupt once. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 76cbb8f5057cd..cd8cbb72a9813 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], @@ -734,6 +767,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 { @@ -749,6 +788,9 @@ impl Claims { ct_count: 0, rotating: true, scrub_gen: 0, + uma_rec: NO_UMA_RECORD, + uma_slot: 0, + uma_private: 0, } } } @@ -779,6 +821,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`]). @@ -791,10 +837,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 @@ -1089,6 +1149,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], @@ -1938,6 +2004,150 @@ 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)?; + self.stats.uma_rebuilds = self.stats.uma_rebuilds.saturating_add(1); + 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 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, + 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; + 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 + /// 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 14c35dfde86f2..abb524b499e19 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 5464950cbc937..dfee91b08e327 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -166,6 +166,20 @@ 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 final boot control (`run` in boot.rs) and the compute UMA idle check read one GPU power +# policy, 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('.words[1] = ') == 1, boot_run_fn +assert ( + boot_run_fn.index('if session.idle_power_off() {') + < boot_run_fn.index('policy.words[1] = 1;') + < boot_run_fn.index('wait_boot_control(session, channels, events, init, base + 2') +), '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 + + harness = r''' #![allow(dead_code, unused_variables)] #[path = "__USAGE__"] @@ -218,7 +232,7 @@ 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,render_pair: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,render_pair:0,rt_compute:false,compute_uma_mask:0,doomed:false,recovery_suspect:false,initbm:false}}} @@ -254,8 +268,16 @@ 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`): 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)} + 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} @@ -348,6 +370,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);} @@ -362,6 +385,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(){ @@ -1368,6 +1392,85 @@ def item(declaration): assert_eq!(r2r, WaitTarget { stamp: 0x900, initbm: true, pair: 0 }); assert_eq!(cross_engine_barrier_type(r2r.initbm, false), BarrierType::Hold); } + 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(()))); + fw.stages.push_back(Stage{result:Ok(()),visible:true}); + fw.publish_checked(done).unwrap(); + fw.engine.flights.clear(); + } + #[test]fn uma_held_managers_stay_bound_while_the_boot_policy_holds_power(){ + let mut done=vec![]; + // The firmware holds the GPU powered: idle passes with a manager held invalidate nothing. + uma_set(false,true); + let mut fw=firmware(vec![],vec![]); + 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_idle_pass_invalidates_before_posting_when_the_gpu_may_power_off(){ + let mut done=vec![]; + // 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![]); + 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(); + idle_pass(&mut fw,4,&mut done); + assert_eq!(uma_seen(),(1,false)); + } + #[test]fn uma_no_idle_invalidation_without_a_held_shared_manager(){ + let mut done=vec![]; + // 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![]); + 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)]); let mut done=vec![]; @@ -3089,7 +3192,6 @@ def item(declaration): } struct Slots; impl Slots { - 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 { Ok(()) } } @@ -3251,6 +3353,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 5fd0cdcfc25f4..2fa058087769e 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -208,6 +208,17 @@ def module(text, name): p.get_or_insert_with(||super::resources::PbRecordPool::new().unwrap()).clone() }) } + // 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())};} @@ -244,6 +255,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 static ACTIVE_CLIENT_MAPS:std::cell::RefCell>=const{std::cell::RefCell::new(Vec::new())}; pub static ON_OBJECTS_DROP:std::cell::RefCell>>=const{std::cell::RefCell::new(None)}; pub static FAIL_CLIENT_MAP:std::cell::Cell=const{std::cell::Cell::new(false)}; @@ -363,6 +375,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)); @@ -440,6 +461,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) @@ -4182,17 +4204,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() { @@ -4236,6 +4261,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] @@ -4463,6 +4518,427 @@ 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"); + 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)); + 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); + 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] + 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); + } + + // 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; + 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() @@ -4558,6 +5034,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 'Class::FwCoherent' in graphs_finish_fn and 'sched_ctx::SIZE' in graphs_finish_fn, 'Graphs::finish must allocate shared sched_ctx as FwCoherent' @@ -4572,12 +5066,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 {') @@ -4667,7 +5165,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 = ( @@ -4709,6 +5211,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 8de97b3b39744..471b7ca815b5d 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); @@ -43,7 +42,6 @@ def function(text, name): } #[derive(Clone,Copy)]enum Channel{Compute,Ta,Fs} 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],user_stamp:[Object;2],notifier:Object} // Production service-stamp accessors (graph.rs) over the mock objects: retirement reads the cells @@ -54,7 +52,7 @@ def function(text, name): impl RGraph{__TA_SERVICE_STAMP__ __FS_SERVICE_STAMP__} struct Graph{compute:[CGraph;hw::sizes::COMPUTE_PIPES],render:[RGraph;hw::sizes::RENDER_PAIRS]} 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)} @@ -63,7 +61,6 @@ def function(text, name): fn render_pass(&self,k:usize)->Result<&RUnit>{self.passes.get(k).ok_or(EINVAL)} fn pb_flight_retired(&self,k:usize,target:u64,renders:u32,idle:bool)->Result{self.pools.flight_retired(k,target,renders,idle)} 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,render_pair:u8,render_chan_settled:[bool;2],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} @@ -880,52 +877,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'),('__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'),('__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) graph_text=(backend/'graph.rs').read_text() cell_start=graph_text.index('/// A 32-bit stamp cell')