diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 9021a4be96da3..4441182786aae 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -532,7 +532,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, @@ -605,7 +605,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, @@ -993,7 +993,7 @@ impl Firmware { stage[sizes::render_stage(pair, 1)] = render.user_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.user_stamp.r32(0)?; } Ok(stage) } @@ -2362,7 +2362,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; @@ -2380,7 +2380,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; @@ -2424,7 +2424,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]; @@ -2477,7 +2477,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 { @@ -2604,7 +2604,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/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 35205be7c442e..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(o)?, + q: QueueSession::new_with(o, None)?, }) } fn finish(self, rings: &mut Objects, sched_ctx: Arc) -> Result { diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 15abb7d1a18df..e5485cfef379c 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -1224,12 +1224,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 { @@ -1242,13 +1244,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; @@ -1400,9 +1414,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; @@ -1480,7 +1494,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; @@ -1509,15 +1523,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 @@ -1525,18 +1542,21 @@ 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_list(2) + 0x4000 <= super::client::compute_base(3)); const _: () = assert!( - super::client::compute_context(2) + 0x40000 <= super::client::compute_base(3) - ); - const _: () = assert!( - super::client::compute_base(COMPUTE_UNITS as u64) <= super::client::PB_HEAP + 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::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; @@ -1551,11 +1571,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 c68490dfd4b28..bbebf62b22a72 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -306,7 +306,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`. @@ -701,7 +701,7 @@ impl Gpu { sleep_dark_held: 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 d2cb70a179ba2..af29a75b192c9 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/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index dfd6cf6a38e85..047b7b79a0db3 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -914,7 +914,7 @@ 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].user_stamp.r32(0) { let reached = if compute_behind[p] { stamp_reached(obs, f.target, self.engine.target[p]) } else { @@ -1325,33 +1325,48 @@ impl Firmware { .is_some() || f.rec[2] != self.channels.producer(Channel::Compute); let g = &self.graph.compute[pipe]; - if pipe_behind { - let tail = self.engine.target[pipe]; - if !stamp_reached(g.fw_stamp.r32(0)?, 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); } - rmb(); - // 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. - full &= stamp_reached(g.service_stamp().read()?, f.target, tail); - } else { - if g.fw_stamp.r32(0)? != 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(); - full &= g.service_stamp().read()? == f.target; } + 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 { @@ -1986,7 +2001,7 @@ 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].user_stamp.r32(0).unwrap_or(0), f.target, e.target[p], ); @@ -2283,7 +2298,7 @@ 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(), @@ -2291,7 +2306,6 @@ impl Firmware { pipe, e.target[pipe], rd(&g.user_stamp, 0), - rd(&g.fw_stamp, 0), rd(&g.qstate, qstate::DONE), rd(&g.qstate, qstate::READ), rd(&g.qstate, qstate::WRITE), diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 2e9c788108037..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 { @@ -133,7 +141,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; @@ -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(); diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index e44bbf98b303a..38c89da03339c 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; /// Number of TA/FS render queue pairs tracked by [`RetiredStamps`] (matches /// `hw::sizes::RENDER_PAIRS`). pub(crate) const RETIRED_RENDER_PAIRS: usize = 8; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index d7a483cd4a459..56fcdb42866f5 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -274,7 +274,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); } @@ -1215,7 +1215,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`. @@ -1293,16 +1293,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() { @@ -2235,7 +2236,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 = @@ -2710,20 +2711,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`. @@ -2769,7 +2770,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 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 0766eeef49f08..a3a7714ad8a76 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -398,14 +398,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, )?, @@ -416,18 +415,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, }) } @@ -1279,12 +1271,12 @@ 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 { - self.compute.lifetime.quarantined_mask() as u32 + pub(crate) fn quarantined_compute_mask(&self) -> u64 { + self.compute.lifetime.quarantined_mask() } pub(crate) fn render_exhausted(&self) -> bool { self.render.lifetime.exhausted() @@ -1312,7 +1304,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; @@ -1327,11 +1319,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) } @@ -1339,10 +1331,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) } @@ -1553,11 +1545,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 { @@ -1573,10 +1565,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) } @@ -1656,18 +1648,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] @@ -1681,7 +1673,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() @@ -1701,7 +1693,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) { @@ -1720,7 +1712,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/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/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); 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 051f67e54b4d8..d3f05b4c7147f 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 @@ -65,7 +65,7 @@ def item(declaration, text=source): const EVENT_RETIRE_POLLS: u32 = 11; mod hw { pub mod sizes { - pub const COMPUTE_PIPES: usize = 8; + pub const COMPUTE_PIPES: usize = 16; pub const RENDER_PAIRS: usize = 2; pub const COALESCE_WINDOW_US: u32 = 18; } @@ -121,7 +121,7 @@ def item(declaration, text=source): } struct ComputeGraph { - fw_stamp: Cell32, + user_stamp: Cell32, } // No `notifier`: the render notifier page is ASC-cached and the host never reads it. struct RenderGraph { @@ -347,7 +347,7 @@ def item(declaration, text=source): objects: Objects, graph: Graph { compute: core::array::from_fn(|_| ComputeGraph { - fw_stamp: Cell32::new(0), + user_stamp: Cell32::new(0), }), render: core::array::from_fn(|_| RenderGraph { user_stamp: [Cell32::new(0), Cell32::new(0)], @@ -585,7 +585,7 @@ def item(declaration, text=source): render_pair: 0, }); fw.engine.target[0] = 0x100; - fw.graph.compute[0].fw_stamp.set(0x100); + fw.graph.compute[0].user_stamp.set(0x100); fw.retire_on_call = true; let mut done = vec![]; @@ -864,9 +864,9 @@ def item(declaration, text=source): fw.engine.target[0] = 0x100; // Render still running, compute reached its stamp. fw.graph.render[0].user_stamp[1].set(0x100); - fw.graph.compute[0].fw_stamp.set(0x100); + fw.graph.compute[0].user_stamp.set(0x100); assert!(fw.oldest_stamp_reached()); - assert_eq!(fw.graph.compute[0].fw_stamp.reads.get(), 1); + assert_eq!(fw.graph.compute[0].user_stamp.reads.get(), 1); assert_eq!(fw.graph.render[0].user_stamp[1].reads.get(), 0); assert_eq!(fw.oldest_terminal_events(), Some((Some(0), Some(0)))); @@ -890,11 +890,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].user_stamp.set(0x100); + fw2.graph.compute[1].user_stamp.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].user_stamp.reads.get(), 1); + assert_eq!(fw2.graph.compute[1].user_stamp.reads.get(), 1); assert_eq!(fw2.graph.render[0].user_stamp[1].reads.get(), 0); } @@ -911,10 +911,10 @@ def item(declaration, text=source): render_pair: 0, }); fc.engine.target[0] = 0x200; - fc.graph.compute[0].fw_stamp.set(0x100); + fc.graph.compute[0].user_stamp.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].user_stamp.reads.get(), 1); + assert_eq!(fc.graph.compute[1].user_stamp.reads.get(), 0); assert_eq!(fc.graph.render[0].user_stamp[1].reads.get(), 0); // Render-only workload never reads compute fw_stamp. @@ -930,8 +930,8 @@ def item(declaration, text=source): fr.engine.fs_target[0] = 0x200; fr.graph.render[0].user_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].user_stamp.reads.get(), 0); + assert_eq!(fr.graph.compute[1].user_stamp.reads.get(), 0); assert_eq!(fr.graph.render[0].user_stamp[1].reads.get(), 1); } @@ -1240,9 +1240,9 @@ 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; mod sizes { - pub const COMPUTE_PIPES: usize = 8; + pub const COMPUTE_PIPES: usize = 16; pub const RENDER_PAIRS: usize = 2; pub const STAGES: usize = 2 + COMPUTE_PIPES + 2 * (RENDER_PAIRS - 1); pub const fn render_stage(pair: usize, stage: usize) -> usize { @@ -1442,7 +1442,7 @@ def item(declaration, text=source): ring.set_indices(0, 3); let mut ev = Events::default(); ev.drain(&device::Device, &ring).unwrap(); - assert_eq!(sizes::render_stage(1, 0), 10); + assert_eq!(sizes::render_stage(1, 0), 2 + COMPUTE_PIPES); assert_eq!(ev.event_ns[0], 0); assert_eq!(ev.event_ns[1], 12345); assert_eq!(ev.event_ns[sizes::render_stage(1, 0)], 12345); 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 3029c72ba4c04..562421f9b0f02 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;pub const RENDER_PAIRS:usize=2;}} +mod hw{pub mod sizes{pub const COMPUTE_PIPES:usize=16;pub const RENDER_PAIRS:usize=2;}} mod command{pub const RENDER:usize=0;pub const COMPUTE:usize=1;} mod params{ pub fn recovery()->bool{true} @@ -31,7 +31,7 @@ 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],user_stamp:[Object;2]}struct Graph{compute:[Compute;hw::sizes::COMPUTE_PIPES],render:[Render;hw::sizes::RENDER_PAIRS]} +struct Compute{user_stamp:Object}struct Render{fw_stamp:[Object;2],user_stamp:[Object;2]}struct Graph{compute:[Compute;hw::sizes::COMPUTE_PIPES],render:[Render;hw::sizes::RENDER_PAIRS]} struct Job{long:bool} impl Job{fn long(&self)->bool{self.long}} struct Flight{render_pair:u8,job:Job,computes:u32,compute_pipe:u8,renders:u32,target:u32,ta_target:u32,fs_target:u32,published_ns:u64} @@ -75,7 +75,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:core::array::from_fn(|_|Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))],user_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]})}, + let mut f=Firmware{graph:Graph{compute:core::array::from_fn(|_|Compute{user_stamp:Object(Cell::new(previous))}),render:core::array::from_fn(|_|Render{fw_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))],user_stamp:[Object(Cell::new(previous)),Object(Cell::new(previous))]})}, engine:Engine{flights:vec![Flight{render_pair:0,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;hw::sizes::RENDER_PAIRS],fs_target:[target;hw::sizes::RENDER_PAIRS],progress_flight:[0;hw::sizes::COMPUTE_PIPES+hw::sizes::RENDER_PAIRS],progress:[__ZERO__;hw::sizes::COMPUTE_PIPES+2*hw::sizes::RENDER_PAIRS]}, 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 +83,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].user_stamp.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].user_stamp.0.set(0x100);f.progress();assert_eq!(f.render_renewed,0);assert_eq!(f.compute_renewed,0); f.graph.render[0].fw_stamp[0].0.set(0x100);f.progress();assert_eq!(f.render_renewed,1);assert_eq!(f.compute_renewed,0); f.graph.render[0].user_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 +97,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].user_stamp.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 +106,7 @@ def function(text,name): f.engine.flights.push(Flight{render_pair:0,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].user_stamp.0.set(0x300);f.progress();assert_eq!((f.render_renewed,f.compute_renewed),(0,1)); f.graph.render[0].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 +115,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].user_stamp.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].user_stamp.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 +132,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].user_stamp.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 +187,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].user_stamp.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-publication.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py index 61f76d1c23deb..1026841f17864 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. @@ -235,7 +235,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} @@ -295,7 +295,7 @@ def item(declaration): fn invalidate_compute_uma(&mut self){UMA_IDLE.with(|u|{let mut s=u.get();s.invalidations+=1;s.held=false;u.set(s);})} fn compute_exhausted(&self)->bool{self.compute_exhausted} fn render_exhausted(&self)->bool{self.render_exhausted} - fn compute_exhausted_within(&self,_units:usize)->bool{self.compute_exhausted}fn compute_exhausted_in_mask(&self,_mask:u32)->bool{self.compute_exhausted} + 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;} @@ -320,7 +320,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 RENDER_PAIRS:usize=2; pub const STAGES:usize=2+COMPUTE_PIPES+2*(RENDER_PAIRS-1); pub const fn render_stage(pair:usize,stage:usize)->usize{if pair==0{stage}else{2+COMPUTE_PIPES+2*(pair-1)+stage}} pub const FLIGHTS:usize=32; 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; __HEAVY_LIMITS__ } } +mod hw { pub mod sizes { pub const RENDER_PAIRS:usize=2; pub const STAGES:usize=2+COMPUTE_PIPES+2*(RENDER_PAIRS-1); pub const fn render_stage(pair:usize,stage:usize)->usize{if pair==0{stage}else{2+COMPUTE_PIPES+2*(pair-1)+stage}} pub const FLIGHTS:usize=64; 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; __HEAVY_LIMITS__ } } 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())} @@ -866,13 +866,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{ @@ -2018,7 +2018,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{render_pair:0, job:c1.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,rt_compute:false,compute_uma_mask:0,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, @@ -2047,17 +2047,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)); @@ -2069,11 +2069,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{render_pair:0, job:c2.clone(),group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:2,rt_compute:false,compute_uma_mask:0,published_ns:1_000_000,target:0x100, @@ -2081,9 +2081,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)); @@ -2102,7 +2102,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. @@ -2113,8 +2113,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; @@ -2128,7 +2128,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)); @@ -2177,13 +2177,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, @@ -2194,7 +2194,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); @@ -2256,7 +2256,7 @@ def item(declaration): exp_cw[0] = Some(WaitTarget{stamp:0x100,initbm:false,pair:0}); 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,pair:0}))); // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; @@ -2307,7 +2307,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; @@ -3006,8 +3006,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 } @@ -3065,7 +3065,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, @@ -3075,7 +3075,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) } __COMPUTE_QUEUE_IS_HEAVY__ __CAN_DEFER_BUSY_COALESCE__ __DEFER_BUSY_COALESCE__ 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 b5a729567747e..f870ada67c9dc 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -357,7 +357,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)} @@ -372,7 +372,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__ // A VM's live token charged to one file's admission count `live`. @@ -381,7 +382,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: live.clone(), 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) } pub fn test_live_token() -> (mmu::VmBind, Arc, std::sync::Arc) { @@ -389,14 +390,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); @@ -434,14 +435,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 { @@ -949,12 +950,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); @@ -1305,9 +1308,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 { @@ -1317,7 +1322,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(); @@ -2329,7 +2340,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)); @@ -2343,7 +2354,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] { @@ -2716,7 +2727,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::FwCoherent); assert_eq!(c.qinfo.class, Class::FwCached); assert_eq!(c.qscratch.class, Class::FwCached); assert_eq!(c.job_list.class, Class::FwCached); @@ -2726,7 +2737,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::FwCoherent); for stage in 0..2 { assert_eq!(r.qinfo[stage].class, Class::FwCached); assert_eq!(r.qscratch[stage].class, Class::FwCached); @@ -4616,10 +4627,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 471b7ca815b5d..29e394315de9a 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 @@ -30,7 +30,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; pub const RENDER_PAIRS: usize = 2; } } +mod hw { pub mod sizes { pub const COMPUTE_PIPES: usize = 16; pub const RENDER_PAIRS: usize = 2; } } struct Object{cells:BTreeMap,va:u64,unstable:bool,reads:Cell,syncs:Cell} impl Default for Object{fn default()->Self{Self{cells:BTreeMap::new(),va:0x1234,unstable:false,reads:Cell::new(0),syncs:Cell::new(0)}}} impl Object { @@ -154,9 +154,9 @@ def function(text, name): f.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(n+1))); f.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(n+1))); 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].user_stamp.set(0,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].user_stamp.set(0,u64::from(encode::stamp(n))); 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); @@ -230,7 +230,7 @@ def function(text, name): for stage in 0..2 { f2.graph.render[0].fw_stamp[stage].set(0,u64::from(encode::stamp(40))); } f2.graph.render[0].user_stamp[0].set(0,u64::from(encode::stamp(40))); f2.graph.render[0].user_stamp[1].set(0,u64::from(encode::stamp(40))); - f2.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + f2.graph.compute[0].user_stamp.set(0,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(){ @@ -275,9 +275,9 @@ def function(text, name): assert_eq!(fr.retired_flight(),Ok(Some((0,Retirement::Full)))); assert_eq!(fr.graph.render[0].notifier.reads.get(),0); 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[0].user_stamp.reads.get(),0); assert_eq!(fr.graph.compute[1].fw_stamp.reads.get(),0); - assert_eq!(fr.graph.compute[1].notifier.reads.get(),0); + assert_eq!(fr.graph.compute[1].user_stamp.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); fp.graph.render[0].user_stamp[1].set(0,u64::from(encode::stamp(6))); @@ -294,9 +294,10 @@ 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].user_stamp.set(0,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].user_stamp.reads.get(),1); + assert_eq!(fm.graph.compute[0].fw_stamp.reads.get(),0); assert_eq!(fm.graph.render[0].notifier.reads.get(),0); // Pending compute class is not re-polled while retiring a burst of render flights. let mut fmix=firmware(false,30); @@ -309,7 +310,7 @@ def function(text, name): for stage in 0..2 { fmix.graph.render[0].fw_stamp[stage].set(0,u64::from(encode::stamp(41))); } fmix.graph.render[0].user_stamp[0].set(0,u64::from(encode::stamp(41))); fmix.graph.render[0].user_stamp[1].set(0,u64::from(encode::stamp(41))); - fmix.graph.compute[0].fw_stamp.set(0,u64::from(encode::stamp(29))); + fmix.graph.compute[0].user_stamp.set(0,u64::from(encode::stamp(29))); let (mut check_c,mut check_r)=([true;hw::sizes::COMPUTE_PIPES],[true;hw::sizes::RENDER_PAIRS]); 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[0] && !check_r[1]); @@ -317,7 +318,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].user_stamp.reads.get(),1); } /// A render flight of ordinal `n` on render pair 1 whose pair-1 cells show it done. fn pair1_render(f:&mut Firmware,n:u64){ @@ -545,6 +546,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. @@ -637,7 +735,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].user_stamp.set(0,u64::from(encode::stamp(9))); f.graph.compute[1].fw_stamp.set(0,u64::from(encode::stamp(11))); f.graph.compute[1].user_stamp.set(0,u64::from(encode::stamp(11))); assert_eq!(f.retired_flight(),Ok(Some((1,Retirement::Full)))); @@ -646,7 +744,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].user_stamp.set(0,u64::from(encode::stamp(10))); assert_eq!(f.retired_flight(),Ok(Some((0,Retirement::Full)))); assert_eq!(f.last_chan_passed.get(),Some(true)); } 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)