From ee819069751450dad2f9a9903e214f7af74a0a26 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 18:00:17 -0500 Subject: [PATCH 1/7] drm/asahi: g16: widen compute units to 64, pipes to 16, and flights to 64 With non-SCS compute VMs sharing one UMA descriptor, pool, and hardware UMA slot across all units, each extension compute unit only backs 288 KiB of preempt, auxiliary, and context-store state. Previously, COMPUTE_UNITS=24, COMPUTE_PIPES=8, and a 32-flight compute cap forced 16 concurrent compute processes to share 8 pipes and contend over only 16 reusable units, and capped deep d=32/d=64 single-queue streams at 23 commands in flight. Widen COMPUTE_UNITS to 64, COMPUTE_PIPES to 16 (events 15..=30 in type-1 event word 1), and FLIGHTS to 64, and derive params::compute_flights() from COMPUTE_UNITS and FLIGHTS: - Compact extension compute unit records (k >= 2) into 1 MiB intervals at EXT_COMPUTE_REC_BASE (0x70b4000000..0x70b7e00000), keeping 26 disjoint 33 MiB SharedComputeUma migration windows below it and base units 0..2 unchanged. - Widen compute unit bitmasks (quarantined_compute_mask, compute_slot_mask, Lifetime masks) from u32 to u64 while keeping SCS slot selection bounded by COMPUTE_UMA_SLOTS (32). - Update host selftests to validate 64 compute units, 16 compute pipes, 26 UMA migration windows, and 64-bit unit masks. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/engine.rs | 14 ++-- drivers/gpu/drm/asahi/g16/fw/work/compute.rs | 4 +- drivers/gpu/drm/asahi/g16/hw.rs | 75 ++++++++++++------- drivers/gpu/drm/asahi/g16/mod.rs | 4 +- drivers/gpu/drm/asahi/g16/params.rs | 8 +- drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 12 +-- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 2 +- drivers/gpu/drm/asahi/g16/resources.rs | 25 ++++--- drivers/gpu/drm/asahi/g16/slots.rs | 52 ++++++------- .../drivers/gpu/asahi-m4/test-poll-retire.py | 4 +- .../gpu/asahi-m4/test-progress-wrap.py | 2 +- .../drivers/gpu/asahi-m4/test-publication.py | 66 ++++++++-------- .../drivers/gpu/asahi-m4/test-resources.py | 39 +++++++--- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 2 +- 14 files changed, 172 insertions(+), 137 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 5609e41b03e5a..031e5f381408f 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -481,7 +481,7 @@ impl HoldCause { } /// Engine statistics, printed by `aurora-g16/stats`. -#[derive(Default, Zeroable)] +#[derive(Zeroable)] pub(crate) struct Stats { pub(crate) pub_ns: u64, pub(crate) idle_from_ns: u64, @@ -541,7 +541,7 @@ pub(crate) struct Stats { /// Host-side phase timers of publication and polling, on with `debug_flags` bit 49 /// (`Debug1`); printed as the `prof:` line of `aurora-g16/stats`. A measurement aid: nothing is /// timed while the flag is off. -#[derive(Default, Zeroable)] +#[derive(Zeroable)] pub(crate) struct Prof { /// Published prefixes timed. pub(crate) prefixes: u64, @@ -2321,7 +2321,7 @@ impl Firmware { let allowed = if p == 0 { slot_mask } else { - slot_mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + slot_mask & !((1u64 << sizes::PIPE1_COMPUTE_START) - 1) }; if allowed == 0 || self.slots.compute_exhausted_in_mask(allowed) { continue; @@ -2339,7 +2339,7 @@ impl Firmware { fn has_compute_pipe_for_vm( &self, vm: &Arc, - slot_mask: u32, + slot_mask: u64, rt_compute: bool, ) -> bool { let avoid = self.engine.handoff_avoid_pipes; @@ -2383,7 +2383,7 @@ impl Firmware { &self, vm: &Arc, pipe: usize, - slot_mask: u32, + slot_mask: u64, ) -> Option { let mut active_same = [0usize; sizes::COMPUTE_PIPES]; let mut active_other = [false; sizes::COMPUTE_PIPES]; @@ -2436,7 +2436,7 @@ impl Firmware { queue: &Arc, vm: &Arc, waits: [Option; sizes::COMPUTE_PIPES], - slot_mask: u32, + slot_mask: u64, rt_compute: bool, heavy_compute: bool, ) -> Option { @@ -2563,7 +2563,7 @@ impl Firmware { } None }; - let has_secondary = (slot_mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1)) != 0; + let has_secondary = (slot_mask & !((1u64 << sizes::PIPE1_COMPUTE_START) - 1)) != 0; let prefer_secondary = has_secondary && active_other.iter().any(|&a| a); if vm_active_pipes < sizes::MAX_VM_COMPUTE_PIPES { if let Some(p) = pick_idle(prefer_secondary) { diff --git a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs index 33b0f56a07045..d5257eb0010f5 100644 --- a/drivers/gpu/drm/asahi/g16/fw/work/compute.rs +++ b/drivers/gpu/drm/asahi/g16/fw/work/compute.rs @@ -45,7 +45,9 @@ pub(crate) const START_SCS: usize = 0x40; pub(crate) const EVENT: u32 = 15; /// Firmware completion events for concurrent compute pipes `0..COMPUTE_PIPES`. /// All events reside in type-1 event word 1 (`15..32`) so event draining reads only words 1 and 4. -pub(crate) const EVENTS: [u32; 8] = [EVENT, 16, 17, 18, 19, 20, 21, 22]; +pub(crate) const EVENTS: [u32; 16] = [ + EVENT, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, +]; /// Resolves a firmware compute completion event back to its compute pipe index (`0..EVENTS.len()`). pub(crate) const fn pipe_of_event(event: u32) -> Option { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 44225bfb62c0d..3bfce1673a9d2 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -937,12 +937,14 @@ pub(crate) mod client { // pack at a 40 MiB stride from 0x7080000000 up to the SCS compute records (0x70b8000000), // clear of [`DYNAMIC`] and [`SCS_POOLS`] and leaving 7.25 MiB guard above each unit's // 32.75 MiB footprint (`0x20c0000`). Every alias is inside Mesa's reserved hole. - pub(crate) const EXT_COMPUTE_STRIDE: u64 = 0x02800000; + pub(crate) const EXT_COMPUTE_POOL_STRIDE: u64 = 0x02100000; + pub(crate) const EXT_COMPUTE_REC_BASE: u64 = 0x70b4000000; + pub(crate) const EXT_COMPUTE_REC_STRIDE: u64 = 0x00100000; pub(crate) const fn compute_base(k: u64) -> u64 { if k < 2 { 0x7001000000 + k * 0x04000000 } else { - 0x7080000000 + (k - 2) * EXT_COMPUTE_STRIDE + 0x7080000000 + (k - 2) * EXT_COMPUTE_POOL_STRIDE } } pub(crate) const fn compute_pool(k: u64) -> u64 { @@ -955,13 +957,25 @@ pub(crate) mod client { compute_base(k) + 0x2020000 } pub(crate) const fn compute_preempt(k: u64) -> u64 { - compute_base(k) + 0x2030000 + if k < 2 { + compute_base(k) + 0x2030000 + } else { + EXT_COMPUTE_REC_BASE + (k - 2) * EXT_COMPUTE_REC_STRIDE + } } pub(crate) const fn compute_aux(k: u64) -> u64 { - compute_base(k) + 0x2040000 + if k < 2 { + compute_base(k) + 0x2040000 + } else { + EXT_COMPUTE_REC_BASE + (k - 2) * EXT_COMPUTE_REC_STRIDE + 0x10000 + } } pub(crate) const fn compute_context(k: u64) -> u64 { - compute_base(k) + 0x2080000 + if k < 2 { + compute_base(k) + 0x2080000 + } else { + EXT_COMPUTE_REC_BASE + (k - 2) * EXT_COMPUTE_REC_STRIDE + 0x40000 + } } pub(crate) const WORK_PAGE: u64 = 0x7000100000; pub(crate) const WORK_OFF: u64 = 0; @@ -1110,9 +1124,9 @@ pub(crate) mod sizes { /// `notifier`, `threshold`, `job_list`) and completion event (`work::compute::EVENTS`) so /// concurrent compute VMs lease disjoint workqueues instead of mixing ASIDs in one active /// `qinfo`. Pipe 0 exclusively owns `0..PIPE1_COMPUTE_START` for base-only and SCS VMs; - /// secondary pipes `1..COMPUTE_PIPES` share `PIPE1_COMPUTE_START..COMPUTE_UNITS` (18 units - /// for 7 secondary pipes, leaving 11 active units beyond the 7 undisplaced retired leases). - pub(crate) const COMPUTE_PIPES: usize = 8; + /// secondary pipes `1..COMPUTE_PIPES` share `PIPE1_COMPUTE_START..COMPUTE_UNITS` (58 units + /// for 15 secondary pipes, leaving 43 active units beyond the 15 undisplaced retired leases). + pub(crate) const COMPUTE_PIPES: usize = 16; /// Maximum concurrent compute pipes one VM may occupy at once, preserving the render /// ring-entry bound (`MAX_RENDER_RING_ENTRIES = 5`) since cross-VM render/compute drains. pub(crate) const MAX_VM_COMPUTE_PIPES: usize = 2; @@ -1206,15 +1220,18 @@ pub(crate) mod sizes { pub(crate) const PB_GROW_STEP: u32 = 10; /// Published prefixes at most. Warm render commands may pipeline across VMs on disjoint /// hardware UMA slots, compute only behind its own VM's work, while cold `InitBM` renders - /// and recovery paths drain. - pub(crate) const FLIGHTS: usize = 32; - /// Retained compute units per VM at most; each unit owns its own hardware UMA slot - /// (`COMPUTE_UMA_SLOT + index`, fitting in `1..RENDER_UMA_SLOT = 33`). A unit is reused - /// only after a later publication retired (it displaced the unit), so `n` units keep up to - /// `n - 1` compute commands in flight (`23 * 2 = 46` entries of the 256-entry compute work - /// ring `QUEUE_CAP`, well inside `AHEAD_RECORDS = 128`, `RING_SLOTS = 256`, and recovery - /// `snapshot_entries = 448`). - pub(crate) const COMPUTE_UNITS: usize = 24; + /// and recovery paths drain. Bounded by channel ahead limit (`AHEAD_RECORDS = 128`). + pub(crate) const FLIGHTS: usize = 64; + /// Retained compute units per VM at most. Non-SCS compute VMs share one UMA descriptor, + /// pool, and hardware UMA slot (`1..=32`) across all units, so unit count is bounded by + /// the 26B123 compute work ring (`(COMPUTE_UNITS - 1) * MAX_COMPUTE_RING_ENTRIES < 256`, + /// `63 * 3 = 189 < 256`), the `u64` slot mask (`<= 64`), `SCHEDULER_CREDITS = 64`, and + /// recovery `snapshot_entries = 448`. With `COMPUTE_PIPES = 16` holding up to 16 + /// undisplaced retired owners, 64 units leave 48 reusable units (3 per VM at 16 processes). + pub(crate) const COMPUTE_UNITS: usize = 64; + /// Disjoint per-VM client VA windows for `SharedComputeUma` pool/freelist/list allocation + /// (2 base windows + 24 extension windows below `EXT_COMPUTE_REC_BASE`). + pub(crate) const COMPUTE_UMA_WINDOWS: usize = 26; /// Device-wide hardware compute UMA manager slots (`COMPUTE_UMA_SLOT..RENDER_UMA_SLOT`, /// slots `1..=32`). Non-SCS compute VMs share one UMA descriptor, pool, and hardware slot /// across all of their compute units and pipes so firmware skips UMA teardown and rebind @@ -1222,18 +1239,23 @@ pub(crate) mod sizes { pub(crate) const COMPUTE_UMA_SLOTS: usize = (super::engine::RENDER_UMA_SLOT - super::engine::COMPUTE_UMA_SLOT) as usize; const _: () = assert!(COMPUTE_UMA_SLOTS == 32); - const _: () = assert!(COMPUTE_UNITS >= 2); + const _: () = assert!(COMPUTE_UNITS >= 2 && COMPUTE_UNITS <= 64); const _: () = assert!((COMPUTE_UNITS - 1) * MAX_COMPUTE_RING_ENTRIES < QUEUE_CAP as usize); const _: () = assert!( - super::client::compute_context(2) + 0x40000 <= super::client::compute_base(3) + super::client::compute_list(2) + 0x4000 <= super::client::compute_base(3) + ); + const _: () = assert!( + super::client::compute_base(COMPUTE_UMA_WINDOWS as u64) + <= super::client::EXT_COMPUTE_REC_BASE ); const _: () = assert!( - super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP + super::client::compute_context(2) + 0x40000 <= super::client::compute_preempt(3) ); const _: () = assert!( - super::engine::COMPUTE_UMA_SLOT + (COMPUTE_UNITS as u32) - <= super::engine::RENDER_UMA_SLOT + super::client::compute_context(COMPUTE_UNITS as u64 - 1) + 0x40000 + <= super::client::scs_compute_records(0) ); + const _: () = assert!(SCS_COMPUTE_UNITS <= COMPUTE_UMA_SLOTS); /// SCS-capable compute units per VM, bound dynamically to healthy compute ledger indices /// (and UMA slots) preferring pipe-0-exclusive indices `0..PIPE1_COMPUTE_START`. pub(crate) const SCS_COMPUTE_UNITS: usize = 2; @@ -1248,11 +1270,10 @@ pub(crate) mod sizes { /// Bytes of a base UMA pool (its seeds of 4 KiB). pub(crate) const POOL_BYTES: u64 = 0x2000000; const _: () = assert!( - super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::scs_compute_records(0) - && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64 - 1) - + super::client::COMPUTE_CONTEXT_OFF - + 0x40000 - <= super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) + super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64 - 1) + + super::client::COMPUTE_CONTEXT_OFF + + 0x40000 + <= super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) && super::client::scs_compute_records(SCS_COMPUTE_UNITS as u64) <= super::client::PB_HEAP && super::client::WORK_PAGE diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index c01ee8c3915b6..aa60d8e7419b3 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -298,7 +298,7 @@ pub(crate) struct Shared { /// Whether any base compute unit (`0..BASE_COMPUTE_UNITS`) has been quarantined. pub(crate) base_compute_quarantined: AtomicBool, /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). - pub(crate) quarantined_compute_mask: AtomicU32, + pub(crate) quarantined_compute_mask: AtomicU64, /// Bitmask of permanently quarantined device-wide compute UMA slots (`0..COMPUTE_UMA_SLOTS`). pub(crate) quarantined_compute_uma_mask: AtomicU32, /// Round-robin cursor assigning each non-SCS compute VM a slot in `0..COMPUTE_UMA_SLOTS`. @@ -689,7 +689,7 @@ impl Gpu { sleeping: AtomicBool::new(false), recovering: AtomicBool::new(false), base_compute_quarantined: AtomicBool::new(false), - quarantined_compute_mask: AtomicU32::new(0), + quarantined_compute_mask: AtomicU64::new(0), quarantined_compute_uma_mask: AtomicU32::new(0), next_compute_uma_slot: AtomicU32::new(0), compute_uma_slot_users, diff --git a/drivers/gpu/drm/asahi/g16/params.rs b/drivers/gpu/drm/asahi/g16/params.rs index 869ab8bd1daa6..515505ff9e685 100644 --- a/drivers/gpu/drm/asahi/g16/params.rs +++ b/drivers/gpu/drm/asahi/g16/params.rs @@ -45,9 +45,13 @@ pub(crate) fn compute_units() -> usize { hw::sizes::COMPUTE_UNITS } -/// Compute commands in flight at most. +/// Compute commands in flight at most: bounded by retained compute units +/// (`COMPUTE_UNITS - 1`, leaving one unit for displacement) and `FLIGHTS`. pub(crate) fn compute_flights() -> usize { - 32usize.clamp(1, hw::sizes::FLIGHTS) + hw::sizes::COMPUTE_UNITS + .saturating_sub(1) + .min(hw::sizes::FLIGHTS) + .max(1) } /// Render commands in flight at most: bounded by both retained pass slots diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index d3cf6caf6084d..0d88f14c314e9 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -119,7 +119,7 @@ impl Lifetime { .any(|u| matches!(u.state, State::Preparing | State::Published)) } /// [`Self::exhausted`] restricted to owners selected by `mask` (bit `k` -> owner `k`). - pub(crate) fn exhausted_in_mask(&self, mask: u32) -> bool { + pub(crate) fn exhausted_in_mask(&self, mask: u64) -> bool { let mut rem = mask; while rem != 0 { let k = rem.trailing_zeros() as usize; @@ -133,12 +133,12 @@ impl Lifetime { .iter() .any(|u| matches!(u.state, State::Preparing | State::Published)) } - /// Bitmask of permanently quarantined owners in `0..N.min(32)`. - pub(crate) fn quarantined_mask(&self) -> u32 { - let mut mask = 0u32; - for k in 0..N.min(32) { + /// Bitmask of permanently quarantined owners in `0..N.min(64)`. + pub(crate) fn quarantined_mask(&self) -> u64 { + let mut mask = 0u64; + for k in 0..N.min(64) { if self.units[k].state == State::Quarantined { - mask |= 1u32 << k; + mask |= 1u64 << k; } } mask diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index a205d213bd221..5e0fb38bc0287 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -159,7 +159,7 @@ impl SnapshotEntry { /// Bounded per-stage history of recently retired firmware stamps. pub(crate) const RETIRED_STAMPS_CAP: usize = 64; /// Number of compute pipes tracked by [`RetiredStamps`] (matches `hw::sizes::COMPUTE_PIPES`). -pub(crate) const RETIRED_COMPUTE_PIPES: usize = 8; +pub(crate) const RETIRED_COMPUTE_PIPES: usize = 16; /// Total retired-stamp stages: compute pipes `0..RETIRED_COMPUTE_PIPES`, TA, FS. pub(crate) const RETIRED_STAGES: usize = RETIRED_COMPUTE_PIPES + 2; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index ffc660744bab8..98e60e102e6f0 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -198,7 +198,7 @@ impl SharedComputeUma { pool_va_idx: usize, ) -> Result> { if uma_slot_idx >= super::hw::sizes::COMPUTE_UMA_SLOTS - || pool_va_idx >= super::hw::sizes::COMPUTE_UNITS + || pool_va_idx >= super::hw::sizes::COMPUTE_UMA_WINDOWS { return Err(EIO); } @@ -492,7 +492,7 @@ pub(crate) struct PrepareHints<'a> { /// A base compute unit (`0..BASE_COMPUTE_UNITS`) is quarantined: allocate extension units. pub(crate) expand_compute_ext: bool, /// Bitmask of permanently quarantined device-wide compute units (`0..COMPUTE_UNITS`). - pub(crate) quarantined_compute_mask: u32, + pub(crate) quarantined_compute_mask: u64, /// Bitmask of permanently quarantined device-wide compute UMA slots (`0..COMPUTE_UMA_SLOTS`). pub(crate) quarantined_compute_uma_mask: u32, /// Round-robin cursor assigning a VM's shared compute UMA slot in `0..COMPUTE_UMA_SLOTS`. @@ -569,16 +569,17 @@ fn pick_compute_uma_slot( /// pipe-0-exclusive units (`0..PIPE1_COMPUTE_START`) are preferred before falling back to /// `PIPE1_COMPUTE_START..max_units`. fn pick_scs_compute_slots( - quarantined_mask: u32, + quarantined_mask: u64, max_units: usize, ) -> [usize; super::hw::sizes::SCS_COMPUTE_UNITS] { let limit = max_units .min(super::hw::sizes::COMPUTE_UNITS) + .min(super::hw::sizes::COMPUTE_UMA_SLOTS) .max(super::hw::sizes::SCS_COMPUTE_UNITS); let mut out = [0usize; super::hw::sizes::SCS_COMPUTE_UNITS]; let mut found = 0usize; for k in 0..limit { - if (quarantined_mask & (1u32 << k)) == 0 { + if (quarantined_mask & (1u64 << k)) == 0 { out[found] = k; found += 1; if found == out.len() { @@ -1363,7 +1364,7 @@ impl Cache { }); if needs_uma { let pool_va_idx = ready.compute_uma_va_idx; - if pool_va_idx >= super::hw::sizes::COMPUTE_UNITS { + if pool_va_idx >= super::hw::sizes::COMPUTE_UMA_WINDOWS { return Err(EIO); } let start = @@ -1795,20 +1796,20 @@ impl Prepared { Ok(self.compute()?.len() + self.compute_ext.as_deref().map_or(0, ComputeUnitSet::len)) } /// Hardware compute ledger bitmask (bit `k` -> unit `k`) this job can use. - pub(crate) fn compute_slot_mask(&self) -> Result { + pub(crate) fn compute_slot_mask(&self) -> Result { let base = self.compute()?; if let Some(slots) = base.hw_slots { - let mut mask = 0u32; + let mut mask = 0u64; for slot in slots { - mask |= 1u32 << slot; + mask |= 1u64 << slot; } return Ok(mask); } let total = self.compute_units()?.min(super::hw::sizes::COMPUTE_UNITS); - Ok(if total >= 32 { - u32::MAX + Ok(if total >= 64 { + u64::MAX } else { - (1u32 << total) - 1 + (1u64 << total) - 1 }) } /// The per-unit arena holding compute unit `k`. @@ -1854,7 +1855,7 @@ impl Prepared { if let Some(uma) = &self.compute_uma { 1u32 << uma.uma_slot_idx } else { - self.compute_slot_mask().unwrap_or(0) + self.compute_slot_mask().unwrap_or(0) as u32 } } /// Whether the VM's shared compute UMA descriptor has completed at least `count` additional diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index d87f49e009fc4..d3ccf6f7b1d4a 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -349,14 +349,13 @@ impl ComputeSlot { /// rebuilding per-unit arenas. pub(crate) fn new_shared_in(o: &mut Objects, k: u64, cmds: &UnitCmds) -> Result { let sh = Class::Shared; - let state = Placement::Base.state(k); Ok(Self { its: alloc(o, 16, sh, None, 0, false)?, preempt: alloc( o, 0x4000, sh, - Client::nc(state + client::COMPUTE_PREEMPT_OFF), + Client::nc(client::compute_preempt(k)), 0, false, )?, @@ -367,18 +366,11 @@ impl ComputeSlot { o, 0x40000, sh, - Client::nc(state + client::COMPUTE_CONTEXT_OFF), - 0, - false, - )?, - aux: alloc( - o, - 0x4000, - sh, - Client::nc(state + client::COMPUTE_AUX_OFF), + Client::nc(client::compute_context(k)), 0, false, )?, + aux: alloc(o, 0x4000, sh, Client::nc(client::compute_aux(k)), 0, false)?, private_uma: None, }) } @@ -1152,11 +1144,11 @@ impl Slots { self.compute.lifetime.exhausted_within(n) } /// Whether none of the compute units in `mask` (bit `k` -> unit `k`) can ever be claimed. - pub(crate) fn compute_exhausted_in_mask(&self, mask: u32) -> bool { + pub(crate) fn compute_exhausted_in_mask(&self, mask: u64) -> bool { self.compute.lifetime.exhausted_in_mask(mask) } /// Bitmask of permanently quarantined compute units (`0..COMPUTE_UNITS`). - pub(crate) fn quarantined_compute_mask(&self) -> u32 { + pub(crate) fn quarantined_compute_mask(&self) -> u64 { self.compute.lifetime.quarantined_mask() } pub(crate) fn render_exhausted(&self) -> bool { @@ -1187,7 +1179,7 @@ impl Slots { (0..n.min(sizes::COMPUTE_UNITS)).any(|k| self.compute.lifetime.available(k)) } /// Whether any compute unit in `mask` can be claimed now. - pub(crate) fn compute_available_in_mask(&self, mask: u32) -> bool { + pub(crate) fn compute_available_in_mask(&self, mask: u64) -> bool { let mut rem = mask; while rem != 0 { let k = rem.trailing_zeros() as usize; @@ -1202,11 +1194,11 @@ impl Slots { /// Pipe 0 may claim any bit in `mask`; secondary pipes stay in /// `PIPE1_COMPUTE_START..COMPUTE_UNITS` so `0..PIPE1_COMPUTE_START` only ever hold pipe-0 /// leases. - pub(crate) fn compute_available_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> bool { + pub(crate) fn compute_available_in_mask_for_pipe(&self, mask: u64, pipe: usize) -> bool { let allowed = if pipe == 0 { mask } else { - mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + mask & !((1u64 << sizes::PIPE1_COMPUTE_START) - 1) }; self.compute_available_in_mask(allowed) } @@ -1214,10 +1206,10 @@ impl Slots { #[allow(dead_code)] pub(crate) fn compute_available_for_pipe(&self, n: usize, pipe: usize) -> bool { let limit = n.min(sizes::COMPUTE_UNITS); - let mask = if limit >= 32 { - u32::MAX + let mask = if limit >= 64 { + u64::MAX } else { - (1u32 << limit) - 1 + (1u64 << limit) - 1 }; self.compute_available_in_mask_for_pipe(mask, pipe) } @@ -1428,11 +1420,11 @@ impl Slots { self.free_compute_in_for_pipe(n, 0) } /// Available compute units in `mask` eligible for `pipe`. - pub(crate) fn free_compute_in_mask_for_pipe(&self, mask: u32, pipe: usize) -> u32 { + pub(crate) fn free_compute_in_mask_for_pipe(&self, mask: u64, pipe: usize) -> u32 { let mut rem = if pipe == 0 { mask } else { - mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + mask & !((1u64 << sizes::PIPE1_COMPUTE_START) - 1) }; let mut count = 0u32; while rem != 0 { @@ -1448,10 +1440,10 @@ impl Slots { #[allow(dead_code)] pub(crate) fn free_compute_in_for_pipe(&self, n: usize, pipe: usize) -> u32 { let limit = n.min(sizes::COMPUTE_UNITS); - let mask = if limit >= 32 { - u32::MAX + let mask = if limit >= 64 { + u64::MAX } else { - (1u32 << limit) - 1 + (1u64 << limit) - 1 }; self.free_compute_in_mask_for_pipe(mask, pipe) } @@ -1527,18 +1519,18 @@ impl Slots { let allowed = if pipe == 0 { mask } else { - mask & !((1u32 << sizes::PIPE1_COMPUTE_START) - 1) + mask & !((1u64 << sizes::PIPE1_COMPUTE_START) - 1) }; if allowed == 0 { return Ok(None); } let n = sizes::COMPUTE_UNITS; let base_cursor = (self.cursor as usize) % n; - let p0_mask = (1u32 << sizes::PIPE1_COMPUTE_START) - 1; + let p0_mask = (1u64 << sizes::PIPE1_COMPUTE_START) - 1; // On pipe 0, prefer pipe-0-exclusive units (`0..PIPE1_COMPUTE_START`) before spilling // into secondary-pipe units (`PIPE1_COMPUTE_START..COMPUTE_UNITS`) so concurrent // secondary pipes keep maximum unit headroom. - let tiers: [u32; 2] = if pipe == 0 { + let tiers: [u64; 2] = if pipe == 0 { [allowed & p0_mask, allowed & !p0_mask] } else { [allowed, 0] @@ -1552,7 +1544,7 @@ impl Slots { } for i in 0..n { let k = (base_cursor + i) % n; - if (tier & (1u32 << k)) != 0 + if (tier & (1u64 << k)) != 0 && !self.compute.scrub_full[k] && self.compute.owner[k] .as_ref() @@ -1572,7 +1564,7 @@ impl Slots { } for i in 0..n { let k = (base_cursor + i) % n; - if (tier & (1u32 << k)) != 0 + if (tier & (1u64 << k)) != 0 && self.compute.owner[k].is_none() && self.compute.lifetime.claim(k) { @@ -1591,7 +1583,7 @@ impl Slots { } for i in 0..n { let k = (base_cursor + i) % n; - if (tier & (1u32 << k)) != 0 && self.compute.lifetime.claim(k) { + if (tier & (1u64 << k)) != 0 && self.compute.lifetime.claim(k) { chosen = Some(k); break 'any; } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index 227ba811a0bdc..be2d3c28dcd1d 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -68,7 +68,7 @@ def item(declaration, text=source): pub const TA_WAVE_PASSES: usize = 4; pub const TA_WAVE_PASSES_LIGHT: usize = 8; pub const TA_WAVE_REFILL_HEADROOM: usize = 2; - pub const COMPUTE_PIPES: usize = 8; + pub const COMPUTE_PIPES: usize = 16; pub const COALESCE_WINDOW_US: u32 = 18; } } @@ -1278,7 +1278,7 @@ def item(declaration, text=source): const STATE_WRITE: usize = 0x40; const RING_SLOTS: u32 = 128; const RECORD_WORDS: usize = 18; - const COMPUTE_PIPES: usize = 8; + const COMPUTE_PIPES: usize = 16; const STAGE_COUNT: usize = 2 + COMPUTE_PIPES; mod compute { pub const EVENT: u32 = 15; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index 19ebbe49508af..c3deb047a9b2f 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -18,7 +18,7 @@ def function(text,name): #[derive(Copy,Clone,Debug,PartialEq,Eq)]struct Error(i32); const EIO:Error=Error(5);const ETIMEDOUT:Error=Error(110); type Result=core::result::Result; -mod hw{pub mod sizes{pub const COMPUTE_PIPES:usize=8;}} +mod hw{pub mod sizes{pub const COMPUTE_PIPES:usize=16;}} mod command{pub const RENDER:usize=0;pub const COMPUTE:usize=1;} mod params{ pub fn recovery()->bool{true} 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 925dc0c683c70..e0490d21defc5 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -126,7 +126,7 @@ def item(declaration): } #[derive(Copy,Clone)]struct Resources{uma_mask:u32} #[allow(non_upper_case_globals)]const Resources:Resources=Resources{uma_mask:1}; -impl Resources{fn compute_units(&self)->Result{Ok(24)}fn compute_slot_mask(&self)->Result{Ok((1u32 << 24) - 1)}fn compute_uma_mask(&self)->u32{self.uma_mask}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} +impl Resources{fn compute_units(&self)->Result{Ok(64)}fn compute_slot_mask(&self)->Result{Ok(u64::MAX)}fn compute_uma_mask(&self)->u32{self.uma_mask}fn compute_scs(&self)->bool{false}fn render_passes(&self)->Result{Ok(8)}fn render_scs(&self)->bool{false}fn pb_slots(&self)->Result{Ok(2)}fn pb_slot_mask(&self)->Result<(u32,usize)>{Ok((0b11,0))}fn pb_heap_blocks(&self)->Result{Ok(512)}} struct Job { id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,dependency:Result,terminal_marked:AtomicBool,resources:Resources } impl Job { fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} @@ -166,7 +166,7 @@ def item(declaration): impl Slots{ 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} + fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted}fn compute_exhausted_in_mask(&self,_mask:u64)->bool{self.compute_exhausted} fn compute_uma_quarantined(&self,_mask:u32)->bool{false} fn render_exhausted_within(&self,_passes:usize)->bool{self.render_exhausted} fn release(&mut self,_claims:&mut Claims){self.releases+=1;} @@ -191,7 +191,7 @@ def item(declaration): // containment branch below decides whether the unit becomes claimable again. pub fn validate_compute_descriptor(refs:&ComputeRefs,_old:&[u8;160],_before:u64)->Result<(),()>{if refs.invalid{Err(())}else{Ok(())}} } -mod hw { pub mod sizes { pub const FLIGHTS:usize=32; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=8; pub const MAX_VM_COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=24; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=24; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } +mod hw { pub mod sizes { pub const FLIGHTS:usize=64; pub const TA_WAVE_PASSES:usize=4; pub const TA_WAVE_PASSES_LIGHT:usize=8; pub const TA_LIGHT_TILEMAP_BYTES:u64=64*1024; pub const TA_WAVE_REFILL_HEADROOM:usize=2; pub const COMPUTE_PIPES:usize=16; pub const MAX_VM_COMPUTE_PIPES:usize=2; pub const COMPUTE_UNITS:usize=64; pub const PIPE1_COMPUTE_START:usize=6; pub const COMPUTE_SLOTS:usize=64; pub const RENDER_SLOTS:usize=48; pub const COALESCE_MAX_CMDS:usize=6; pub const COALESCE_WINDOW_US:u32=18; pub const COALESCE_WINDOW_NS:u64=18_000; pub const COMPUTE_HEAVY_EMA_US:u32=200; pub const COMPUTE_HEAVY_INFLIGHT_NS:u64=180_000; } } mod command {pub const RENDER:usize=0;pub const COMPUTE:usize=1;} thread_local!{static CLOCK:std::cell::Cell=const{std::cell::Cell::new(0)};} fn now_ns()->u64{CLOCK.with(|clock|clock.get())} @@ -872,13 +872,13 @@ def item(declaration): struct QueueBehindSlots{compute_exhausted:bool,render_exhausted:bool,compute_available:bool,pass_available:bool,quarantined_uma_mask:u32} impl QueueBehindSlots{ fn compute_exhausted(&self)->bool{self.compute_exhausted} - fn compute_exhausted_in_mask(&self,mask:u32)->bool{self.compute_exhausted||mask==0} + fn compute_exhausted_in_mask(&self,mask:u64)->bool{self.compute_exhausted||mask==0} fn compute_uma_quarantined(&self,mask:u32)->bool{(self.quarantined_uma_mask&mask)!=0} fn render_exhausted(&self)->bool{self.render_exhausted} fn compute_available(&self,_n:usize)->bool{self.compute_available} - fn compute_available_in_mask(&self,_mask:u32)->bool{self.compute_available} - fn compute_available_in_mask_for_pipe(&self,mask:u32,pipe:usize)->bool{ - let allowed = if pipe == 0 { mask } else { mask & !((1u32 << hw::sizes::PIPE1_COMPUTE_START) - 1) }; + fn compute_available_in_mask(&self,_mask:u64)->bool{self.compute_available} + fn compute_available_in_mask_for_pipe(&self,mask:u64,pipe:usize)->bool{ + let allowed = if pipe == 0 { mask } else { mask & !((1u64 << hw::sizes::PIPE1_COMPUTE_START) - 1) }; self.compute_available && allowed != 0 } fn compute_available_for_pipe(&self,n:usize,pipe:usize)->bool{ @@ -1926,7 +1926,7 @@ def item(declaration): }; // Empty engine starts on pipe 0. let no_w = [None; sizes::COMPUTE_PIPES]; - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, false), Some(0)); host.engine.flights.push(QueueBehindFlight{ job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,compute_uma_mask:0,heavy_render:false,published_ns:1_000_000,target:0x100, cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, @@ -1949,17 +1949,17 @@ def item(declaration): q1.compute_ewma_us.store(0, Ordering::Relaxed); // Light single-queue barrier-free compute stays affine to its active pipe (pipe 0), // while heavy single-queue compute and a second independent queue balance onto idle pipe 1. - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(1)); - assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(1)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, true), Some(1)); + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, u64::MAX, false, false), Some(1)); // Cross-VM compute leases its own disjoint pipe (never shares VM1's active pipe 0). - assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), Some(1)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, u64::MAX, false, false), Some(1)); // Base-only VM2 (only units 0..2, cannot use secondary pipes) waits when pipe 0 is busy by VM1. assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), None); assert!(!host.has_compute_pipe_for_vm(&vm2, 0b11, false)); // RT/SCS compute on same VM stays pinned to pipe 0; other VM RT returns None while pipe 0 busy. - assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, (1u32 << 24) - 1, true, true), Some(0)); - assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, true, true), None); + assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, u64::MAX, true, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, u64::MAX, true, true), None); // A 2-unit base-only or SCS same-VM stays pinned to pipe 0. assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, 0b11, false, true), Some(0)); assert_eq!(host.choose_compute_pipe(&q2, &vm1, no_w, 0b110, false, true), Some(0)); @@ -1971,11 +1971,11 @@ def item(declaration): cstamp:[0x100;16],r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0,initbm:false, has_timestamps:false,doomed:false,recovery_suspect:false, }); - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(0)); - assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), Some(1)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, u64::MAX, false, false), Some(1)); // Heavy VM1 picks idle pipe 2 (never VM2's active pipe 1). - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(2)); - assert_eq!(host.choose_compute_pipe(&q3, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(2)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, true), Some(2)); + assert_eq!(host.choose_compute_pipe(&q3, &vm1, no_w, u64::MAX, false, false), Some(2)); // Once VM1 has 2 active pipes (0 and 2), MAX_VM_COMPUTE_PIPES=2 keeps VM1 on {0, 2}. host.engine.flights.push(QueueBehindFlight{ job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:2,rt_compute:false,compute_uma_mask:0,heavy_render:false,published_ns:1_000_000,target:0x100, @@ -1983,9 +1983,9 @@ def item(declaration): has_timestamps:false,doomed:false,recovery_suspect:false, }); host.engine.next_compute_pipe = 2; - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(2)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, true), Some(2)); host.engine.next_compute_pipe = 0; - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, true), Some(0)); // Cross-VM non-SCS compute queues on disjoint pipes without draining. assert!(host.can_queue_behind(&c_vm2)); assert!(host.can_queue_behind(&c2)); @@ -2004,7 +2004,7 @@ def item(declaration): assert!(!host.can_queue_behind(&c_vm2)); assert!(host.blocked_on_slot_headroom(&c_vm2)); assert!(!host.needs_engine_drain(&c_vm2)); - assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, (1u32 << 24) - 1, false, false), None); + assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, u64::MAX, false, false), None); // Starvation handoff: when all 8 pipes are occupied by other VMs, compute_handoff_pipe // picks one compatible pipe (0) to drain so the remaining 7 pipes keep dispatching while // pipe 0 drains for the waiting 9th VM. @@ -2015,8 +2015,8 @@ def item(declaration): let vm11 = host.engine.flights[1].job.vm.clone(); let q11 = host.engine.flights[1].job.queue.clone(); // Pipe 0 incumbent stops refilling pipe 0 while pipe 1 incumbent keeps dispatching on pipe 1. - assert_eq!(host.choose_compute_pipe(&q10, &vm10, no_w, (1u32 << 24) - 1, false, false), None); - assert_eq!(host.choose_compute_pipe(&q11, &vm11, no_w, (1u32 << 24) - 1, false, false), Some(1)); + assert_eq!(host.choose_compute_pipe(&q10, &vm10, no_w, u64::MAX, false, false), None); + assert_eq!(host.choose_compute_pipe(&q11, &vm11, no_w, u64::MAX, false, false), Some(1)); // Base-only VM2 (only units 0..2, limited to pipe 0) waiting while extension VM1 refills // pipe 0: avoiding pipe 0 moves VM1 onto pipe 1 while pipe 0 drains, then VM2 gets pipe 0! host.engine.handoff_avoid_pipes = 0; @@ -2030,7 +2030,7 @@ def item(declaration): assert_eq!(host.choose_compute_pipe(&q2, &vm2, no_w, 0b11, false, false), None); host.engine.handoff_avoid_pipes = 1u32 << 0; // Extension VM1 continues dispatching on secondary pipe 1 instead of refilling pipe 0. - assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, (1u32 << 24) - 1, false, false), Some(1)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, u64::MAX, false, false), Some(1)); // A base-only VM1 incumbent stops refilling pipe 0 so pipe 0 drains for handoff. assert_eq!(host.choose_compute_pipe(&q1, &vm1, no_w, 0b11, false, false), None); assert!(!host.has_compute_pipe_for_vm(&vm1, 0b11, false)); @@ -2079,13 +2079,13 @@ def item(declaration): // Waiting on seq 1 (pipe 0 only) returns [Some(0x100), None..] and reuses pipe 0 (zero c2c barrier). let w1 = host.wait_compute_stamps_for(&c3, Some(1)).unwrap(); assert_eq!(w1, exp1); - assert_eq!(host.choose_compute_pipe(&q1, &vm1, w1, (1u32 << 24) - 1, false, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w1, u64::MAX, false, true), Some(0)); // Waiting on seq 2 (both pipe 0 seq 1 and pipe 1 seq 2 <= 2) returns both stamps and // selects the least-loaded pipe (pipe 0 has 1 active vs pipe 1 has 2 -> picks pipe 0, // so prefix_compute emits one cross-pipe c2c barrier on pipe 1's 0x200). let w2 = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2, exp2); - assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2, (1u32 << 24) - 1, false, false), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2, u64::MAX, false, false), Some(0)); // Unpublished seq 3 returns Err(EAGAIN). assert_eq!(host.wait_compute_stamps_for(&c4, Some(3)), Err(EAGAIN)); // If seq 2 retired out-of-order on pipe 1 while seq 1 is still active on pipe 0, @@ -2096,7 +2096,7 @@ def item(declaration): assert!(q1.is_compute_retired(2)); let w2_ooo = host.wait_compute_stamps_for(&c4, Some(2)).unwrap(); assert_eq!(w2_ooo, exp1); - assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2_ooo, (1u32 << 24) - 1, false, true), Some(0)); + assert_eq!(host.choose_compute_pipe(&q1, &vm1, w2_ooo, u64::MAX, false, true), Some(0)); // Once contiguous completed[COMPUTE] reaches 2, wait_compute_stamps_for returns all None. q1.completed[command::COMPUTE].store(2, Ordering::Release); q1.compute_ooo.store(0, Ordering::Release); @@ -2158,7 +2158,7 @@ def item(declaration): exp_cw[0] = Some(WaitTarget{stamp:0x100,initbm:false}); let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); assert_eq!(cw,exp_cw); - assert_eq!(host.choose_compute_pipe(&q2,&vm1,cw,(1u32<<24)-1,false,false),Some(0)); + assert_eq!(host.choose_compute_pipe(&q2,&vm1,cw,u64::MAX,false,false),Some(0)); // Cross-queue render wait resolves q1's FS stamp 0x200. assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; @@ -2209,7 +2209,7 @@ def item(declaration): let gpu = Gpu; let limits = gpu.queue_limits().expect("G16 must expose queue_limits"); assert_eq!(limits.max_queues, 58); - assert_eq!(limits.max_in_flight_per_queue, 32); + assert_eq!(limits.max_in_flight_per_queue, 64); assert_eq!(limits.flags, 0); assert_eq!(limits.pad, 0); let mut features = 0u64; @@ -2857,8 +2857,8 @@ def item(declaration): } struct Resources { units: usize, scs: bool } impl Resources { - fn compute_slot_mask(&self) -> Result { - Ok(if self.units >= 32 { u32::MAX } else { (1u32 << self.units) - 1 }) + fn compute_slot_mask(&self) -> Result { + Ok(if self.units >= 64 { u64::MAX } else { (1u64 << self.units) - 1 }) } fn compute_scs(&self) -> bool { self.scs } fn render_scs(&self) -> bool { self.scs } @@ -2918,7 +2918,7 @@ def item(declaration): } struct Slots { free_c: u32 } impl Slots { - fn free_compute_in_mask_for_pipe(&self, _m: u32, _p: usize) -> u32 { self.free_c } + fn free_compute_in_mask_for_pipe(&self, _m: u64, _p: usize) -> u32 { self.free_c } } struct Host { recovery: Recovery, @@ -2929,7 +2929,7 @@ def item(declaration): } impl Host { fn can_queue_behind(&self, _job: &Arc) -> bool { self.allow_behind } - fn choose_compute_pipe(&self, _q: &Arc, _vm: &Arc, _w: [Option<()>; crate::hw::sizes::COMPUTE_PIPES], _m: u32, _rt: bool, _heavy: bool) -> Option { Some(0) } + fn choose_compute_pipe(&self, _q: &Arc, _vm: &Arc, _w: [Option<()>; crate::hw::sizes::COMPUTE_PIPES], _m: u64, _rt: bool, _heavy: bool) -> Option { Some(0) } fn ta_pending_passes(&self) -> usize { self.ta_pending } __COMPUTE_QUEUE_IS_HEAVY__ __TA_WAVE_CAP_FOR__ 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 e09ad8a7422ec..731ea897be816 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -304,14 +304,14 @@ def module(text, name): } impl ComputeArena{ pub fn compute_units(&self)->Result{Ok(self.compute.len())} - pub fn compute_slot_mask(&self)->Result{ + pub fn compute_slot_mask(&self)->Result{ if let Some(slots)=self.hw_slots { - let mut mask=0u32; - for slot in slots { mask |= 1u32 << slot; } + let mut mask=0u64; + for slot in slots { mask |= 1u64 << slot; } return Ok(mask); } let n=self.compute.len().min(super::hw::sizes::COMPUTE_UNITS); - Ok(if n>=32 { u32::MAX } else { (1u32 << n) - 1 }) + Ok(if n>=64 { u64::MAX } else { (1u64 << n) - 1 }) } pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{ if let Some(slots)=self.hw_slots { @@ -1134,9 +1134,11 @@ def module(text, name): assert_eq!(p0.heap.fills.lock().unwrap().last(),Some(&(0,0x4000))); } - #[test]fn forty_eight_render_passes_and_twenty_four_compute_units_are_disjoint_in_mesa_hole(){ + #[test]fn forty_eight_render_passes_and_sixty_four_compute_units_are_disjoint_in_mesa_hole(){ assert_eq!(g16::hw::sizes::RENDER_SLOTS, 48); - assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 24); + assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 64); + assert_eq!(g16::hw::sizes::COMPUTE_PIPES, 16); + assert_eq!(g16::hw::sizes::FLIGHTS, 64); let mut o=Objects::new(); let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); for idx in 0..g16::hw::sizes::EXT_PB_SLOTS { @@ -1146,7 +1148,13 @@ def module(text, name): assert_eq!(ext.refs().unwrap().parameter_id,hw_slot); } for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { - g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k,&crate::g16::object::test_unit_cmds(k)).unwrap(); + g16::slots::ComputeSlot::new_shared_in(&mut o,k,&crate::g16::object::test_unit_cmds(k)).unwrap(); + } + let pl=g16::slots::Placement::Base; + for w in 0..g16::hw::sizes::COMPUTE_UMA_WINDOWS as u64 { + o.alloc(g16::object::Request{size:pl.pool_bytes(),class:g16::object::Class::Shared,placement:g16::object::Placement::Anywhere,offset:0,client:Some((pl.pool(w),g16::hw::pte::LEAF_NC)),lower:None,cpu:false}).unwrap(); + g16::graph::alloc(&mut o,pl.freelist_bytes(),g16::object::Class::Shared,g16::graph::Client::nc(pl.freelist(w)),0,false).unwrap(); + g16::graph::alloc(&mut o,0x4000,g16::object::Class::Shared,g16::graph::Client::nc(pl.state(w)+g16::hw::client::COMPUTE_LIST_OFF),0,false).unwrap(); } let mut scene_lists=Vec::new(); let count_client=|objs:&Objects|objs.objects.iter().filter(|a|a.gva.is_some()).count(); @@ -2111,7 +2119,7 @@ def module(text, name): let mut c=Claims::new(); assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c,Some(bad.id),0).unwrap(),Some(0)); s.hold_vm(&c,&bad).unwrap();s.publish(&mut c).unwrap();s.quarantine(&mut c); - assert_eq!(s.quarantined_compute_mask(), 1u32 << 0); + assert_eq!(s.quarantined_compute_mask(), 1u64 << 0); // Pipe 1 runs concurrent non-SCS compute on PIPE1_COMPUTE_START..COMPUTE_UNITS. let mut c_p1=Claims::new(); assert_eq!(s.claim_compute_for_pipe(&prep_full,&mut c_p1,Some(other.id),1).unwrap(),Some(p1_start)); @@ -2125,7 +2133,7 @@ def module(text, name): } let prep_scs=g16::resources::ComputeArena{compute:scs_units,render:None,hw_slots:Some(scs_slots),shared_uma:None}; let scs_mask = prep_scs.compute_slot_mask().unwrap(); - assert_eq!(scs_mask, (1u32 << 1) | (1u32 << 2)); + assert_eq!(scs_mask, (1u64 << 1) | (1u64 << 2)); // Execute two back-to-back SCS compute commands (e.g. rt.scene p_rt + p_comp) repeatedly: // must never hit compute_exhausted_in_mask and must ping-pong cleanly across [1, 2]. for expected in [1usize, 2, 1, 2] { @@ -3679,10 +3687,17 @@ def module(text, name): s.publish(&mut cb1).unwrap(); s.retire(&mut cb1).unwrap(); let lease_b1 = uma_b1.uma_lease.clone(); - // Exhausting pool_va_idx >= COMPUTE_UNITS returns EIO. + // Exhausting pool_va_idx >= COMPUTE_UMA_WINDOWS returns EIO. assert!( - SharedComputeUma::new(&factory, &bind_b, &vm_b.vm, &live_b, s2, COMPUTE_UNITS) - .is_err() + SharedComputeUma::new( + &factory, + &bind_b, + &vm_b.vm, + &live_b, + s2, + g16::hw::sizes::COMPUTE_UMA_WINDOWS, + ) + .is_err() ); drop(bind_b); drop(prep_b); 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 570b060527199..864b6a71d0834 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 @@ -31,7 +31,7 @@ def function(text, name): #[path="__LOGIC__"]mod logic; use logic::{Retirement, ABORT_GRACE_NS}; mod encode { __STAMP_SEED__ __STAMP__ } -mod hw { pub mod sizes { pub const COMPUTE_PIPES: usize = 8; } } +mod hw { pub mod sizes { pub const COMPUTE_PIPES: usize = 16; } } struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell} impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0)}}} impl Object { From 97d88a257221df38378ed543ddddc6521aa4771b Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 21:05:50 -0500 Subject: [PATCH 2/7] drm/asahi: g16: map shared compute UMA descriptors and fw_stamp ASC-cached Shared compute UMA descriptors and compute queue fw_stamp records do not need to be uncached on the firmware side: - Add a device-lifetime ComputeUmaPool on Factory that allocates persistent ASC-cached (FwCoherent) SharedComputeUma descriptors paired with uncached (Fw) counters. Because the descriptor is never unmapped, firmware can cache it across flights; a lease returns to the pool on drop only when every published flight has retired normally, keeping aborted or quarantined records out of circulation. - Map compute QueueSession fw_stamp records ASC-cached (FwCached) and observe compute retirement through the uncached service stamp written by the notifier service after firmware descriptor bookkeeping. This drops uncached firmware writes on every shared compute flight and eliminates the host read of the shared descriptor at retirement. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/engine.rs | 25 ++- drivers/gpu/drm/asahi/g16/graph.rs | 7 +- drivers/gpu/drm/asahi/g16/mod.rs | 6 +- drivers/gpu/drm/asahi/g16/object.rs | 7 + drivers/gpu/drm/asahi/g16/poll.rs | 31 ++-- drivers/gpu/drm/asahi/g16/resources.rs | 165 ++++++++++++++++-- drivers/gpu/drm/asahi/g16/slots.rs | 19 +- .../drivers/gpu/asahi-m4/test-poll-retire.py | 31 ++-- .../gpu/asahi-m4/test-progress-wrap.py | 21 +-- .../drivers/gpu/asahi-m4/test-resources.py | 67 ++++++- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 40 ++--- 11 files changed, 321 insertions(+), 98 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 031e5f381408f..0cb98cca234ea 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -899,7 +899,7 @@ impl Firmware { stage[0] = self.graph.render.fw_stamp[0].r32(0)?; stage[1] = self.graph.render.fw_stamp[1].r32(0)?; for (p, compute) in self.graph.compute.iter().enumerate() { - stage[2 + p] = compute.fw_stamp.r32(0)?; + stage[2 + p] = compute.notifier.r32(notifier_page::COMPUTE_STAMP)?; } Ok(stage) } @@ -3489,6 +3489,7 @@ impl Firmware { if let Some(shared) = job.resources.shared_compute_uma() { if f.claims.slot_count != 0 { let tail_sub = f.csubmitted[(f.claims.slot_count - 1) as usize]; + shared.uma_lease.publish(); shared.submitted.store(tail_sub, Ordering::Release); shared.counter.w64(0, tail_sub)?; } @@ -3780,18 +3781,16 @@ impl Firmware { 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); - } + // The shared UMA descriptor is ASC-cached (`FwCoherent`) so the host does + // not read firmware-cached completion words; verify the uncached host + // submission counter matches `before` at idle boundaries. + if pf.uma_delta == 1 + && before == shared.retired.load(Ordering::Acquire) + && shared.counter.r64(0)? != before + { + self.slots.quarantine(&mut f.claims); + self.sync_quarantine_hints(); + return Err(EIO); } } else { // Slots::claim_compute proved a different fully retired unit displaced this diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index b3eaa19d7ee44..e9f28c6991d30 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -135,11 +135,14 @@ struct QueueSession { } impl QueueSession { fn new(o: &mut Objects) -> Result { + Self::new_with(o, Class::Shared) + } + fn new_with(o: &mut Objects, fw_stamp_class: Class) -> Result { Ok(Self { qinfo: alloc(o, qinfo::SIZE, graph_fw(), None, 0, false)?, qstate: alloc(o, qstate::SIZE, Class::Fw, None, 0, false)?, user_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, - fw_stamp: alloc(o, 8, Class::Shared, None, 0, false)?, + fw_stamp: alloc(o, 8, fw_stamp_class, None, 0, false)?, }) } /// Completes the queue with its firmware-cached work ring from a device-lifetime @@ -220,7 +223,7 @@ impl ComputeGraphSession { notifier: alloc(o, 0x1000, Class::Fw, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, job_list: alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, - q: QueueSession::new(o)?, + q: QueueSession::new_with(o, Class::FwCached)?, }) } fn finish(self, rings: &mut Objects) -> Result { diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index aa60d8e7419b3..399ae0dd25885 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -782,7 +782,11 @@ impl Firmware { let recovery = recovery::Recovery::new()?; let render_cmds = resources::RenderCmds::new()?; let compute_cmds = resources::ComputeCmds::new()?; - let private_factory = booted.objects.private_factory(render_cmds, compute_cmds); + let compute_uma_pool = resources::ComputeUmaPool::new()?; + let private_factory = + booted + .objects + .private_factory(render_cmds, compute_cmds, compute_uma_pool); let graph = graph::Graphs::finish(dev, graph_session, &private_factory)?; let slot = KBox::::new_uninit(GFP_KERNEL)?; Ok((graph, private_factory, slots, pools, vms, engine, recovery, slot)) diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index cda6f6617e279..81c943d7b54fe 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -396,6 +396,7 @@ pub(crate) struct Factory { firmware: core::ops::Range, render_cmds: Arc, compute_cmds: Arc, + compute_uma_pool: Arc, } impl Factory { @@ -489,6 +490,10 @@ impl Factory { pub(crate) fn compute_cmds(&self, k: usize) -> Result { self.compute_cmds.get(self, k) } + + pub(crate) fn compute_uma_pool(&self) -> &Arc { + &self.compute_uma_pool + } } /// The firmware object allocator and the set of retained objects. @@ -547,6 +552,7 @@ impl Objects { &mut self, render_cmds: Arc, compute_cmds: Arc, + compute_uma_pool: Arc, ) -> Factory { self.sealed = true; Factory { @@ -556,6 +562,7 @@ impl Objects { firmware: self.fw_next..hw::va::FW_ALLOC.end, render_cmds, compute_cmds, + compute_uma_pool, } } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index b3190639b2d67..9e03a4bbb8c27 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -925,7 +925,10 @@ impl Firmware { rmb(); for p in 0..super::hw::sizes::COMPUTE_PIPES { if let Some(f) = oldest_compute[p] { - if let Ok(obs) = self.graph.compute[p].fw_stamp.r32(0) { + if let Ok(obs) = self.graph.compute[p] + .notifier + .r32(notifier_page::COMPUTE_STAMP) + { let reached = if compute_behind[p] { stamp_reached(obs, f.target, self.engine.target[p]) } else { @@ -1290,9 +1293,13 @@ impl Firmware { .is_some() || f.rec[2] != self.channels.producer(Channel::Compute); let g = &self.graph.compute[pipe]; + // Compute `fw_stamp` is ASC-cached (`FwCached`), matching macOS 26B123; the host + // checks the uncached compute service stamp that firmware stores strictly after + // updating `fw_stamp` and completing work-item, microsequence, and UMA accesses. if pipe_behind { let tail = self.engine.target[pipe]; - if !stamp_reached(g.fw_stamp.r32(0)?, f.target, tail) + let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; + if !stamp_reached(stamp, f.target, tail) || !self.queue_ring_passed(Channel::Compute, &g.qstate, &g.qinfo, f)? || !(f.chan_settled || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) @@ -1300,12 +1307,10 @@ impl Firmware { return Ok(Retirement::Pending); } rmb(); - let stamp = g.notifier.r32(notifier_page::COMPUTE_STAMP)?; - full &= stamp_reached(stamp, f.target, tail) - && (stamp != f.target - || g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot); + full &= stamp != f.target + || g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; } else { - if g.fw_stamp.r32(0)? != f.target + if g.notifier.r32(notifier_page::COMPUTE_STAMP)? != f.target || !self.queue_ring_receipt(&g.qstate, &g.qinfo, f.head)? || !(f.chan_settled || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) @@ -1313,8 +1318,7 @@ impl Firmware { return Ok(Retirement::Pending); } rmb(); - full &= g.notifier.r32(notifier_page::COMPUTE_STAMP)? == f.target - && g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; + full &= g.notifier.r32(notifier_page::COMPUTE_CONTEXT)? == f.job.vm.slot; } let count = f.claims.slot_count as usize; full &= count != 0 && count == f.computes as usize; @@ -1861,7 +1865,9 @@ impl Firmware { for p in 0..CP { if let Some(f) = fc[p] { next_progress[p] = pending( - g[p].fw_stamp.r32(0).unwrap_or(0), + g[p].notifier + .r32(notifier_page::COMPUTE_STAMP) + .unwrap_or(0), f.target, e.target[p], ); @@ -2147,15 +2153,14 @@ impl Firmware { dev_info!( self.graph.dev.as_ref(), - "G16: {}: ctx={} prefixes={} n={} pipe={} target={:#x} user={:#x} fw={:#x} done={} read={} write={} head={} ch={}/{} events={}/{} errors={} busy={} fault={:#x} {}ms\n", + "G16: {}: ctx={} prefixes={} n={} pipe={} target={:#x} user={:#x} done={} read={} write={} head={} ch={}/{} events={}/{} errors={} busy={} fault={:#x} {}ms\n", what, f.map_or(0, |f| f.job.vm.slot), e.flights.len(), e.ordinal, pipe, e.target[pipe], - rd(&g.user_stamp, 0), - rd(&g.fw_stamp, 0), + rd(&g.notifier, notifier_page::COMPUTE_STAMP), rd(&g.qstate, qstate::DONE), rd(&g.qstate, qstate::READ), rd(&g.qstate, qstate::WRITE), diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 98e60e102e6f0..bd831328ab42d 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -158,6 +158,141 @@ impl ComputeCmds { /// avoids allocating and mapping fresh epochs whenever submission depth rises. const SPARE_EPOCHS: usize = 32; +/// Firmware-cached descriptor and uncached submission counter of one shared compute UMA slot +/// ([`SharedComputeUma`]), kept for the device lifetime because ASC-cached mappings have no +/// qualified teardown. +pub(crate) struct ComputeUmaRecordSet { + pub(crate) descriptor: Arc, + /// Uncached submission counter written by the host at every compute publication. + pub(crate) counter: Arc, +} + +impl ComputeUmaRecordSet { + fn alloc(o: &mut Objects) -> Result { + Ok(Self { + descriptor: super::graph::alloc( + o, + super::fw::work::compute::DESCRIPTOR_SIZE, + super::object::Class::FwCoherent, + None, + 0, + false, + )?, + counter: super::graph::alloc(o, 0x80, super::object::Class::Fw, None, 0, false)?, + }) + } +} + +struct ComputeUmaEntry { + set: ComputeUmaRecordSet, + in_use: AtomicBool, +} + +/// Device-lifetime pool of ASC-cached compute UMA descriptor/counter record sets. +/// +/// A set returns to the pool only when every flight published on it retired normally (firmware +/// cleans the descriptor on idle before storing the flight's service stamp) and the last holder +/// (the VM's [`SharedComputeUma`] and [`super::slots::Slots`]'s hardware-slot retention lease) +/// drops. A set that carried an aborted or quarantined flight stays out of the pool forever. +#[pin_data] +pub(crate) struct ComputeUmaPool { + #[pin] + entries: Mutex>>, +} + +impl ComputeUmaPool { + pub(crate) fn new() -> Result> { + Arc::pin_init( + pin_init!(Self { + entries <- new_mutex!(KVec::new(), "g16::ComputeUmaPool"), + }), + GFP_KERNEL, + ) + } + + pub(crate) fn take(&self, factory: &Factory) -> Result<(Arc, bool)> { + let idle = self + .entries + .lock() + .iter() + .find(|entry| { + entry + .in_use + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + }) + .cloned(); + let (entry, used) = match idle { + Some(entry) => (entry, true), + None => { + // Never dropped, also on partial failure: maps ASC-cached FwCoherent records. + let mut objects = core::mem::ManuallyDrop::new(factory.persistent_objects()); + let set = ComputeUmaRecordSet::alloc(&mut objects)?; + objects.finish_private()?; + let entry = Arc::new( + ComputeUmaEntry { + set, + in_use: AtomicBool::new(true), + }, + GFP_KERNEL, + )?; + self.entries.lock().push(entry.clone(), GFP_KERNEL)?; + (entry, false) + } + }; + let lease = Arc::new( + ComputeUmaLease { + entry, + published_flights: AtomicU64::new(0), + retired_flights: AtomicU64::new(0), + }, + GFP_KERNEL, + )?; + Ok((lease, used)) + } +} + +/// Lease on one [`ComputeUmaPool`] record set, shared by [`SharedComputeUma`] and +/// [`super::slots::Slots`] until firmware's hardware UMA slot is overwritten by another owner. +pub(crate) struct ComputeUmaLease { + entry: Arc, + published_flights: AtomicU64, + retired_flights: AtomicU64, +} + +impl ComputeUmaLease { + /// Records a published compute flight using this descriptor. + pub(crate) fn publish(&self) { + self.published_flights.fetch_add(1, Ordering::AcqRel); + } + + /// Records a normal full retirement of a compute flight using this descriptor. + pub(crate) fn retire(&self) { + self.retired_flights.fetch_add(1, Ordering::AcqRel); + } + + /// Whether every flight published on this descriptor retired normally. + pub(crate) fn settled(&self) -> bool { + self.published_flights.load(Ordering::Acquire) + == self.retired_flights.load(Ordering::Acquire) + } +} + +impl core::ops::Deref for ComputeUmaLease { + type Target = ComputeUmaRecordSet; + fn deref(&self) -> &Self::Target { + &self.entry.set + } +} + +impl Drop for ComputeUmaLease { + fn drop(&mut self) { + if self.settled() { + self.entry.in_use.store(false, Ordering::Release); + } + } +} + /// Per-VM shared compute UMA manager descriptor, submission counter, and 32 MiB backing pool. /// /// All non-SCS compute units (`0..COMPUTE_UNITS`) of a VM reference this single descriptor and @@ -177,7 +312,7 @@ pub(crate) struct SharedComputeUmaInner { pub(crate) pool: Arc, pub(crate) pool_state: Arc, pub(crate) page_list: Arc, - pub(crate) uma_lease: Arc, + pub(crate) uma_lease: Arc, pub(crate) uma_slot: u32, pub(crate) uma_slot_idx: usize, pub(crate) seeds: u32, @@ -208,12 +343,13 @@ 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 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 uma_lease = super::object::FwLease::new(fw)?; + let (uma_lease, used) = factory.compute_uma_pool().take(factory)?; + let descriptor = uma_lease.descriptor.clone(); + let counter = uma_lease.counter.clone(); + if used { + counter.fill(0, 0, counter.size)?; + descriptor.fill(0, 0, super::fw::work::compute::DESCRIPTOR_SIZE)?; + } let mut objects = factory.objects(vm); let pool = objects.alloc(super::object::Request { size: placement.pool_bytes(), @@ -1858,9 +1994,11 @@ impl Prepared { self.compute_slot_mask().unwrap_or(0) as u32 } } - /// 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. + /// Whether the VM's shared compute UMA submission counter accounts for at least `count` + /// additional commands beyond previously retired flights, and matches exact host conservation + /// when `last_vm_flight` drains the VM idle. The descriptor itself is ASC-cached (`FwCoherent`) + /// so its completion count is not read by the host: firmware advances `COMPLETED` and cleans + /// the descriptor on idle strictly before storing the flight's service stamp (`user_stamp`). pub(crate) fn compute_uma_retired(&self, count: u32, last_vm_flight: bool) -> Result { let Some(uma) = &self.compute_uma else { return Ok(false); @@ -1870,16 +2008,13 @@ impl Prepared { .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) + Ok(counter >= needed && (!last_vm_flight || needed == counter)) } /// 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); + uma.uma_lease.retire(); } } /// Whether this job's renders use SCS-capable render allocators. diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index d3ccf6f7b1d4a..d7504cc5a6bd4 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -783,8 +783,8 @@ pub(crate) struct ComputeOwners { /// 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]`. - retained_uma: [Option>; sizes::COMPUTE_UMA_SLOTS], - pending_uma: [Option>; sizes::COMPUTE_UNITS], + retained_uma: [Option; sizes::COMPUTE_UMA_SLOTS], + 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 /// retirement (`retained_uma[slot]` keeps the VM-free `FwLease`) and moved into @@ -804,6 +804,13 @@ pub(crate) struct ComputeOwners { last_full: [bool; sizes::COMPUTE_UNITS], } +/// Hardware compute UMA descriptor/counter retention lease keeping firmware's global +/// `uma_mgr_table[COMPUTE_UMA_SLOT + slot]` mapped across closed-VM reclaim until overwritten. +enum ComputeUmaRetain { + Private(Arc), + Shared(Arc), +} + /// Bitmask of valid hardware compute UMA slot indices (`0..sizes::COMPUTE_UMA_SLOTS`). const COMPUTE_UMA_MASK: u32 = u32::MAX >> (32 - sizes::COMPUTE_UMA_SLOTS); @@ -1964,7 +1971,7 @@ impl Slots { self.compute.pending_owner[k] = Some(vm.clone()); self.compute.pending_arena[k] = resources.compute_arena(k); if let Some(shared) = resources.shared_compute_uma() { - self.compute.pending_uma[k] = Some(shared.uma_lease.clone()); + self.compute.pending_uma[k] = Some(ComputeUmaRetain::Shared(shared.uma_lease.clone())); self.compute.pending_uma_slot[k] = shared.uma_slot_idx; self.compute.pending_shared_uma[k] = Some(shared.clone()); } else if let Some(private) = resources @@ -1972,7 +1979,7 @@ impl Slots { .ok() .and_then(|unit| unit.private_uma.as_ref()) { - self.compute.pending_uma[k] = Some(private.uma_lease()); + self.compute.pending_uma[k] = Some(ComputeUmaRetain::Private(private.uma_lease())); self.compute.pending_uma_slot[k] = private.uma_slot_idx(); self.compute.pending_shared_uma[k] = None; } else { @@ -2103,7 +2110,7 @@ impl Slots { } if let Some(cell) = self.compute.pending_uma.get_mut(k as usize) { if let Some(shared) = resources.shared_compute_uma() { - *cell = Some(shared.uma_lease.clone()); + *cell = Some(ComputeUmaRetain::Shared(shared.uma_lease.clone())); self.compute.pending_uma_slot[k as usize] = shared.uma_slot_idx; self.compute.pending_shared_uma[k as usize] = Some(shared.clone()); } else if let Some(private) = resources @@ -2111,7 +2118,7 @@ impl Slots { .ok() .and_then(|unit| unit.private_uma.as_ref()) { - *cell = Some(private.uma_lease()); + *cell = Some(ComputeUmaRetain::Private(private.uma_lease())); self.compute.pending_uma_slot[k as usize] = private.uma_slot_idx(); self.compute.pending_shared_uma[k as usize] = None; } else { diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py index be2d3c28dcd1d..52ead13872528 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-poll-retire.py @@ -122,8 +122,11 @@ def item(declaration, text=source): } } +mod notifier_page { + pub const COMPUTE_STAMP: usize = 0x640; +} struct ComputeGraph { - fw_stamp: Cell32, + notifier: Cell32, } struct RenderGraph { fw_stamp: [Cell32; 2], @@ -350,7 +353,7 @@ def item(declaration, text=source): objects: Objects, graph: Graph { compute: core::array::from_fn(|_| ComputeGraph { - fw_stamp: Cell32::new(0), + notifier: Cell32::new(0), }), render: RenderGraph { fw_stamp: [Cell32::new(0), Cell32::new(0)], @@ -598,7 +601,7 @@ def item(declaration, text=source): fs_target: 0, }); fw.engine.target[0] = 0x100; - fw.graph.compute[0].fw_stamp.set(0x100); + fw.graph.compute[0].notifier.set(0x100); fw.retire_on_call = true; let mut done = vec![]; @@ -867,9 +870,9 @@ def item(declaration, text=source): fw.engine.target[0] = 0x100; // Render still running, compute reached its stamp. fw.graph.render.fw_stamp[1].set(0x100); - fw.graph.compute[0].fw_stamp.set(0x100); + fw.graph.compute[0].notifier.set(0x100); assert!(fw.oldest_stamp_reached()); - assert_eq!(fw.graph.compute[0].fw_stamp.reads.get(), 1); + assert_eq!(fw.graph.compute[0].notifier.reads.get(), 1); assert_eq!(fw.graph.render.fw_stamp[1].reads.get(), 0); assert_eq!(fw.oldest_terminal_events(), Some((Some(0), Some(0)))); @@ -891,11 +894,11 @@ def item(declaration, text=source): }); fw2.engine.target[0] = 0x200; fw2.engine.target[1] = 0x100; - fw2.graph.compute[0].fw_stamp.set(0x100); - fw2.graph.compute[1].fw_stamp.set(0x100); + fw2.graph.compute[0].notifier.set(0x100); + fw2.graph.compute[1].notifier.set(0x100); assert!(fw2.oldest_stamp_reached()); - assert_eq!(fw2.graph.compute[0].fw_stamp.reads.get(), 1); - assert_eq!(fw2.graph.compute[1].fw_stamp.reads.get(), 1); + assert_eq!(fw2.graph.compute[0].notifier.reads.get(), 1); + assert_eq!(fw2.graph.compute[1].notifier.reads.get(), 1); assert_eq!(fw2.graph.render.fw_stamp[1].reads.get(), 0); } @@ -911,10 +914,10 @@ def item(declaration, text=source): fs_target: 0, }); fc.engine.target[0] = 0x200; - fc.graph.compute[0].fw_stamp.set(0x100); + fc.graph.compute[0].notifier.set(0x100); assert!(!fc.oldest_stamp_reached()); - assert_eq!(fc.graph.compute[0].fw_stamp.reads.get(), 1); - assert_eq!(fc.graph.compute[1].fw_stamp.reads.get(), 0); + assert_eq!(fc.graph.compute[0].notifier.reads.get(), 1); + assert_eq!(fc.graph.compute[1].notifier.reads.get(), 0); assert_eq!(fc.graph.render.fw_stamp[0].reads.get(), 0); assert_eq!(fc.graph.render.fw_stamp[1].reads.get(), 0); @@ -930,8 +933,8 @@ def item(declaration, text=source): fr.engine.fs_target = 0x200; fr.graph.render.fw_stamp[1].set(0x100); assert!(!fr.oldest_stamp_reached()); - assert_eq!(fr.graph.compute[0].fw_stamp.reads.get(), 0); - assert_eq!(fr.graph.compute[1].fw_stamp.reads.get(), 0); + assert_eq!(fr.graph.compute[0].notifier.reads.get(), 0); + assert_eq!(fr.graph.compute[1].notifier.reads.get(), 0); assert_eq!(fr.graph.render.fw_stamp[0].reads.get(), 0); assert_eq!(fr.graph.render.fw_stamp[1].reads.get(), 1); } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py index c3deb047a9b2f..e32f68be4ff27 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-progress-wrap.py @@ -31,7 +31,8 @@ def function(text,name): macro_rules! dev_warn{($($tt:tt)*)=>{};} macro_rules! dev_err{($($tt:tt)*)=>{};} struct Object(Cell);impl Object{fn r32(&self,_off:usize)->core::result::Result{Ok(self.0.get())}} -struct Compute{fw_stamp:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;hw::sizes::COMPUTE_PIPES],render:Render} +mod notifier_page{pub const COMPUTE_STAMP:usize=0x640;} +struct Compute{notifier:Object}struct Render{fw_stamp:[Object;2]}struct Graph{compute:[Compute;hw::sizes::COMPUTE_PIPES],render:Render} struct Job{long:bool} impl Job{fn long(&self)->bool{self.long}} struct Flight{job:Job,computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} @@ -75,7 +76,7 @@ def function(text,name): fn firmware(render:bool,target:u32,previous:u32)->Firmware{ set_now_ns(1_000_000_000); let mut t=[0u32;hw::sizes::COMPUTE_PIPES];t[0]=target; - let mut f=Firmware{graph:Graph{compute:core::array::from_fn(|_|Compute{fw_stamp:Object(Cell::new(previous))}),render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, + let mut f=Firmware{graph:Graph{compute:core::array::from_fn(|_|Compute{notifier:Object(Cell::new(previous))}),render:Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]}}, engine:Engine{flights:vec![Flight{job:Job{long:false},computes:u32::from(!render),compute_pipe:0,renders:u32::from(render),target,ta_target:target,fs_target:target,published_ns:1}],target:t,ta_target:target,fs_target:target,progress_flight:[0;hw::sizes::COMPUTE_PIPES+1],progress:[__ZERO__;hw::sizes::COMPUTE_PIPES+2]}, recovery:Recovery{deadlines:logic::Deadlines::EXPIRED,compute_deadlines:[logic::Deadlines::EXPIRED;hw::sizes::COMPUTE_PIPES],warning_deadline_ns:[u64::MAX;2],compute_warning_deadline_ns:[u64::MAX;hw::sizes::COMPUTE_PIPES],long_commands:0,receipt_fault:false,failed:None}, render_renewed:0,compute_renewed:0,pipe_renewed:[0;hw::sizes::COMPUTE_PIPES],fail_stops:vec![]}; @@ -83,13 +84,13 @@ def function(text,name): } #[test]fn pending_native_zero_and_reached_are_distinct_progress_states(){ let mut f=firmware(false,0x100,0);f.progress();assert_eq!(f.compute_renewed,0);f.progress();assert_eq!(f.compute_renewed,0); - f.graph.compute[0].fw_stamp.0.set(0x100);f.progress();assert_eq!(f.compute_renewed,1,"completion following real wire zero renews deadline before retirement check"); + f.graph.compute[0].notifier.0.set(0x100);f.progress();assert_eq!(f.compute_renewed,1,"completion following real wire zero renews deadline before retirement check"); assert_eq!(f.render_renewed,0); f.progress();assert_eq!(f.compute_renewed,1,"repeated completed stamp is not new progress"); } #[test]fn paired_ta_fs_zero_each_renews_once_without_lending_other_engine_progress(){ let mut f=firmware(true,0x100,0);f.progress(); - f.graph.compute[0].fw_stamp.0.set(0x100);f.progress();assert_eq!(f.render_renewed,0);assert_eq!(f.compute_renewed,0); + f.graph.compute[0].notifier.0.set(0x100);f.progress();assert_eq!(f.render_renewed,0);assert_eq!(f.compute_renewed,0); f.graph.render.fw_stamp[0].0.set(0x100);f.progress();assert_eq!(f.render_renewed,1);assert_eq!(f.compute_renewed,0); f.graph.render.fw_stamp[1].0.set(0x100);f.progress();assert_eq!(f.render_renewed,2);assert_eq!(f.compute_renewed,0); f.progress();assert_eq!(f.render_renewed,2); @@ -97,7 +98,7 @@ def function(text,name): #[test]fn before_at_and_after_zero_completions_have_the_same_progress_contract(){ for target in [0x7fffff00u32,0x80000000,0xffffff00,0,0x100]{ let mut f=firmware(false,target,target.wrapping_sub(0x100));f.progress();assert_eq!(f.compute_renewed,0); - f.graph.compute[0].fw_stamp.0.set(target);f.progress();assert_eq!(f.compute_renewed,1); + f.graph.compute[0].notifier.0.set(target);f.progress();assert_eq!(f.compute_renewed,1); f.engine.flights[0].published_ns=2;f.progress();assert_eq!(f.compute_renewed,1,"new flight first sample is not forward progress"); } } @@ -106,7 +107,7 @@ def function(text,name): f.engine.flights.push(Flight{job:Job{long:false},computes:1,compute_pipe:0,renders:0,target:0x300,ta_target:0,fs_target:0,published_ns:2}); f.engine.target[0]=0x300; f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,0)); - f.graph.compute[0].fw_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); + f.graph.compute[0].notifier.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); f.graph.render.fw_stamp[0].0.set(0x200);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(1,1)); } #[test]fn two_concurrent_compute_pipes_sample_progress_independently(){ @@ -115,11 +116,11 @@ def function(text,name): f.engine.target[0]=0x200;f.engine.target[1]=0x200; f.progress();assert_eq!(f.compute_renewed,0); // Pipe 1 advances while pipe 0 stays pending -> renews compute deadline once. - f.graph.compute[1].fw_stamp.0.set(0x200); + f.graph.compute[1].notifier.0.set(0x200); f.progress();assert_eq!(f.compute_renewed,1); f.progress();assert_eq!(f.compute_renewed,1); // Pipe 0 advances independently -> renews compute deadline a second time. - f.graph.compute[0].fw_stamp.0.set(0x200); + f.graph.compute[0].notifier.0.set(0x200); f.progress();assert_eq!(f.compute_renewed,2); } #[test]fn stuck_render_times_out_while_compute_keeps_advancing_and_retiring(){ @@ -132,7 +133,7 @@ def function(text,name): for step in 1u64..=3 { set_now_ns(1_000_000_000 + step * 400_000_000); let next_target = 0x300 + (step as u32) * 0x100; - f.graph.compute[0].fw_stamp.0.set(next_target - 0x100); + f.graph.compute[0].notifier.0.set(next_target - 0x100); f.engine.flights[1].target = next_target; f.engine.flights[1].published_ns = 2 + step; f.engine.target[0] = next_target; @@ -187,7 +188,7 @@ def function(text,name): for step in 1u64..=3 { set_now_ns(1_000_000_000 + step * 2_000_000_000); let next_target = 0x300 + (step as u32) * 0x100; - f.graph.compute[1].fw_stamp.0.set(next_target - 0x100); + f.graph.compute[1].notifier.0.set(next_target - 0x100); f.engine.flights[1].target = next_target; f.engine.flights[1].published_ns = 2 + step; f.engine.target[1] = next_target; 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 731ea897be816..8869fe773c209 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -131,11 +131,20 @@ def module(text, name): } } pub struct Factory; + std::thread_local!{ + pub static COMPUTE_UMA_POOL: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; + } impl Factory{ pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} 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()} + pub fn compute_uma_pool(&self)->Arc{ + COMPUTE_UMA_POOL.with(|p|{ + let mut p = p.borrow_mut(); + p.get_or_insert_with(||super::resources::ComputeUmaPool::new().unwrap()).clone() + }) + } } 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())};} @@ -2392,7 +2401,7 @@ def module(text, name): assert_eq!(c1.qinfo.class, Class::FwCached); assert_eq!(c1.qstate.class, Class::Fw); assert_eq!(c1.ring.class, Class::FwCoherent); - assert_eq!(c1.fw_stamp.class, Class::Shared); + assert_eq!(c1.fw_stamp.class, Class::FwCached); assert_eq!(c.qinfo.class, Class::FwCached); assert_eq!(c.qscratch.class, Class::FwCached); assert_eq!(c.job_list.class, Class::FwCached); @@ -2402,7 +2411,7 @@ def module(text, name): assert_eq!(c.threshold.class, Class::Fw); assert_eq!(c.ring.class, Class::FwCoherent); assert_eq!(c.user_stamp.class, Class::Shared); - assert_eq!(c.fw_stamp.class, Class::Shared); + assert_eq!(c.fw_stamp.class, Class::FwCached); for stage in 0..2 { assert_eq!(r.qinfo[stage].class, Class::FwCached); assert_eq!(r.qscratch[stage].class, Class::FwCached); @@ -3643,7 +3652,11 @@ def module(text, name): .unwrap(); s.hold_compute_slot(ka, &vm_a, &prep_a).unwrap(); s.publish(&mut ca).unwrap(); + uma_a.uma_lease.publish(); s.quarantine(&mut ca); + assert!(!uma_a.uma_lease.settled(), "aborted UMA lease must never recycle"); + assert_eq!(uma_a.descriptor.class, g16::object::Class::FwCoherent); + assert_eq!(uma_a.counter.class, g16::object::Class::Fw); let qmask = s.quarantined_compute_uma_mask(); assert_eq!(qmask, 1u32 << 0); assert!(s.compute_uma_quarantined(1u32 << 0)); @@ -3685,7 +3698,13 @@ def module(text, name): ); s.hold_compute_slot(kb1, &vm_b, &prep_b).unwrap(); s.publish(&mut cb1).unwrap(); + uma_b1.uma_lease.publish(); s.retire(&mut cb1).unwrap(); + uma_b1.uma_lease.retire(); + assert!(uma_b1.uma_lease.settled(), "cleanly retired UMA lease settles for reuse"); + let desc_a_va = uma_a.descriptor.va; + let desc_b0_va = uma_b0.descriptor.va; + let desc_b1_va = uma_b1.descriptor.va; let lease_b1 = uma_b1.uma_lease.clone(); // Exhausting pool_va_idx >= COMPUTE_UMA_WINDOWS returns EIO. assert!( @@ -3705,9 +3724,27 @@ def module(text, name): drop(uma_b0); drop(occ_b1); assert_eq!(users[s2].load(Ordering::Acquire), 0); - assert_eq!(sync::Arc::strong_count(&lease_b1), 2, "retired FwLease retained"); + assert_eq!(sync::Arc::strong_count(&lease_b1), 2, "retired ComputeUmaLease retained"); + drop(lease_b1); drop(s); drop(uma_a); + // Once every holder of cleanly settled ComputeUmaLeases drops, the pool recycles + // both settled FwCoherent descriptors and never recycles the aborted one (`desc_a_va`). + let vm_c = vm(2003); + let vm_d = vm(2004); + let (bind_c, live_c, _) = g16::vm::test_live_token(); + let (bind_d, live_d, _) = g16::vm::test_live_token(); + let uma_c = SharedComputeUma::new(&factory, &bind_c, &vm_c.vm, &live_c, s2, 0).unwrap(); + let uma_d = SharedComputeUma::new(&factory, &bind_d, &vm_d.vm, &live_d, s2, 0).unwrap(); + let (vc, vd) = (uma_c.descriptor.va, uma_d.descriptor.va); + drop(bind_c); + drop(bind_d); + drop(uma_c); + drop(uma_d); + assert_eq!(vc, desc_b0_va, "first settled FwCoherent descriptor recycled"); + assert_eq!(vd, desc_b1_va, "second settled FwCoherent descriptor recycled"); + assert_ne!(vc, desc_a_va); + assert_ne!(vd, desc_a_va); } } @@ -3805,7 +3842,29 @@ def module(text, name): assert alloc_private_in_fn.index('self.uat.kernel_lower_vm().map_in_range(') < alloc_private_in_fn.index('self.uat.kernel_vm().map_in_range('), 'alloc_private_in must map uncached aliases before firmware aperture' 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' + 'use core::sync::atomic::AtomicBool;\n' + + item(resources_source, 'pub(crate) struct ComputeUmaRecordSet {') + + '\n' + + item(resources_source, 'impl ComputeUmaRecordSet {') + + '\n' + + item(resources_source, 'struct ComputeUmaEntry {') + + '\n' + + 'pub(crate) struct ComputeUmaPool { entries: crate::sync::Mutex>> }\n' + + 'impl ComputeUmaPool {\n' + + ' pub(crate) fn new() -> Result> {\n' + + ' crate::sync::Arc::new(Self { entries: crate::sync::Mutex::new(KVec::new()) }, 0)\n' + + ' }\n' + + item(resources_source, 'pub(crate) fn take(&self, factory: &Factory) -> Result<(Arc, bool)> {') + + '\n}\n' + + item(resources_source, 'pub(crate) struct ComputeUmaLease {') + + '\n' + + item(resources_source, 'impl ComputeUmaLease {') + + '\n' + + item(resources_source, 'impl core::ops::Deref for ComputeUmaLease {') + + '\n' + + item(resources_source, 'impl Drop for ComputeUmaLease {') + + '\n' + + 'pub(crate) struct SharedComputeUma(crate::cleanup::Deferred);\n' + item(resources_source, 'impl core::ops::Deref for SharedComputeUma {') + '\n' + item(resources_source, 'pub(crate) struct SharedComputeUmaInner {') 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 864b6a71d0834..2e8d616c04f56 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 @@ -156,9 +156,10 @@ def function(text, name): f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(n+1))); f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,9); assert_eq!(f.retired(),Ok(Retirement::Full)); - f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(n-1))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(n-1))); assert_eq!(f.retired(),Ok(Retirement::Pending)); - f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(n))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(n))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_CONTEXT,2); assert_eq!(f.retired(),Ok(Retirement::Full)); f.queue_passed=false;assert_eq!(f.retired(),Ok(Retirement::Pending)); f.queue_passed=true;f.engine.flights[0].job.resources.compute[0].descriptor.set(manager::COMPLETED,n-1); @@ -233,7 +234,7 @@ def function(text, name): for stage in 0..2 { f2.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(40))); } f2.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(40))); f2.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(40))); - f2.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + f2.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(29))); assert_eq!(f2.retired_flight(),Ok(Some((1,Retirement::Full)))); } #[test]fn multi_compute_horizon_requires_every_claimed_unit_receipt(){ @@ -273,9 +274,9 @@ def function(text, name): // Render-only retirement performs zero compute WC reads. let mut fr=firmware(true,5); assert_eq!(fr.retired_flight(),Ok(Some((0,Retirement::Full)))); - assert_eq!(fr.graph.compute[0].fw_stamp.reads.get(),0); assert_eq!(fr.graph.compute[0].notifier.reads.get(),0); - assert_eq!(fr.graph.compute[1].fw_stamp.reads.get(),0); + assert_eq!(fr.graph.compute[0].notifier.reads.get(),0); + assert_eq!(fr.graph.compute[1].notifier.reads.get(),0); assert_eq!(fr.graph.compute[1].notifier.reads.get(),0); // In-progress render (TA done, FS still running) fails fast on FS stamp without reading TA or scene. let mut fp=firmware(true,7); @@ -292,9 +293,9 @@ def function(text, name): // Mixed flight pending is polled once, not twice. let mut fm=firmware(false,9); fm.engine.flights[0].renders=1; - fm.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(8))); + fm.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(8))); assert_eq!(fm.retired_flight(),Ok(None)); - assert_eq!(fm.graph.compute[0].fw_stamp.reads.get(),1); + assert_eq!(fm.graph.compute[0].notifier.reads.get(),1); assert_eq!(fm.graph.render.fw_stamp[1].reads.get(),0); // Pending compute class is not re-polled while retiring a burst of render flights. let mut fmix=firmware(false,30); @@ -307,7 +308,7 @@ def function(text, name): for stage in 0..2 { fmix.graph.render.fw_stamp[stage].set(0,u64::from(encode::stamp(41))); } fmix.graph.render.notifier.set(notifier_page::TA_STAMP,u64::from(encode::stamp(41))); fmix.graph.render.notifier.set(notifier_page::FS_STAMP,u64::from(encode::stamp(41))); - fmix.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + fmix.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(29))); let (mut check_c,mut check_r)=([true;hw::sizes::COMPUTE_PIPES],true); assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); assert!(!check_c[0] && !check_c[1] && check_r); @@ -315,7 +316,7 @@ def function(text, name): assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(Some((1,Retirement::Full)))); fmix.engine.flights.remove(1); assert_eq!(fmix.retired_flight_classes(&mut check_c,&mut check_r),Ok(None)); - assert_eq!(fmix.graph.compute[0].fw_stamp.reads.get(),1); + assert_eq!(fmix.graph.compute[0].notifier.reads.get(),1); } #[test]fn innocent_suspect_flight_does_not_false_abort_after_recovery_grace(){ let mut f=firmware(true,15); @@ -446,7 +447,7 @@ def function(text, name): f.engine.flights.push(c1); f.engine.target[0]=encode::stamp(10);f.engine.target[1]=encode::stamp(11); f.channels.compute_producer=2; - f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(9))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(9))); f.graph.compute[1].fw_stamp.set(0,u64::from(encode::stamp(11))); f.graph.compute[1].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(11))); f.graph.compute[1].notifier.set(notifier_page::COMPUTE_CONTEXT,2); @@ -456,7 +457,7 @@ def function(text, name): assert_eq!(f.retired_flight(),Ok(None)); // Now finish pipe 0: rec[2]=1 != producer=2 still sets chan_behind=true. f.last_chan_passed.set(None); - f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(10))); + f.graph.compute[0].notifier.set(notifier_page::COMPUTE_STAMP,u64::from(encode::stamp(10))); assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); assert_eq!(f.last_chan_passed.get(),Some(true)); } @@ -713,19 +714,18 @@ def function(text, name): 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. + // With only flight 0 left (`last_vm_flight == true`), `needed == 1 != counter == 2` + // (retired == 0, count == 1, counter == 2) MUST reject so an unretired command cannot be + // missed before the VM drains idle. f.engine.flights.pop(); assert_eq!(f.retired_at(0),Ok(Retirement::Pending)); - // Advancing `retired == 1` (`needed == 2 > COMPLETED == 1`) also stays Pending. + // Advancing `retired == 1` (`needed == 2 == counter == 2`) retires Full without reading + // the ASC-cached descriptor from the host. 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.engine.flights[0].job.resources.compute_uma.as_ref().unwrap().descriptor.reads.get(),0); + // Counter lagging behind `needed` stays Pending. + f.engine.flights[0].job.resources.compute_uma.as_mut().unwrap().counter.set(0,1); assert_eq!(f.retired_at(0),Ok(Retirement::Pending)); } From 1de4e8f8751d06a0bf7d16842db69d25ab079432 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 23:37:14 -0500 Subject: [PATCH 3/7] drm/asahi: g16: document the wider flight limit Document the 64-flight limit and format the layout assertions. The reported per-queue limit rises from 32 to 64. Compute completion uses the uncached service stamp so progress and retirement do not depend on CPU reads of cached firmware records. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/hw.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 3bfce1673a9d2..7ac346e2a8567 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -1191,7 +1191,7 @@ pub(crate) mod sizes { /// queue/recovery capacities: `47` in-flight passes consume at most `47 * 4 = 188` entries of /// each 256-entry TA/FS work ring (`QUEUE_CAP = 256`, 255 usable, ring cap `63`), use /// per-allocator hardware UMA slots `RENDER_UMA_SLOT + slot` (`33..38`, strictly inside the - /// firmware render slot range `33..64`), post at most `FLIGHTS = 32` `SubmitRecord`s (vs + /// firmware render slot range `33..64`), post at most `FLIGHTS = 64` `SubmitRecord`s (vs /// `AHEAD_RECORDS = 128` / `RING_SLOTS = 256`), and stay far below the firmware recovery /// `snapshot_entries = 448` limit. pub(crate) const RENDER_SLOTS: usize = 48; @@ -1241,16 +1241,14 @@ pub(crate) mod sizes { const _: () = assert!(COMPUTE_UMA_SLOTS == 32); const _: () = assert!(COMPUTE_UNITS >= 2 && COMPUTE_UNITS <= 64); const _: () = assert!((COMPUTE_UNITS - 1) * MAX_COMPUTE_RING_ENTRIES < QUEUE_CAP as usize); - const _: () = assert!( - super::client::compute_list(2) + 0x4000 <= super::client::compute_base(3) - ); + const _: () = + assert!(super::client::compute_list(2) + 0x4000 <= super::client::compute_base(3)); const _: () = assert!( super::client::compute_base(COMPUTE_UMA_WINDOWS as u64) <= super::client::EXT_COMPUTE_REC_BASE ); - const _: () = assert!( - super::client::compute_context(2) + 0x40000 <= super::client::compute_preempt(3) - ); + const _: () = + assert!(super::client::compute_context(2) + 0x40000 <= super::client::compute_preempt(3)); const _: () = assert!( super::client::compute_context(COMPUTE_UNITS as u64 - 1) + 0x40000 <= super::client::scs_compute_records(0) From eb8c98e615c07405c59bf1b2517bb240c34fe1c8 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Wed, 2 Dec 2026 20:03:44 -0500 Subject: [PATCH 4/7] drm/asahi: g16: keep a stage witness for suspect compute flights With compute fw_stamp ASC-cached, retirement gates compute on the service stamp alone. A flight that a GPU recovery aborted can keep a stale service stamp: it then stays pending for good, never reaches the abort grace, and the administrative deadline fail-stops the GPU for every client. Before this branch, the uncached fw_stamp gated retirement and the stale service stamp led to the abort. Do what suspect renders do. Allocate compute fw_stamp as a device-lifetime FwCoherent object, the class render fw_stamp[1] already has, and let a suspect flight whose service stamp is stale sync and check it. A still running suspect stays pending, a passed one starts the abort grace, and a full receipt still needs the service stamp. Other flights never read fw_stamp, as before. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/graph.rs | 2 +- drivers/gpu/drm/asahi/g16/poll.rs | 61 +++++++----- .../drivers/gpu/asahi-m4/test-publication.py | 2 +- .../drivers/gpu/asahi-m4/test-resources.py | 8 +- .../drivers/gpu/asahi-m4/test-stamp-wrap.py | 97 +++++++++++++++++++ 5 files changed, 141 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 657fcda25cfea..c250298e4a7c5 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -256,7 +256,7 @@ impl ComputeGraphSession { notifier: alloc(o, 0x1000, Class::FwCached, None, 0, false)?, threshold: alloc(o, 24, Class::Fw, None, 0, false)?, job_list: alloc(o, job_list::SIZE, graph_fw(), None, 0, false)?, - q: QueueSession::new_with(o, Some(Class::FwCached))?, + q: QueueSession::new_with(o, None)?, }) } fn finish(self, rings: &mut Objects, sched_ctx: Arc) -> Result { diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 99614a8d510df..d6f9170b10bf0 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1321,35 +1321,48 @@ impl Firmware { .is_some() || f.rec[2] != self.channels.producer(Channel::Compute); let g = &self.graph.compute[pipe]; - // Compute `fw_stamp` is ASC-cached (`FwCached`), matching macOS 26B123; the host - // checks the uncached compute service stamp (`user_stamp`) that firmware stores - // strictly after updating `fw_stamp` and completing work-item, microsequence, and UMA - // accesses. - if pipe_behind { - let tail = self.engine.target[pipe]; - if !stamp_reached(g.service_stamp().read()?, f.target, tail) - || !self.queue_ring_passed(Channel::Compute, &g.qstate, &g.qinfo, f)? - || !(f.chan_settled - || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) - { + let tail = self.engine.target[pipe]; + let reached = |stamp: u32| { + if pipe_behind { + stamp_reached(stamp, f.target, tail) + } else { + stamp == f.target + } + }; + // Compute `fw_stamp` is ASC-cached (`FwCoherent`), matching macOS 26B123. Normal + // flights fail fast on the uncached compute service stamp (`user_stamp`) and never + // read it. The service stamp alone authenticates the receipt: its target is this + // pipe's own ordinal, and the firmware stores it only after updating `fw_stamp` and + // after its last access to the command's work item, microsequence and UMA + // descriptor. The cached notifier record's context word is written back only when + // the record is unlinked, so the host cannot read it reliably. A command a recovery + // aborted may never get its service stamp: a suspect flight whose service stamp is + // stale syncs and checks `fw_stamp` as an independent stage witness, as suspect + // renders do below, so that it reaches the abort grace once its stage and queues + // passed, and not while it still runs. + let served = reached(g.service_stamp().read()?); + if !served { + if !f.recovery_suspect { return Ok(Retirement::Pending); } - // The service stamp alone authenticates the receipt: its target is this pipe's - // own ordinal, and the firmware stores it only after its last access to the - // command's work item, microsequence and UMA descriptor. The cached notifier - // record's context word is written back only when the record is unlinked, so - // the host cannot read it reliably. - rmb(); - } else { - if g.service_stamp().read()? != f.target - || !self.queue_ring_receipt(&g.qstate, &g.qinfo, f.head)? - || !(f.chan_settled - || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) - { + g.fw_stamp.sync_for_cpu(0, 4)?; + if !reached(g.fw_stamp.r32(0)?) { return Ok(Retirement::Pending); } - rmb(); } + let ring = if pipe_behind { + self.queue_ring_passed(Channel::Compute, &g.qstate, &g.qinfo, f)? + } else { + self.queue_ring_receipt(&g.qstate, &g.qinfo, f.head)? + }; + if !ring + || !(f.chan_settled + || self.channel_receipt(Channel::Compute, f.rec[2], chan_behind)?) + { + return Ok(Retirement::Pending); + } + rmb(); + full &= served; let count = f.claims.slot_count as usize; full &= count != 0 && count == f.computes as usize; if full { 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 8bd2883ea5154..d69d9764038d4 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -130,7 +130,7 @@ def item(declaration): assert va not in source, va assert source.count('user_stamp: g.service_stamp().va(),') == 1 assert source.count('user_stamp: [r.ta_service_stamp().va(), r.fs_service_stamp().va()],') == 2 -assert poll_src.count('g.service_stamp().read()?') == 2 +assert poll_src.count('g.service_stamp().read()?') == 1 assert poll_src.count('g.fs_service_stamp().read()?') == 2 assert poll_src.count('g.ta_service_stamp().read()?') == 2 # Cross-pipe compute->compute barriers wait on the producer pipe's service stamp as well. 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 f5ae30b68cb3d..3301fb6199e12 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -934,12 +934,14 @@ def module(text, name): let rg = RenderGraph::new(&mut session, &mut rings, ctx).unwrap(); let all_persistent = [ &cg0.ring, + &cg0.fw_stamp, &cg1.ring, + &cg1.fw_stamp, &rg.ring[0], &rg.ring[1], &rg.fw_stamp[1], ]; - assert_eq!(rings.objects.len(), 5); + assert_eq!(rings.objects.len(), 7); assert_eq!(rg.fw_stamp[0].class, Class::Shared); for obj in all_persistent { assert_eq!(obj.class, Class::FwCoherent); @@ -2595,7 +2597,7 @@ def module(text, name): assert_eq!(c1.qinfo.class, Class::FwCached); assert_eq!(c1.qstate.class, Class::Fw); assert_eq!(c1.ring.class, Class::FwCoherent); - assert_eq!(c1.fw_stamp.class, Class::FwCached); + assert_eq!(c1.fw_stamp.class, Class::FwCoherent); assert_eq!(c.qinfo.class, Class::FwCached); assert_eq!(c.qscratch.class, Class::FwCached); assert_eq!(c.job_list.class, Class::FwCached); @@ -2605,7 +2607,7 @@ def module(text, name): assert_eq!(c.threshold.class, Class::Fw); assert_eq!(c.ring.class, Class::FwCoherent); assert_eq!(c.user_stamp.class, Class::Shared); - assert_eq!(c.fw_stamp.class, Class::FwCached); + assert_eq!(c.fw_stamp.class, Class::FwCoherent); for stage in 0..2 { assert_eq!(r.qinfo[stage].class, Class::FwCached); assert_eq!(r.qscratch[stage].class, Class::FwCached); 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 27ee33bed7b93..b63bcc2747c05 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 @@ -548,6 +548,103 @@ def function(text, name): assert_eq!(ok.graph.render[0].fw_stamp[0].syncs.get(),0); assert_eq!(ok.graph.render[0].fw_stamp[1].syncs.get(),0); } +#[test]fn suspect_compute_with_passed_queues_and_stale_service_stamp_aborts_after_grace(){ + // Single suspect compute: stage stamp and queue receipts passed, service stamp still stale. + let mut f=firmware(false,23); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + f.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(22))); + CLOCK.with(|c| c.set(100_000_000)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + assert_eq!(f.engine.flights[0].gate_passed_ns,Some(100_000_000)); + assert_eq!(f.engine.flights[0].unsettled_polls,1); + assert!(f.graph.compute[0].fw_stamp.syncs.get()>=1); + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS - 1)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS)); + assert_eq!(f.retired(),Ok(Retirement::Aborted)); + assert!(f.engine.flights[0].doomed); + + // Same suspect compute when the queue has NOT passed stays Pending and never starts the grace. + let mut q=firmware(false,24); + q.engine.flights[0].recovery_suspect=true; + q.engine.flights[0].recovery_started_ns=10_000_000; + q.queue_passed=false; + q.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(23))); + CLOCK.with(|c| c.set(100_000_000)); + assert_eq!(q.retired(),Ok(Retirement::Pending)); + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS * 2)); + assert_eq!(q.retired(),Ok(Retirement::Pending)); + assert!(!q.engine.flights[0].doomed); + assert_eq!(q.engine.flights[0].gate_passed_ns,None); + + // Innocent suspect compute whose stale service stamp settles within the grace retires Full. + let mut s=firmware(false,25); + s.engine.flights[0].recovery_suspect=true; + s.engine.flights[0].recovery_started_ns=10_000_000; + s.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(24))); + CLOCK.with(|c| c.set(100_000_000)); + assert_eq!(s.retired(),Ok(Retirement::Pending)); + assert_eq!(s.engine.flights[0].gate_passed_ns,Some(100_000_000)); + CLOCK.with(|c| c.set(100_500_000)); + s.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(25))); + assert_eq!(s.retired(),Ok(Retirement::Full)); + assert!(!s.engine.flights[0].doomed); + + // Pipelined suspect compute (a later flight on the same pipe) aborts the same way. + let mut b=firmware(false,26); + b.engine.flights[0].recovery_suspect=true; + b.engine.flights[0].recovery_started_ns=10_000_000; + let later=firmware(false,27).engine.flights.remove(0); + b.engine.flights.push(later); + b.engine.target[0]=encode::stamp(27); + b.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(25))); + CLOCK.with(|c| c.set(100_000_000)); + assert_eq!(b.retired(),Ok(Retirement::Pending)); + assert_eq!(b.engine.flights[0].gate_passed_ns,Some(100_000_000)); + assert!(b.graph.compute[0].fw_stamp.syncs.get()>=1); + CLOCK.with(|c| c.set(100_000_000 + ABORT_GRACE_NS)); + assert_eq!(b.retired(),Ok(Retirement::Aborted)); + assert!(b.engine.flights[0].doomed); +} +#[test]fn suspect_compute_with_unreached_stage_and_stale_service_stamp_stays_pending(){ + // Queues passed, but BOTH the stage stamp and the service stamp are one target behind: a + // still-running suspect compute never arms the abort grace. + for behind in [false,true] { + let mut f=firmware(false,28); + f.engine.flights[0].recovery_suspect=true; + f.engine.flights[0].recovery_started_ns=10_000_000; + if behind { + let later=firmware(false,29).engine.flights.remove(0); + f.engine.flights.push(later); + f.engine.target[0]=encode::stamp(29); + } + f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(27))); + f.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(27))); + for now in [100_000_000,100_000_000 + ABORT_GRACE_NS] { + CLOCK.with(|c| c.set(now)); + assert_eq!(f.retired(),Ok(Retirement::Pending)); + assert!(!f.engine.flights[0].doomed); + assert_eq!(f.engine.flights[0].gate_passed_ns,None); + assert_eq!(f.engine.flights[0].unsettled_polls,0); + } + assert!(f.graph.compute[0].fw_stamp.syncs.get()>=2); + } + // A compute that is no suspect never reads or syncs the ASC-cached stage stamp, served or not, + // and a suspect whose service stamp settled retires Full even if the stage stamp lags. + let mut n=firmware(false,30); + n.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(29))); + assert_eq!(n.retired(),Ok(Retirement::Pending)); + n.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(30))); + assert_eq!(n.retired(),Ok(Retirement::Full)); + n.engine.flights[0].recovery_suspect=true; + n.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + assert_eq!(n.retired(),Ok(Retirement::Full)); + assert_eq!(n.graph.compute[0].fw_stamp.syncs.get(),0); + assert_eq!(n.graph.compute[0].fw_stamp.reads.get(),0); +} #[test]fn same_tick_stage_timestamps_retire_full_while_zero_or_reversed_stay_pending(){ // 24 MHz (41.67 ns) stage timestamps can legitimately record end == start on tiny draws // or dispatches; accept end >= start while still rejecting 0 or reversed intervals. From 532944a865ddcea001ecb871d349ebc37bbe17f3 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 3 Dec 2026 01:57:14 -0500 Subject: [PATCH 5/7] drm/asahi: g16: bind a VM to its TTBAT slot with its first queue A user VM takes one of the 63 TTBAT slots when it is created and keeps it until its last firmware lease goes. A Vulkan client creates two VMs: its physical device's, which never gets a queue, and its logical device's. So the slots run out at half as many clients as the contexts could serve. Slots are short to begin with. The newest retired compute owner of every pipe, the newest render owner, and the owner epoch of every PB slot keep their VM bound after its client exits, until a later publication displaces them. With eight compute pipes and twenty PB slots that is up to 29 slots of clients that are gone. On a J773g desktop with gpubench compute.light procs running, 21 of the 63 slots were held like that and 9 by the desktop, which left room for 16 Vulkan processes and nothing more. With the sixteen pipes of linux#3340, 29 were, and VM_CREATE failed with ENOSPC. Those leases have to stay: releasing a closed VM's PB epoch early let the parameter manager write through a reused context (047b934ce47a). But only the jobs of a queue run in a VM's context, so a VM without one needs no slot. Keep it unbound in the registry and bind it when its first queue is created. Its root is named by the TTBAT only then, with every mapping made before it already visible to the walker. Slots stay exclusive and are reserved before they are bound, as before, so a leased slot is still never handed out again and the slot allocator never waits. A failed binding leaves the VM unbound for another try. The per-file limit of eight VMs still counts every VM, bound or not. The device limit and the per-process share count bound VMs, so running out of slots is now ENOSPC from QUEUE_CREATE rather than from VM_CREATE. The fail-stop path also latches its error on unbound VMs. test-vm-slots.py runs the production VM and queue creation against a model of the slots, with the pipe and PB slot counts of hw.rs: every lease held by an exited client, the desktop, then sixteen Vulkan processes. Without this change the thirteenth process fails there, and the ninth with sixteen pipes. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/vm.rs | 223 +++++++--- .../drivers/gpu/asahi-m4/test-resources.py | 9 +- .../drivers/gpu/asahi-m4/test-vm-registry.py | 41 +- .../drivers/gpu/asahi-m4/test-vm-slots.py | 402 ++++++++++++++++++ 4 files changed, 594 insertions(+), 81 deletions(-) create mode 100644 tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-slots.py diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 9546f47c30045..04fbe1d15164f 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -10,11 +10,18 @@ //! ([`object::Objects::clients`]) as driver mappings at their fixed GVAs, and reserve //! [`super::hw::client::CLIENT_APERTURE`], the pass-slot range and the PB page list //! (`vm.install_driver_mappings`): user binds there fail (EINVAL); +//! - keep it unbound ([`IdleVm`]) until its client creates a queue. +//! +//! With the VM's first queue ([`lookup`]): +//! //! - bind it to an exclusive TTBAT slot ([`mmu::Uat::bind`]) for as long as its [`VmState`] //! lives; at most [`super::hw::sizes::MAX_VMS`] such VMs (ENOSPC beyond, checked before //! binding so the slot allocator never blocks), shared between processes as the queues are //! ([`crate::queue_share::Shares`]), since a process may open the device many times. //! +//! Only a queue's jobs run in a VM's context, so a VM without one needs no slot: a Vulkan +//! client opens one such VM for its physical device beside the VM its logical device uses. +//! //! The [`VmState`] of a VM is shared by the [`Registry`] (while the client's VM handle exists), //! the VM's queues and its jobs. It cannot be owned by the [`mmu::Vm`] itself: the slot binding //! holds a `Vm` reference. The registry drops its reference once the shared lifetime reports the @@ -34,6 +41,7 @@ use kernel::{ drm::gem::BaseObject, new_mutex, prelude::*, + rbtree::{RBTree, RBTreeNode}, sync::{aref::ARef, Arc, Mutex, UniqueArc}, }; @@ -133,7 +141,7 @@ pub(crate) struct VmStateInner { /// The VM: span checks, stream reads and job guards. pub(crate) vm: mmu::Vm, /// Private mappings are kept outside generic close's user GPUVA teardown. - context_mappings: KVec, + context_mappings: Option>>, pub(crate) resources: Option>, #[allow(dead_code)] pub(crate) live: Arc, @@ -152,33 +160,61 @@ impl Drop for VmStateInner { fn drop(&mut self) { mod_pr_debug!("G16: VM {} releases context {}\n", self.id, self.slot); drop(self.resources.take()); - self.context_mappings.clear(); + drop(self.context_mappings.take()); } } -/// Count a VM until every deferred arena has unmapped and released its binding. +/// Count a bound VM until every deferred arena has unmapped and released its binding. pub(crate) struct LiveToken { registry: Arc, bind: Option, - file_id: u64, + _place: Arc, process: usize, } impl Drop for LiveToken { fn drop(&mut self) { drop(self.bind.take()); - self.registry.release(self.file_id, self.process); + self.registry.release(self.process); + } +} + +/// One of its file's VMs, counted until the VM is closed and, if it was bound, every deferred +/// arena has unmapped. +pub(crate) struct FilePlace { + registry: Arc, + file_id: u64, +} +impl Drop for FilePlace { + fn drop(&mut self) { + self.registry.leave(self.file_id); } } -/// Live-VM accounting and the VMs whose client handle is open. +/// A VM whose client has created no queue yet. Nothing runs in its context, so it holds no TTBAT +/// slot; [`lookup`] binds it for its first queue. +struct IdleVm { + vm: mmu::Vm, + status: Arc, + mappings: Arc>, + place: Arc, +} + +/// VM accounting and the VMs whose client handle is open. #[pin_data] pub(crate) struct Registry { - /// VMs whose client handle may still be open, oldest first. + /// Bound VMs whose client handle may still be open, oldest first. #[pin] vms: Mutex>>, + /// VMs without a queue, by identifier. Its nodes are allocated before taking the lock, + /// which `fail_all()` takes under the device lock. + #[pin] + idle: Mutex>, + /// Serializes the binding of VMs ([`lookup`]): a VM is bound once. + #[pin] + binding: Mutex<()>, /// Live [`VmState`]s (each holds a TTBAT slot) plus reservations being created. live: AtomicU32, - /// Includes deferred/retained bindings after the file handle closes. + /// The VMs of each file. Includes deferred/retained bindings after the file handle closes. #[pin] files: Mutex>, /// The live VMs counted per creating process; taken under `files`. @@ -186,8 +222,8 @@ pub(crate) struct Registry { processes: Mutex, } -/// A reserved place among the live VMs, released unless a [`VmState`] takes it over. -struct Reservation<'a>(Option<&'a Registry>, u64, usize); +/// A reserved TTBAT slot among the live VMs, released unless a [`VmState`] takes it over. +struct Reservation<'a>(Option<&'a Registry>, usize); impl Reservation<'_> { fn into_state(mut self) { @@ -198,7 +234,7 @@ impl Reservation<'_> { impl Drop for Reservation<'_> { fn drop(&mut self) { if let Some(registry) = self.0 { - registry.release(self.1, self.2); + registry.release(self.1); } } } @@ -210,6 +246,8 @@ impl Registry { Arc::pin_init( pin_init!(Self { vms <- new_mutex!(vms, "g16::Registry::vms"), + idle <- new_mutex!(RBTree::new(), "g16::Registry::idle"), + binding <- new_mutex!((), "g16::Registry::binding"), live: AtomicU32::new(0), files <- new_mutex!(files, "g16::Registry::files"), processes <- new_mutex!(crate::queue_share::Shares::new(), @@ -219,8 +257,40 @@ impl Registry { ) } - /// Reserves a place for a new VM after dropping the registry's references to closed VMs. - fn reserve(&self, file_id: u64) -> Result> { + /// Counts a new VM against its file. + fn admit(registry: &Arc, file_id: u64) -> Result> { + // The place gives its count back when dropped, so allocate it before counting. + let place = UniqueArc::::new_uninit(GFP_KERNEL)?; + { + let mut files = registry.files.lock(); + match files.iter().position(|(id, _)| *id == file_id) { + Some(index) if files[index].1 >= MAX_VMS_PER_FILE => return Err(ENOSPC), + Some(index) => files[index].1 += 1, + None => files.push((file_id, 1), GFP_NOWAIT)?, + } + } + Ok(place + .write(FilePlace { + registry: registry.clone(), + file_id, + }) + .into()) + } + + /// Takes a VM off its file's count. + fn leave(&self, file_id: u64) { + let mut files = self.files.lock(); + if let Some(index) = files.iter().position(|(id, _)| *id == file_id) { + files[index].1 -= 1; + if files[index].1 == 0 { + let _ = files.remove(index); + } + } + } + + /// Reserves a TTBAT slot for a VM's first queue after dropping the registry's references to + /// closed VMs. + fn reserve(&self) -> Result> { self.prune(); // The shared slot allocator hands out a single slot with robust isolation. let limit = if module_parameters::robust_isolation.value() != 0 { @@ -236,45 +306,18 @@ impl Registry { let rollback = kernel::types::ScopeGuard::new(|| { self.live.fetch_sub(1, Ordering::AcqRel); }); - let process = { - let mut files = self.files.lock(); - let index = match files.iter().position(|(id, _)| *id == file_id) { - Some(index) if files[index].1 >= MAX_VMS_PER_FILE => return Err(ENOSPC), - Some(index) => index, - None => { - files.push((file_id, 0), GFP_NOWAIT)?; - files.len() - 1 - } - }; - match self.processes.lock().take_current(limit, GFP_NOWAIT) { - Ok(process) => { - files[index].1 += 1; - process - } - Err(error) => { - if files[index].1 == 0 { - let _ = files.remove(index); - } - // The share refusing is "no room"; a failed allocation stays ENOMEM. - return Err(if error == EBUSY { ENOSPC } else { error }); - } - } - }; + let process = self + .processes + .lock() + .take_current(limit, GFP_NOWAIT) + // The share refusing is "no room"; a failed allocation stays ENOMEM. + .map_err(|error| if error == EBUSY { ENOSPC } else { error })?; rollback.dismiss(); - Ok(Reservation(Some(self), file_id, process)) + Ok(Reservation(Some(self), process)) } - fn release(&self, file_id: u64, process: usize) { - let gone = { - let mut files = self.files.lock(); - if let Some(index) = files.iter().position(|(id, _)| *id == file_id) { - files[index].1 -= 1; - if files[index].1 == 0 { - let _ = files.remove(index); - } - } - self.processes.lock().give_back(process) - }; + fn release(&self, process: usize) { + let gone = self.processes.lock().give_back(process); // Drops the process's mm reference outside the registry locks. drop(gone); self.live.fetch_sub(1, Ordering::AcqRel); @@ -283,6 +326,9 @@ impl Registry { /// Drop the handle owner immediately, outside the registry lock. Other references /// still protect jobs, both hardware units' last owners, and deferred destruction. pub(crate) fn close(&self, id: u64) { + // A VM that never had a queue: its mappings go here, outside the registry locks. + let idle = self.idle.lock().remove_node(&id); + drop(idle); let state = { let mut vms = self.vms.lock(); let index = vms.iter().position(|state| state.id == id); @@ -387,6 +433,9 @@ impl Registry { /// Latches `error` on every VM whose client handle is open. The fail-stop path calls it under /// the device lock. pub(crate) fn fail_all(&self, error: Error) { + for idle in self.idle.lock().values() { + idle.status.record(error); + } for state in self.vms.lock().iter() { state.status.record(error); } @@ -399,7 +448,7 @@ pub(crate) fn reserved_ranges() -> [Range; 2] { [0x1000000000..0x1000010000, 0x7000000000..0x7100000000] } -/// Creates a user VM (`gpu::Gpu::new_vm`). +/// Creates a user VM (`gpu::Gpu::new_vm`), unbound until its first queue. /// /// Kernel memory sized by the VM's client (its private arenas) is charged to `memory`. pub(crate) fn new_vm( @@ -414,13 +463,13 @@ pub(crate) fn new_vm( // Reserve outside the device lock: reclaim may wait for a fence whose poller needs it. let mut aliases = KVec::with_capacity(hw::sizes::MAX_CLIENT, GFP_KERNEL)?; // Snapshot only references and metadata under the device lock; map after releasing it. - let (registry, factory) = { + let registry = { let state = gpu.shared.state.lock(); let firmware = state.as_ref().ok_or(ENODEV)?; ClientAlias::collect(&firmware.objects, &mut aliases)?; - (firmware.vms.clone(), firmware.private_factory.clone()) + firmware.vms.clone() }; - let reservation = registry.reserve(file_id)?; + let place = Registry::admit(®istry, file_id)?; let id = gpu.ids.vm.next(); let mut vm = gpu .uat @@ -430,7 +479,7 @@ pub(crate) fn new_vm( vm = vm.with_memory_client(memory); } // Driver mappings retain their VM. Break that ownership if any later step fails, - // including binding/state allocation and registry insertion. + // including registry insertion. let failed_vm = kernel::types::ScopeGuard::new_with_data(vm.clone(), |vm| { if let Err(error) = vm.unmap_user_ranges(hw::USER_RANGE.clone(), kernel_range) { pr_err!("G16: closing unpublished VM failed: {:?}\n", error); @@ -440,7 +489,41 @@ pub(crate) fn new_vm( let status = vm.status().ok_or(EINVAL)?.clone(); let (mappings, reserved) = Registry::driver_mappings(&vm, aliases)?; vm.install_driver_mappings(KVec::new(), reserved)?; - // The context names the root only now: everything above is already visible to the walker. + let idle = IdleVm { + vm: vm.clone(), + status, + mappings: Arc::new(mappings, GFP_KERNEL)?, + place, + }; + let node = RBTreeNode::new(id, idle, GFP_KERNEL)?; + // Identifiers are never reused, so nothing is replaced. + let replaced = registry.idle.lock().insert(node); + drop(replaced); + drop(failed_vm.dismiss()); + Ok(vm) +} + +/// Binds the idle VM `vm` to a TTBAT slot for its first queue. The caller holds +/// [`Registry::binding`]; a failure leaves the VM idle. +fn bind_idle( + gpu: &Gpu, + registry: &Arc, + factory: object::Factory, + id: u64, +) -> Result> { + let (vm, status, mappings, place) = { + let idle = registry.idle.lock(); + let idle = idle.get(&id).ok_or(ENOENT)?; + ( + idle.vm.clone(), + idle.status.clone(), + idle.mappings.clone(), + idle.place.clone(), + ) + }; + let reservation = registry.reserve()?; + // The context names the root only now: the driver mappings and everything the client mapped + // so far are already visible to the walker. let bind = gpu.uat.bind(&vm)?; let slot = bind.slot(); let generation = bind.generation(); @@ -451,8 +534,8 @@ pub(crate) fn new_vm( .write(LiveToken { registry: registry.clone(), bind: Some(bind), - file_id, - process: reservation.2, + _place: place, + process: reservation.1, }) .into(); reservation.into_state(); @@ -468,21 +551,35 @@ pub(crate) fn new_vm( generation, status, vm: vm.clone(), - context_mappings: mappings, + context_mappings: Some(mappings), resources: Some(resources), live, }; let state = Arc::new(VmState(crate::cleanup::Deferred::new(inner)?), GFP_KERNEL)?; // Registry storage was bounded and preallocated at backend startup. NOWAIT also keeps // an invariant failure from entering reclaim under a lock required by fail_all(). - registry.vms.lock().push(state, GFP_NOWAIT)?; - drop(failed_vm.dismiss()); + registry.vms.lock().push(state.clone(), GFP_NOWAIT)?; + let idle = registry.idle.lock().remove_node(&id); + drop(idle); + // A close that found neither: the VM was closed before its state was pushed. + if vm.is_closed() { + registry.close(id); + return Err(ENOENT); + } mod_pr_debug!("G16: VM {} context {}\n", id, slot); - Ok(vm) + Ok(state) } /// The state of a VM for a new queue. pub(crate) fn lookup(gpu: &Gpu, vm: &mmu::Vm) -> Result> { - let registry = gpu.shared.state.lock().as_ref().ok_or(ENODEV)?.vms.clone(); - registry.find(vm) + let (registry, factory) = { + let state = gpu.shared.state.lock(); + let firmware = state.as_ref().ok_or(ENODEV)?; + (firmware.vms.clone(), firmware.private_factory.clone()) + }; + let _binding = registry.binding.lock(); + match registry.find(vm) { + Err(error) if error == ENOENT => bind_idle(gpu, ®istry, factory, vm.id()), + found => found, + } } 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..ddddbdbe690b3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -345,7 +345,7 @@ def module(text, name): let released = std::sync::Arc::new(AtomicBool::new(false)); let registry = Arc::new(Registry { live: live.clone() }, 0).unwrap(); let bind = mmu::VmBind { live, released: released.clone() }; - let token = Arc::new(LiveToken { registry, bind: Some(bind), file_id: 0, process: 0 }, 0).unwrap(); + let token = Arc::new(LiveToken { registry, bind: Some(bind), _place: Arc::new(FilePlace, 0).unwrap(), process: 0 }, 0).unwrap(); (Self { cache: Some(cache), _live: Some(token), ..Self::new() }, released) } pub fn is_closed(&self)->bool{self.closed.load(Ordering::Acquire)} @@ -360,7 +360,8 @@ def module(text, name): || self.vm.cache.as_ref().is_some_and(|cache| cache.renders_unpublished()) } } - pub struct Registry{pub live:std::sync::Arc}impl Registry{fn release(&self,_file:u64,_process:usize){self.live.fetch_sub(1,Ordering::AcqRel);}} + pub struct Registry{pub live:std::sync::Arc}impl Registry{fn release(&self,_process:usize){self.live.fetch_sub(1,Ordering::AcqRel);}} + pub struct FilePlace; __LIVE_TOKEN__ __LIVE_DROP__ pub fn test_live_token() -> (mmu::VmBind, Arc, std::sync::Arc) { @@ -368,14 +369,14 @@ def module(text, name): let released = std::sync::Arc::new(AtomicBool::new(false)); let registry = Arc::new(Registry { live: live.clone() }, 0).unwrap(); let bind = mmu::VmBind { live, released: released.clone() }; - let token = Arc::new(LiveToken { registry, bind: Some(bind.clone()), file_id: 0, process: 0 }, 0).unwrap(); + let token = Arc::new(LiveToken { registry, bind: Some(bind.clone()), _place: Arc::new(FilePlace, 0).unwrap(), process: 0 }, 0).unwrap(); (bind, token, released) } #[test]fn accounting_outlives_deferred_arenas_and_releases_binding_first(){ use std::sync::atomic::{AtomicU32,AtomicBool}; let count=std::sync::Arc::new(AtomicU32::new(1));let released=std::sync::Arc::new(AtomicBool::new(false)); let registry=Arc::new(Registry{live:count.clone()},0).unwrap(); - let token=Arc::new(LiveToken{registry,file_id:0,process:0,bind:Some(mmu::VmBind{live:count.clone(),released:released.clone()})},0).unwrap(); + let token=Arc::new(LiveToken{registry,_place:Arc::new(FilePlace,0).unwrap(),process:0,bind:Some(mmu::VmBind{live:count.clone(),released:released.clone()})},0).unwrap(); let deferred_arena=token.clone();drop(token); assert_eq!(count.load(Ordering::Acquire),1);assert!(!released.load(Ordering::Acquire)); drop(deferred_arena);assert!(released.load(Ordering::Acquire));assert_eq!(count.load(Ordering::Acquire),0); diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py index bd42929f117a4..ae51a0e690120 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py @@ -16,7 +16,7 @@ def item(marker,text=None): #![allow(dead_code,unused_variables,non_upper_case_globals)] extern crate self as kernel; use std::sync::{Arc,Mutex as StdMutex,atomic::{AtomicU32,Ordering}}; -type Result = std::result::Result;const ENOSPC:u32=28;const GFP_NOWAIT:u32=0; +type Result = std::result::Result;const ENOSPC:u32=28;const GFP_NOWAIT:u32=0;const GFP_KERNEL:u32=1; struct Mutex(StdMutex);implMutex{fn lock(&self)->std::sync::MutexGuard<'_,T>{self.0.lock().unwrap()}} struct KVec(Vec);implKVec{fn push(&mut self,v:T,_f:u32)->Result{self.0.push(v);Ok(())}fn remove(&mut self,i:usize)->Result{Ok(self.0.remove(i))}} implstd::ops::Deref for KVec{type Target=Vec;fn deref(&self)->&Vec{&self.0}} @@ -52,36 +52,49 @@ def item(marker,text=None): struct Handle(std::sync::atomic::AtomicBool);impl Handle{fn open()->Self{Self(std::sync::atomic::AtomicBool::new(false))}fn mark_closed(&self){self.0.store(true,Ordering::Release);}fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)}} struct Cache{closes:AtomicU32,spares:StdMutex>>}impl Cache{fn new()->Self{Self{closes:AtomicU32::new(0),spares:StdMutex::new(Vec::new())}}fn close(&self){self.closes.fetch_add(1,Ordering::AcqRel);let spares=std::mem::take(&mut *self.spares.lock().unwrap());drop(spares);}} struct VmState{id:u64,vm:Handle,drops:Arc,resources:Option>}impl Drop for VmState{fn drop(&mut self){self.drops.fetch_add(1,Ordering::AcqRel);}} +// The kernel's fallible constructor; the tests' own Arcs stay std's. +struct UniqueArc(T);struct Space(std::marker::PhantomData); +implUniqueArc{fn new_uninit(_f:u32)->Result>{Ok(Space(std::marker::PhantomData))}} +implSpace{fn write(self,v:T)->UniqueArc{UniqueArc(v)}} +implFrom>for Arc{fn from(v:UniqueArc)->Self{Arc::new(v.0)}} +// VMs without a queue are covered by test-vm-slots.py. +struct IdleVm;struct RBTree(std::collections::BTreeMap); +implRBTree{fn remove_node(&mut self,k:&K)->Option{self.0.remove(k)}} __REGISTRY__ -struct Reservation<'a>(Option<&'a Registry>,u64,usize); +__FILE_PLACE__ +__FILE_PLACE_DROP__ +struct Reservation<'a>(Option<&'a Registry>,usize); __RESERVATION_DROP__ impl Registry{ + __ADMIT__ + __LEAVE__ __RESERVE__ __RELEASE__ __CLOSE__ __PRUNE__ - fn new_test()->Self{Self{live:AtomicU32::new(0),vms:Mutex(StdMutex::new(KVec(Vec::with_capacity(63)))),files:Mutex(StdMutex::new(KVec(Vec::with_capacity(63)))),processes:Mutex(StdMutex::new(queue_share::Shares::new()))}} + fn new_test()->Arc{Arc::new(Self{idle:Mutex(StdMutex::new(RBTree(Default::default()))),binding:Mutex(StdMutex::new(())),live:AtomicU32::new(0),vms:Mutex(StdMutex::new(KVec(Vec::with_capacity(63)))),files:Mutex(StdMutex::new(KVec(Vec::with_capacity(63)))),processes:Mutex(StdMutex::new(queue_share::Shares::new()))})} } #[test]fn pending_and_live_file_quota_returns_only_on_release(){ - let r=Registry::new_test();let mut owners:Vec<_>=(0..8).map(|_|r.reserve(7).unwrap()).collect(); - assert!(matches!(r.reserve(7),Err(ENOSPC)));let other=r.reserve(8).unwrap(); - drop(owners.pop());owners.push(r.reserve(7).unwrap());assert!(matches!(r.reserve(7),Err(ENOSPC))); + let r=Registry::new_test();let place=|file|Registry::admit(&r,file); + let mut owners:Vec<_>=(0..8).map(|_|(place(7).unwrap(),r.reserve().unwrap())).collect(); + assert!(matches!(place(7),Err(ENOSPC)));let other=(place(8).unwrap(),r.reserve().unwrap()); + drop(owners.pop());owners.push((place(7).unwrap(),r.reserve().unwrap()));assert!(matches!(place(7),Err(ENOSPC))); drop((owners,other));assert_eq!(r.live.load(Ordering::Acquire),0);assert!(r.files.lock().is_empty()); } #[test]fn device_quota_is_still_bounded_across_files(){ // Eight processes, one file each: the device limit still holds across them. - let r=Registry::new_test();let owners:Vec<_>=(0..63u64).map(|n|{as_process((n/8+1) as usize);r.reserve(n/8).unwrap()}).collect(); - as_process(100);assert!(matches!(r.reserve(100),Err(ENOSPC)));drop(owners);assert_eq!(r.live.load(Ordering::Acquire),0); + let r=Registry::new_test();let owners:Vec<_>=(0..63u64).map(|n|{as_process((n/8+1) as usize);r.reserve().unwrap()}).collect(); + as_process(100);assert!(matches!(r.reserve(),Err(ENOSPC)));drop(owners);assert_eq!(r.live.load(Ordering::Acquire),0); assert_eq!(r.processes.lock().held(),0); } #[test]fn a_process_alone_leaves_vm_slots_for_the_compositor(){ - // One process across eight files stops at 56 of 63; another process still gets a slot. + // One process stops at 56 of 63; another process still gets a slot. let r=Registry::new_test();as_process(1); - let owners:Vec<_>=(0..56).map(|n|r.reserve(n/7).unwrap()).collect(); - assert!(matches!(r.reserve(9),Err(ENOSPC)));assert!(r.files.lock().iter().all(|(id,_)|*id!=9)); - as_process(2);let compositor=r.reserve(50).unwrap(); + let owners:Vec<_>=(0..56).map(|_|r.reserve().unwrap()).collect(); + assert!(matches!(r.reserve(),Err(ENOSPC)));assert_eq!(r.live.load(Ordering::Acquire),56); + as_process(2);let compositor=r.reserve().unwrap(); drop(owners);drop(compositor);assert_eq!(r.live.load(Ordering::Acquire),0); - assert!(r.files.lock().is_empty());assert_eq!(r.processes.lock().held(),0); + assert_eq!(r.processes.lock().held(),0); } #[test]fn close_releases_registry_owner_without_another_vm_create(){ let r=Registry::new_test();let drops=Arc::new(AtomicU32::new(0)); @@ -108,7 +121,7 @@ def item(marker,text=None): assert_eq!(drops.load(Ordering::Acquire),1); } ''' -for tag,marker in [('REGISTRY','pub(crate) struct Registry'),('RESERVATION_DROP',"impl Drop for Reservation<'_>"),('RESERVE','fn reserve(&self, file_id:'),('RELEASE','fn release(&self, file_id:'),('CLOSE','pub(crate) fn close(&self, id:'),('PRUNE','fn prune(&self)')]: +for tag,marker in [('REGISTRY','pub(crate) struct Registry'),('RESERVATION_DROP',"impl Drop for Reservation<'_>"),('FILE_PLACE','pub(crate) struct FilePlace'),('FILE_PLACE_DROP','impl Drop for FilePlace'),('ADMIT','fn admit('),('LEAVE','fn leave('),('RESERVE','fn reserve(&self)'),('RELEASE','fn release(&self, process:'),('CLOSE','pub(crate) fn close(&self, id:'),('PRUNE','fn prune(&self)')]: source=source.replace('__'+tag+'__',item(marker).replace(' #[pin]\n','')) source=source.replace('__QS_RESERVE__','pub '+item('fn reserve(max: u32)',qs)).replace('__QS_MAY_TAKE_HELD__','pub '+item('fn may_take_held(',qs)) source=source.replace('struct Reservation<',s[s.index('const MAX_VMS_PER_FILE:'):s.index(';',s.index('const MAX_VMS_PER_FILE:'))+1]+'\nstruct Reservation<',1) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-slots.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-slots.py new file mode 100644 index 0000000000000..8f108d77c074e --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-slots.py @@ -0,0 +1,402 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise when production VM creation and queue creation take a TTBAT slot, without a GPU.""" +from common import kernel_root, output_dir, rustc +import re, subprocess + +g16 = kernel_root() / 'drivers/gpu/drm/asahi/g16' +vm = (g16 / 'vm.rs').read_text() +hw = (g16 / 'hw.rs').read_text() +qs = (g16.parent / 'queue_share.rs').read_text() + + +def item(text, marker): + start = text.index(marker) + i = text.index('{', start) + 1 + depth = 1 + while depth: + depth += (text[i] == '{') - (text[i] == '}') + i += 1 + return text[start:i] + + +def constant(name): + """A `usize`/`u32` constant of hw.rs, following sums of other such constants.""" + value = re.search(r'pub\(crate\) const %s: (?:usize|u32) = ([^;]+);' % name, hw).group(1) + return sum(int(v) if v.isdigit() else constant(v) for v in value.split(' + ')) + + +# Everything from the VM state on, without what builds the mappings and the registry's locks. +code = vm[vm.index('/// G16 state of one user VM'):] +for marker in (' pub(crate) fn new() -> Result>', ' fn driver_mappings(', + 'pub(crate) fn reserved_ranges('): + code = code.replace(item(code, marker), '') +code = code.replace('#[pin_data]\n', '').replace(' #[pin]\n', '') +per_file = re.search(r'const MAX_VMS_PER_FILE: u32 = \d+;', vm).group(0) + +# Fields of the registry that only some versions of vm.rs have. +registry = item(code, 'pub(crate) struct Registry') +fields = ''.join(text for name, text in ( + ('idle:', 'idle: Mutex::new(RBTree::new()),'), + ('binding:', 'binding: Mutex::new(()),'), +) if name in registry) + +source = r''' +#![allow(dead_code, unused_variables, unused_imports, unused_macros)] +use std::{collections::BTreeMap, ops::Range, sync::{Mutex as StdMutex, MutexGuard}}; +type Result = std::result::Result; +type Error = u32; +const ENOENT: u32 = 2; const EIO: u32 = 5; const ENOMEM: u32 = 12; const EBUSY: u32 = 16; +const ENODEV: u32 = 19; const EINVAL: u32 = 22; const ENOSPC: u32 = 28; +const GFP_KERNEL: u32 = 0; const GFP_NOWAIT: u32 = 1; +macro_rules! mod_pr_debug { ($($t:tt)*) => {}; } +macro_rules! pr_err { ($($t:tt)*) => {}; } + +struct Mutex(StdMutex); +impl Mutex { + fn new(v: T) -> Self { Self(StdMutex::new(v)) } + // A held lock means the code under test would deadlock. + fn lock(&self) -> MutexGuard<'_, T> { self.0.try_lock().expect("lock held") } +} +struct Arc(std::sync::Arc); +impl Arc { fn new(v: T, _f: u32) -> Result { Ok(Self(std::sync::Arc::new(v))) } } +impl Clone for Arc { fn clone(&self) -> Self { Self(self.0.clone()) } } +impl std::ops::Deref for Arc { type Target = T; fn deref(&self) -> &T { &self.0 } } +struct UniqueArc(T); +struct Space(std::marker::PhantomData); +impl UniqueArc { + fn new_uninit(_f: u32) -> Result> { Ok(Space(std::marker::PhantomData)) } +} +impl Space { fn write(self, v: T) -> UniqueArc { UniqueArc(v) } } +impl From> for Arc { + fn from(v: UniqueArc) -> Self { Self(std::sync::Arc::new(v.0)) } +} +struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn with_capacity(n: usize, _f: u32) -> Result { Ok(Self(Vec::with_capacity(n))) } + fn push(&mut self, v: T, _f: u32) -> Result { self.0.push(v); Ok(()) } + fn remove(&mut self, i: usize) -> Result { Ok(self.0.remove(i)) } +} +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +struct RBTree(BTreeMap); +struct RBTreeNode(K, V); +impl RBTreeNode { fn new(k: K, v: V, _f: u32) -> Result { Ok(Self(k, v)) } } +impl RBTree { + fn new() -> Self { Self(BTreeMap::new()) } + fn insert(&mut self, n: RBTreeNode) -> Option { self.0.insert(n.0, n.1) } + fn get(&self, k: &K) -> Option<&V> { self.0.get(k) } + fn remove_node(&mut self, k: &K) -> Option { self.0.remove(k) } + fn values(&self) -> impl Iterator { self.0.values() } +} +mod kernel { pub mod types { + pub struct ScopeGuard(Option<(T, F)>); + impl ScopeGuard { + pub fn new_with_data(v: T, f: F) -> Self { Self(Some((v, f))) } + pub fn dismiss(mut self) -> T { self.0.take().unwrap().0 } + } + impl ScopeGuard<(), fn(())> { + pub fn new(f: F) -> ScopeGuard<(), impl FnOnce(())> { + ScopeGuard(Some(((), move |()| f()))) + } + } + impl Drop for ScopeGuard { + fn drop(&mut self) { if let Some((v, f)) = self.0.take() { f(v) } } + } +} } +mod module_parameters { + pub struct Param; + impl Param { pub fn value(&self) -> u32 { 0 } } + #[allow(non_upper_case_globals)] pub static robust_isolation: Param = Param; +} +mod queue_share { + use super::*; + thread_local! { pub static CURRENT: std::cell::Cell = std::cell::Cell::new(1); } + __QS_RESERVE__ + __QS_MAY_TAKE_HELD__ + pub struct Shares(pub BTreeMap); + impl Shares { + pub fn take_current(&mut self, max: u32, _f: u32) -> Result { + let key = CURRENT.with(|c| c.get()); + let held = self.0.get(&key).copied().unwrap_or(0); + if !may_take_held(held, self.0.values().sum(), max) { return Err(EBUSY); } + *self.0.entry(key).or_default() += 1; + Ok(key) + } + pub fn give_back(&mut self, key: usize) -> Option { + let held = self.0.get_mut(&key)?; + *held -= 1; + if *held != 0 { return None; } + self.0.remove(&key); + Some(key) + } + } +} +mod memacct { pub struct Client; } +// The production cleanup is asynchronous; releasing at once only makes reuse earlier. +mod cleanup { + pub struct Deferred(T); + impl Deferred { pub fn new(v: T) -> super::Result { Ok(Self(v)) } } + impl std::ops::Deref for Deferred { type Target = T; fn deref(&self) -> &T { &self.0 } } +} +mod mmu { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + pub struct KernelMapping; + #[derive(Clone)] + pub struct Vm { id: u64, closed: std::sync::Arc, status: Option> } + impl Vm { + pub fn with_tracked_status(mut self) -> Result { + self.status = Some(Arc::new(vm::VmStatus::default(), 0)?); + Ok(self) + } + pub fn with_memory_client(self, _c: Arc) -> Self { self } + pub fn id(&self) -> u64 { self.id } + pub fn status(&self) -> Option<&Arc> { self.status.as_ref() } + pub fn is_closed(&self) -> bool { self.closed.load(Ordering::Acquire) } + pub fn install_driver_mappings(&self, _m: KVec, _r: KVec>) -> Result { Ok(()) } + pub fn unmap_user_ranges(&self, _u: Range, _k: Range) -> Result { + self.closed.store(true, Ordering::Release); + Ok(()) + } + pub fn bo_deferred_cleanup(&self) {} + } + /// TTBAT user slots 1..=63 and their users: a slot is free only without any. + pub struct Uat { pub users: std::sync::Arc>>, pub on_bind: StdMutex>> } + impl Uat { + pub fn new_vm(&self, id: u64, _k: Range) -> Result { + Ok(Vm { id, closed: Default::default(), status: None }) + } + pub fn bind(&self, vm: &Vm) -> Result { + if let Some(f) = self.on_bind.lock().unwrap().take() { f(vm); } + let mut users = self.users.lock().unwrap(); + // The slot allocator would wait here: the registry must never let it come to that. + let slot = (1..=super::hw::sizes::MAX_VMS).find(|s| !users.contains_key(s)).expect("no free slot"); + users.insert(slot, 1); + Ok(VmBind { slot, users: self.users.clone() }) + } + } + pub struct VmBind { slot: u32, users: std::sync::Arc>> } + impl VmBind { + pub fn slot(&self) -> u32 { self.slot } + pub fn generation(&self) -> u8 { 1 } + } + impl Clone for VmBind { + fn clone(&self) -> Self { + *self.users.lock().unwrap().get_mut(&self.slot).unwrap() += 1; + Self { slot: self.slot, users: self.users.clone() } + } + } + impl Drop for VmBind { + fn drop(&mut self) { + let mut users = self.users.lock().unwrap(); + let n = users.get_mut(&self.slot).unwrap(); + *n -= 1; + if *n == 0 { users.remove(&self.slot); } + } + } +} +mod hw { + pub const USER_RANGE: std::ops::Range = 0..1; + pub mod sizes { pub const MAX_VMS: u32 = __MAX_VMS__; pub const MAX_CLIENT: usize = 1; } +} +mod object { + #[derive(Clone)] pub struct Factory; + pub struct Objects; +} +mod resources { + use super::*; + thread_local! { pub static FAIL: std::cell::Cell = std::cell::Cell::new(false); } + pub struct Cache(mmu::VmBind, Arc); + impl Cache { + pub fn new(_f: object::Factory, b: mmu::VmBind, l: Arc, _s: std::sync::Arc) -> Result> { + if FAIL.with(|f| f.replace(false)) { return Err(ENOMEM); } + Arc::new(Self(b, l), 0) + } + pub fn close(&self) {} + pub fn renders_unpublished(&self) -> bool { false } + } +} +pub struct Firmware { objects: object::Objects, vms: Arc, private_factory: object::Factory } +pub struct Shared { crashed: std::sync::atomic::AtomicBool, state: Mutex> } +struct Ids { vm: Sequence } +struct Sequence(std::sync::atomic::AtomicU64); +impl Sequence { fn next(&self) -> u64 { self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } } +pub struct Gpu { shared: std::sync::Arc, uat: mmu::Uat, ids: Ids } +mod vm { + use super::*; + use std::sync::atomic::{AtomicU32, Ordering}; + #[derive(Default)] pub struct VmStatus(std::sync::atomic::AtomicU32); + impl VmStatus { + pub fn record(&self, e: u32) { self.0.store(e, Ordering::Release); } + pub fn get(&self) -> u32 { self.0.load(Ordering::Acquire) } + } + struct ClientAlias; + impl ClientAlias { fn collect(_o: &object::Objects, _a: &mut KVec) -> Result { Ok(()) } } + __PER_FILE__ + __CODE__ + impl Registry { + fn driver_mappings(_vm: &mmu::Vm, _a: KVec) -> Result<(KVec, KVec>)> { + Ok((KVec::new(), KVec::new())) + } + fn new_test() -> Arc { + Arc::new(Self { + vms: Mutex::new(KVec::new()), live: AtomicU32::new(0), files: Mutex::new(KVec::new()), + processes: Mutex::new(queue_share::Shares(BTreeMap::new())), __FIELDS__ + }, 0).unwrap() + } + fn idle_files(&self) -> bool { self.files.lock().is_empty() && self.processes.lock().0.is_empty() } + } + fn gpu() -> Gpu { + Gpu { + shared: std::sync::Arc::new(Shared { + crashed: Default::default(), + state: Mutex::new(Some(Firmware { objects: object::Objects, vms: Registry::new_test(), private_factory: object::Factory })), + }), + uat: mmu::Uat { users: Default::default(), on_bind: Default::default() }, + ids: Ids { vm: Sequence(1.into()) }, + } + } + fn registry(g: &Gpu) -> Arc { g.shared.state.lock().as_ref().unwrap().vms.clone() } + fn create(g: &Gpu, file: u64) -> Result { + queue_share::CURRENT.with(|c| c.set(file as usize)); + new_vm(g, 0..1, file, None) + } + // What file::Vm does when the client's handle goes. + fn close(g: &Gpu, vm: &mmu::Vm) { + vm.unmap_user_ranges(0..1, 0..1).unwrap(); + registry(g).close(vm.id()); + } + fn slots_in_use(g: &Gpu) -> usize { g.uat.users.lock().unwrap().len() } + /// A Vulkan process: its physical device's VM, which never gets a queue, and its logical + /// device's VM with one. + fn vulkan(g: &Gpu, file: u64) -> Result<([mmu::Vm; 2], Arc)> { + let physical = create(g, file)?; + let logical = create(g, file)?; + let state = lookup(g, &logical)?; + Ok(([physical, logical], state)) + } + + /// gpubench compute.light procs d=16, pass 2 (linux#3340): every pipe and slot that keeps its + /// newest owner until another one displaces it keeps the VM of a process that has exited. + #[test] + fn exited_clients_on_every_pipe_leave_slots_for_sixteen_processes() { + let g = gpu(); + let desktop: Vec<_> = (0..9).map(|n| { let vm = create(&g, n).unwrap(); (lookup(&g, &vm).unwrap(), vm) }).collect(); + let mut leases = Vec::new(); + for n in 0..__PINNED__ { + let (vms, state) = vulkan(&g, 100 + n).unwrap(); + for vm in &vms { close(&g, vm); } + leases.push(state); + } + assert_eq!(slots_in_use(&g), desktop.len() + leases.len()); + let clients: Vec<_> = (0..16).map(|n| { + vulkan(&g, 200 + n).unwrap_or_else(|e| panic!("process {n}: errno {e}, {} slots in use", slots_in_use(&g))) + }).collect(); + // The slots of the exited clients are still leased: none of them was handed out again. + let mut slots: Vec = desktop.iter().map(|d| d.0.slot).chain(leases.iter().map(|s| s.slot)) + .chain(clients.iter().map(|c| c.1.slot)).collect(); + assert_eq!(slots.len(), slots_in_use(&g)); + slots.sort(); slots.dedup(); + assert_eq!(slots.len(), slots_in_use(&g)); + } + #[test] + fn a_leased_slot_is_not_reused_until_its_last_owner_goes() { + let g = gpu(); + let (vms, lease) = vulkan(&g, 1).unwrap(); + for vm in &vms { close(&g, vm); } + // Fill the rest; the process share keeps some free for others, so use many processes. + let mut held = Vec::new(); + let full = loop { + match vulkan(&g, 2 + held.len() as u64) { + Ok(client) => { assert_ne!(client.1.slot, lease.slot); held.push(client) } + Err(e) => break e, + } + }; + assert_eq!(full, ENOSPC); + assert_eq!(held.len() as u32, hw::sizes::MAX_VMS - 1); + let slot = lease.slot; + drop(lease); + assert_eq!(vulkan(&g, 1000).unwrap().1.slot, slot); + } + #[test] + fn a_vm_is_bound_once_for_all_its_queues() { + let g = gpu(); + let vm = create(&g, 1).unwrap(); + assert_eq!(slots_in_use(&g), 0); + let (a, b) = (lookup(&g, &vm).unwrap(), lookup(&g, &vm).unwrap()); + assert!(std::sync::Arc::ptr_eq(&a.0, &b.0)); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (1, (1, 1))); + close(&g, &vm); + drop(a); + assert_eq!(slots_in_use(&g), 1); + drop(b); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (0, (0, 0))); + assert!(registry(&g).idle_files()); + assert!(matches!(lookup(&g, &vm), Err(ENOENT))); + } + #[test] + fn a_failed_binding_leaves_the_vm_for_another_queue() { + let g = gpu(); + let vm = create(&g, 1).unwrap(); + resources::FAIL.with(|f| f.set(true)); + assert!(matches!(lookup(&g, &vm), Err(ENOMEM))); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (0, (0, 0))); + let state = lookup(&g, &vm).unwrap(); + assert_eq!(slots_in_use(&g), 1); + close(&g, &vm); + drop(state); + assert_eq!(slots_in_use(&g), 0); + assert!(registry(&g).idle_files()); + } + #[test] + fn a_vm_closed_while_it_is_bound_keeps_nothing() { + let g = gpu(); + let vm = create(&g, 1).unwrap(); + let r = registry(&g); + *g.uat.on_bind.lock().unwrap() = Some(Box::new(move |vm| { + vm.unmap_user_ranges(0..1, 0..1).unwrap(); + r.close(vm.id()); + })); + assert!(matches!(lookup(&g, &vm), Err(ENOENT))); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (0, (0, 0))); + assert!(registry(&g).idle_files()); + } + #[test] + fn the_file_quota_counts_vms_with_and_without_a_queue() { + let g = gpu(); + let mut vms: Vec<_> = (0..MAX_VMS_PER_FILE).map(|_| create(&g, 7).unwrap()).collect(); + let state = lookup(&g, &vms[0]).unwrap(); + assert!(matches!(create(&g, 7), Err(ENOSPC))); + assert!(create(&g, 8).is_ok()); + // Closing an unbound VM gives its place back at once, a bound one with its last owner. + close(&g, &vms.pop().unwrap()); + vms.push(create(&g, 7).unwrap()); + close(&g, &vms[0]); + assert!(matches!(create(&g, 7), Err(ENOSPC))); + drop(state); + assert!(create(&g, 7).is_ok()); + } + #[test] + fn fail_stop_reaches_vms_without_a_queue() { + let g = gpu(); + let (idle, bound) = (create(&g, 1).unwrap(), create(&g, 2).unwrap()); + let state = lookup(&g, &bound).unwrap(); + registry(&g).fail_all(EIO); + assert_eq!((idle.status().unwrap().get(), state.status.get()), (EIO, EIO)); + } +} +''' +# The newest owner of every compute pipe, of the render slots, and of every PB slot. +pinned = constant('COMPUTE_PIPES') + 1 + constant('PB_SLOTS') +for tag, text in (('QS_RESERVE', 'pub ' + item(qs, 'fn reserve(max: u32)')), + ('QS_MAY_TAKE_HELD', 'pub ' + item(qs, 'fn may_take_held(')), + ('MAX_VMS', str(constant('MAX_VMS'))), ('PINNED', str(pinned)), + ('PER_FILE', per_file), ('FIELDS', fields), ('CODE', code)): + source = source.replace('__%s__' % tag, text) +out = output_dir() +path = out / 'vm_slots.rs' +path.write_text(source) +subprocess.run(rustc() + ['--edition=2021', '--test', str(path), '-o', str(out / 'vm_slots')], check=True) +subprocess.run([str(out / 'vm_slots')], check=True) From e1a826530d635c000f6edaaa379cf7590e020851 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 3 Dec 2026 02:05:43 -0500 Subject: [PATCH 6/7] tools/asahi: g16-vm-share: follow the VM registry's reservation Registry::reserve() takes a TTBAT slot for a VM's first queue and no longer counts the VM against its file. Reserve without a file; the file limit is covered by the asahi-m4 selftest test-vm-registry.py. Signed-off-by: DjDeveloperr --- tools/asahi/g16-vm-share-tests.py | 65 +++++++++++-------------------- 1 file changed, 23 insertions(+), 42 deletions(-) diff --git a/tools/asahi/g16-vm-share-tests.py b/tools/asahi/g16-vm-share-tests.py index 4e82135f52c24..6b4893d3ca20e 100755 --- a/tools/asahi/g16-vm-share-tests.py +++ b/tools/asahi/g16-vm-share-tests.py @@ -5,7 +5,7 @@ The production Registry::reserve and Registry::release (g16/vm.rs) and the process share rule (queue_share.rs) are copied from the tree and built with rustc against mocks of the kernel mutex, vector, scope guard and current process. A process may open the device many times, so -the live VMs must be shared per process: one process with many files must leave room for the +the bound VMs must be shared per process: one process with many files must leave room for the others, and giving VMs back must make room again. --mutations also runs the checks against each mutant below and expects every one to fail: @@ -34,7 +34,7 @@ def item(source, signature): def before_share(): """The reservation as it was before VMs were shared per process.""" - return r'''fn reserve(&self, file_id: u64) -> Result> { + return r'''fn reserve(&self) -> Result> { self.prune(); let limit = if module_parameters::robust_isolation.value() != 0 { 1 } else { hw::sizes::MAX_VMS }; self.live @@ -45,27 +45,16 @@ def before_share(): let rollback = kernel::types::ScopeGuard::new(|| { self.live.fetch_sub(1, Ordering::AcqRel); }); - { - let mut files = self.files.lock(); - if let Some((_, count)) = files.iter_mut().find(|(id, _)| *id == file_id) { - if *count >= MAX_VMS_PER_FILE { - return Err(ENOSPC); - } - *count += 1; - } else { - files.push((file_id, 1), GFP_NOWAIT)?; - } - } rollback.dismiss(); - Ok(Reservation(Some(self), file_id, 0)) + Ok(Reservation(Some(self), 0)) }''' def fixture(mutation): vm = (ASAHI / 'g16/vm.rs').read_text() share = (ASAHI / 'queue_share.rs').read_text() - reserve = item(vm, 'fn reserve(&self, file_id: u64)') - release = item(vm, 'fn release(&self, file_id: u64') + reserve = item(vm, 'fn reserve(&self) ->') + release = item(vm, 'fn release(&self, process:') if mutation == 'before-share': reserve = before_share() elif mutation == 'lone-takes-all': @@ -75,7 +64,6 @@ def fixture(mutation): if old not in release: raise RuntimeError('mutation site changed: never-give-back') release = release.replace(old, 'None::') - per_file = next(line for line in vm.splitlines() if line.startswith('const MAX_VMS_PER_FILE')) max_vms = next(line.strip() for line in (ASAHI / 'g16/hw.rs').read_text().splitlines() if 'const MAX_VMS:' in line).replace('pub(crate) ', '') policy = '\n'.join(item(share, signature) for signature in ( @@ -136,11 +124,11 @@ def fixture(mutation): fn current_key() -> (usize, Option>) { (CURRENT.with(|c| c.get()), None) } struct Process { key: usize, _mm: Option>, held: u32, tgid: Pid, comm: [u8; 16] } pub(crate) struct Shares(KVec); -''' + policy + '\n' + shares + '\n' + per_file + r''' -struct Registry { live: AtomicU32, files: Mutex>, processes: Mutex } -struct Reservation<'a>(Option<&'a Registry>, u64, usize); +''' + policy + '\n' + shares + r''' +struct Registry { live: AtomicU32, processes: Mutex } +struct Reservation<'a>(Option<&'a Registry>, usize); impl Drop for Reservation<'_> { - fn drop(&mut self) { if let Some(registry) = self.0 { registry.release(self.1, self.2); } } + fn drop(&mut self) { if let Some(registry) = self.0 { registry.release(self.1); } } } impl Registry { fn prune(&self) {} @@ -151,23 +139,18 @@ def fixture(mutation): fn main() { let max = hw::sizes::MAX_VMS; - let registry = Registry { live: AtomicU32::new(0), files: Mutex(RefCell::new(KVec::new())), - processes: Mutex(RefCell::new(Shares::new())) }; - // A compositor (process 1) holds one VM. + let registry = Registry { live: AtomicU32::new(0), processes: Mutex(RefCell::new(Shares::new())) }; + // A compositor (process 1) has one VM bound. as_process(1); - let compositor = registry.reserve(100).expect("compositor VM"); - // Process 2 opens the device again and again, creating every VM each file allows. + let compositor = registry.reserve().expect("compositor VM"); + // Process 2 creates VMs with a queue until it is refused, whatever files they are on. as_process(2); let mut taken = Vec::new(); - for file in 200..(200 + max as u64) { - let before = taken.len(); - for _ in 0..MAX_VMS_PER_FILE { - match registry.reserve(file) { - Ok(r) => taken.push(r), - Err(e) => { assert_eq!(e, ENOSPC); break; } - } + loop { + match registry.reserve() { + Ok(r) => taken.push(r), + Err(e) => { assert_eq!(e, ENOSPC); break; } } - if taken.len() == before { break; } } let held = taken.len() as u32; println!("process 2 holds {} of {} VMs", held, max); @@ -175,31 +158,29 @@ def fixture(mutation): assert!(held >= max / 2, "a process may hold half the device's VMs"); // But it leaves room for the others: a newly started process and the compositor get VMs. as_process(3); - let late = registry.reserve(300).expect("FAIL line 1: a newly started process gets no VM"); + let late = registry.reserve().expect("FAIL line 1: a newly started process gets no VM"); as_process(1); - let second = registry.reserve(100).expect("FAIL line 2: the compositor gets no second VM"); + let second = registry.reserve().expect("FAIL line 2: the compositor gets no second VM"); assert!(registry.live.load(Ordering::Acquire) <= max); drop(late); drop(second); // A VM given back can be created again by the same process. as_process(2); drop(taken.pop()); - taken.push(registry.reserve(9999).expect("FAIL line 3: a given back VM cannot be created again")); + taken.push(registry.reserve().expect("FAIL line 3: a given back VM cannot be created again")); drop(taken); drop(compositor); // Everything given back: a process alone still leaves the reserve, since a VM keeps its // slot until it is closed, and a process started after it gets a VM. as_process(4); let mut all = Vec::new(); - for file in 0..(max as u64 + 8) { - for _ in 0..MAX_VMS_PER_FILE { - if let Ok(r) = registry.reserve(1000 + file) { all.push(r) } - } + for _ in 0..max + 8 { + if let Ok(r) = registry.reserve() { all.push(r) } } assert_eq!(all.len() as u32, max - reserve(max), "FAIL line 4: a process alone takes the reserve (or less than the rest)"); as_process(5); - let after = registry.reserve(5000).expect("FAIL line 6: a process started later gets no VM"); + let after = registry.reserve().expect("FAIL line 6: a process started later gets no VM"); drop(after); drop(all); assert_eq!(registry.live.load(Ordering::Acquire), 0); From d50ef24e7dae60160adbb6c229bc2598503948b8 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 3 Dec 2026 02:06:28 -0500 Subject: [PATCH 7/7] drm/asahi: g16: keep displacement in the owner ledger Whether a retired compute or render owner was displaced was decided by comparing it with every other owner, and the engine asks that of every unit a VM may use several times for each submission. That is a pairwise scan. It costs nothing while units are unused, which is how a driver starts, but it runs in full once every unit has retired work, and it grows with the square of the units: one pass over the ledger took 0.7 us with 24 units and 8 pipes and 6.6 us with 64 units and 16 pipes on an x86 build host. The J773g row of linux#3340 shows it. The time gpubench measures in the submit calls of compute.light rose from 9-11 us to 19 us at procs depths 8 and 16, and queue depth 1 went from 104 to 116 us per submission in the second pass, with the ledger full. In the first it was level with linux#3695 and linux#3699 alone. Keep the answer in each owner instead and update it when a publication retires, which already walks the ledger. The same pass then takes 0.05 us at either size. Nothing else changes: an owner is displaced by the same publications as before. A host test compares the kept answer with the pairwise scan over random transitions, in-order and ordered pipes alike. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 85 ++++++++++++++++++--- 1 file changed, 76 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index a61cd241032d2..27f09bd5e3d07 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -34,6 +34,9 @@ struct Unit { generation: u8, pipe: u8, publication: u64, + /// A later publication retired ([`Lifetime::displaced_by_scan`]), kept by `retire()` and + /// `quarantine()` so that claiming among many owners need not compare them all pairwise. + displaced: bool, } /// Accounting of physical owners, including permanently retained abort storage. @@ -63,6 +66,7 @@ impl Lifetime { generation: 0, pipe: 0, publication: 0, + displaced: false, }; Self { units: [unit; N], @@ -107,18 +111,22 @@ impl Lifetime { }; match u.state { State::Fresh => true, - // A later publication on the same hardware pipe retired: it started only after this - // owner finished on that pipe, and its load displaced this owner from the slot. - // A later publication retired: with `ordered` pipes on any pipe, else on this one. - State::Retired => self.units.iter().enumerate().any(|(b, other)| { - b != k - && other.state == State::Retired - && (self.ordered || other.pipe == u.pipe) - && other.publication > u.publication - }), + State::Retired => u.displaced, _ => false, } } + /// Whether a later publication than retired owner `k`'s retired: with `ordered` pipes on any + /// pipe, else on `k`'s own, where it started only after `k` finished and its load displaced + /// `k` from the slot. The newest retired owner of a pipe is never claimed, so it stays + /// [`State::Retired`] and keeps proving this for the others. + fn displaced_by_scan(&self, k: usize) -> bool { + let u = self.units[k]; + self.units.iter().any(|other| { + other.state == State::Retired + && (self.ordered || other.pipe == u.pipe) + && other.publication > u.publication + }) + } /// No amount of firmware progress can make a unit claimable. The caller must fail /// pending work rather than wait forever after abort/quarantine or sequence exhaustion. pub(crate) fn exhausted(&self) -> bool { @@ -209,6 +217,7 @@ impl Lifetime { self.sequence += 1; self.units[k].pipe = pipe; self.units[k].publication = self.sequence; + self.units[k].displaced = false; self.units[k].state = State::Published; true } @@ -228,11 +237,25 @@ impl Lifetime { return false; } self.units[k].state = State::Retired; + self.units[k].displaced = self.displaced_by_scan(k); + let ordered = self.ordered; + for other in self.units.iter_mut() { + if (ordered || other.pipe == pipe) && other.publication < publication { + other.displaced = true; + } + } true } /// A firmware-aborted owner is retained forever and cannot grant a displacement lease. pub(crate) fn quarantine(&mut self, k: usize) { + let retired = self.units[k].state == State::Retired; self.units[k].state = State::Quarantined; + if retired { + // It may have been the only proof of an earlier owner's displacement. + for b in 0..N { + self.units[b].displaced = self.displaced_by_scan(b); + } + } } } @@ -240,6 +263,50 @@ impl Lifetime { mod tests { use super::*; #[test] + fn kept_displacement_matches_the_pairwise_scan() { + // Every transition of a small ledger, drawn by a fixed linear congruential sequence. + fn run(mut l: Lifetime, pipes: u64) { + let mut seed = 1u64; + let mut next = |n: u64| { + seed = seed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (seed >> 33) % n + }; + let mut reused = 0; + for _ in 0..4000 { + let k = next(N as u64) as usize; + match next(16) { + 0..=4 => reused += u32::from(l.claim(k)), + 5 => l.cancel(k), + 6..=9 => { + l.publish_on(k, next(pipes) as u8); + } + 10..=14 => { + l.retire(k); + } + // Rare: a quarantined owner never comes back. + _ if next(200) == 0 && l.counts().quarantined as usize + 3 < N => { + l.quarantine(k) + } + _ => {} + } + for b in 0..N { + let scan = match l.units[b].state { + State::Fresh => true, + State::Retired => l.displaced_by_scan(b), + _ => false, + }; + assert_eq!(l.available(b), scan); + } + } + assert!(reused > 100); + } + run(Lifetime::<12>::new(true), 3); + run(Lifetime::<12>::new(true).ordered(), 3); + run(Lifetime::<12>::new(false), 2); + } + #[test] fn ordered_pipes_displace_by_publication_on_any_pipe() { // Owner 0 on pipe 0, then owner 1 on pipe 1; pipe 1 retires first. let mut l = Lifetime::<3>::new(true).ordered();