From 23d0ffd82d7d734df8e8804cc88519e78ec05ee9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 11:08:42 -0500 Subject: [PATCH 01/10] drm/asahi/g16: eliminate multi-kilobyte kernel stack frames in probe and hot paths Kernel VMAP_STACK (32 KiB with 16 KiB pages) overflowed in g16::Firmware::start_backend (22,688 B frame) during probe. Keep large G16 boot, backend, scrub, and command-validation structures off the kernel stack: - Allocate ComputeOwners, RenderOwners, Pools, ScrubQueue, GpuAdt, Admitted, Booted, Stats, Prof, Scratch, Firmware, and SpanProof in- place on the heap (KBox::init / KBox::try_init / KBox::zeroed / write_init). - Retain failed Booted/Firmware sessions directly as KBox variants instead of unpacking Firmware back onto the stack with KBox::into_inner. - Bound stack-resident ScrubBatch to 8 displaced slots per pass and drain ScrubQueue entries one-by-one in join_workers. - Reuse heap-resident ValidateScratch inside SpanProof for Prepared::validate and SpanBatch::flush_with_proof. - Mark probe/boot/engine phase boundaries #[inline(never)] so unrelated large frames do not merge. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/fwid.rs | 1 + drivers/gpu/drm/asahi/g16/adt.rs | 26 +- drivers/gpu/drm/asahi/g16/boot.rs | 93 ++++--- drivers/gpu/drm/asahi/g16/command.rs | 226 +++++++++++++----- drivers/gpu/drm/asahi/g16/engine.rs | 36 +-- drivers/gpu/drm/asahi/g16/graph.rs | 2 + drivers/gpu/drm/asahi/g16/initdata.rs | 1 + drivers/gpu/drm/asahi/g16/mod.rs | 146 +++++------ drivers/gpu/drm/asahi/g16/poll.rs | 1 + drivers/gpu/drm/asahi/g16/pools.rs | 26 ++ drivers/gpu/drm/asahi/g16/queue.rs | 2 +- drivers/gpu/drm/asahi/g16/recovery.rs | 1 + drivers/gpu/drm/asahi/g16/sleep.rs | 16 +- drivers/gpu/drm/asahi/g16/slots.rs | 46 +++- .../gpu/asahi-m4/test-command-stream.py | 1 + .../drivers/gpu/asahi-m4/test-resources.py | 3 +- 16 files changed, 427 insertions(+), 200 deletions(-) diff --git a/drivers/gpu/drm/asahi/fwid.rs b/drivers/gpu/drm/asahi/fwid.rs index 62dc0452e7818..2f9d086c3efe0 100644 --- a/drivers/gpu/drm/asahi/fwid.rs +++ b/drivers/gpu/drm/asahi/fwid.rs @@ -287,6 +287,7 @@ impl fmt::Display for Identity { /// Identifies the firmware build loaded at `text` (DATA `data_size` bytes) among `builds`, /// before any firmware-visible write. #[cfg_attr(not(CONFIG_DRM_ASAHI_G16), allow(dead_code))] +#[inline(never)] pub(crate) fn identify( dev: &device::Device, text: Range, diff --git a/drivers/gpu/drm/asahi/g16/adt.rs b/drivers/gpu/drm/asahi/g16/adt.rs index d885732c02194..3c639f054c4ec 100644 --- a/drivers/gpu/drm/asahi/g16/adt.rs +++ b/drivers/gpu/drm/asahi/g16/adt.rs @@ -139,7 +139,8 @@ pub(crate) fn layout(dev: &device::Device) -> Option<&'static hw::FwLayout> { } /// Validates the FDT contract and returns the reserved physical regions, read-only. -pub(crate) fn read(dev: &device::Device) -> Result { +#[inline(never)] +pub(crate) fn read(dev: &device::Device) -> Result> { let node = dev.of_node().ok_or(EINVAL)?; let (version, vas, flags) = handoff(dev)?; let names: KVec = node.get_property(c_str!("memory-region-names"))?; @@ -223,14 +224,17 @@ pub(crate) fn read(dev: &device::Device) -> Result { performance.count ); let [ttbs, tables, handoff, shared_l2, text, data] = regions; - Ok(GpuAdt { - ttbs, - tables, - handoff, - shared_l2, - text, - data, - performance, - layout, - }) + Ok(KBox::init( + init!(GpuAdt { + ttbs, + tables, + handoff, + shared_l2, + text, + data, + performance, + layout, + }), + GFP_KERNEL, + )?) } diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index fdef6c7c908da..353c576b247d1 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -462,7 +462,7 @@ impl Rtkit { /// The result of admission: everything probe-time checks established, nothing written. pub(crate) struct Admitted { pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, } /// The running firmware session: RTKit, MMIO and the adopted UAT. (The @@ -472,7 +472,7 @@ pub(crate) struct Session { pub(crate) shared: Arc, pub(crate) rtkit: Rtkit, pub(crate) regs: regs::Regs, - pub(crate) adt: GpuAdt, + pub(crate) adt: KBox, uat: Arc, /// The PPL handoff page, mapped here only to read the firmware's powered flag /// ([`hw::FwLayout::powered`]); `None` when the firmware keeps the GPU powered. @@ -602,7 +602,7 @@ pub(crate) fn admit( _dev: &AsahiDrmDevice, cfg: &'static Config, res: shared_regs::G16Resources, -) -> Result { +) -> Result> { let dev = pdev.as_ref(); // The board check guards the PMP AGX vote, which only the 25G83 start sends. A firmware // whose handoff names the start without the vote (26B123) rests on the firmware identity @@ -677,7 +677,7 @@ pub(crate) fn admit( return Err(Error::from_errno(-(bindings::EHOSTDOWN as i32))); } dev_info!(dev, "T8132 G16G admitted, ASC={:#x}\n", regs.asc_control()?); - Ok(Admitted { regs, adt }) + Ok(KBox::init(init!(Admitted { regs, adt }), GFP_KERNEL)?) } /// Posts one device control with only the opcode and waits for it. @@ -758,6 +758,7 @@ fn publish_loader_table(session: &Session, init: &InitData, offset: u64) -> Resu } /// Wake the sole firmware instance, publish its loader table, then qualify NOP and policy. +#[inline(never)] fn run( session: &mut Session, events: &mut Events, @@ -900,15 +901,54 @@ fn run( Ok(()) } +/// Retains a failed firmware start out-of-line so [`start`] never reserves an [`Orphan`] slot on +/// its normal stack frame. +#[cold] +#[inline(never)] +fn retain_start_failure( + shared: &Shared, + session: Session, + objects: Objects, + built: Option<(InitData, Channels, u32)>, + events: Events, +) { + let (init, channels) = match built { + Some((init, channels, _)) => (Some(init), Some(channels)), + None => (None, None), + }; + match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => { + let orphan = slot + .write_init(init!(Orphan { + session, + _objects: objects, + channels, + _init: init, + events, + })) + .unwrap_or_else(|e| match e {}); + shared.retain_failed(super::Retained::Orphan(orphan)); + } + Err(_) => { + dev_err!( + shared.dev.as_ref(), + "G16: cannot keep the failed session; leaked\n" + ); + // Without memory for the box, leak the firmware-reachable parts. + core::mem::forget((session, objects, channels, init, events)); + } + } +} + /// Brings the firmware to READY. #[inline(never)] pub(crate) fn start( - admitted: Admitted, + admitted: KBox, dev: &AsahiDrmDevice, cfg: &'static Config, shared: &Arc, -) -> Result { - let Admitted { regs, adt } = admitted; +) -> Result> { + let Admitted { regs, adt } = KBox::into_inner(admitted); let d: ARef = shared.dev.clone(); // Cold ownership must hold before the PMP vote as well as immediately before RUN. if regs.asc_control()? & regs::ASC_RUN != 0 { @@ -1005,6 +1045,13 @@ pub(crate) fn start( return Err(e); } }; + let booted_slot = match KBox::::new_uninit(GFP_KERNEL) { + Ok(slot) => slot, + Err(e) => { + core::mem::forget(objects); + return Err(e.into()); + } + }; let mut session = Session { dev: d.clone(), shared: shared.clone(), @@ -1074,27 +1121,19 @@ pub(crate) fn start( "G16 start failed: {:?}; session retained until reboot\n", e ); - let (init, channels) = match built { - Some((init, channels, _)) => (Some(init), Some(channels)), - None => (None, None), - }; - shared.orphan(Orphan { - session, - _objects: objects, - channels, - _init: init, - events, - }); + retain_start_failure(shared, session, objects, built, events); return Err(e); } let (init, channels, max_frequency_khz) = built.ok_or(EINVAL)?; - Ok(Booted { - session, - init, - objects, - channels, - events, - id, - max_frequency_khz, - }) + Ok(booted_slot + .write_init(init!(Booted { + session, + init, + objects, + channels, + events, + id, + max_frequency_khz, + })) + .unwrap_or_else(|e| match e {})) } diff --git a/drivers/gpu/drm/asahi/g16/command.rs b/drivers/gpu/drm/asahi/g16/command.rs index 10311e618483d..3d6e66ff8bdfd 100644 --- a/drivers/gpu/drm/asahi/g16/command.rs +++ b/drivers/gpu/drm/asahi/g16/command.rs @@ -637,18 +637,16 @@ fn align_span(start: u64, end: u64) -> Result<(u64, u64)> { /// Maximum page-aligned GPUVM spans retained in one logical queue's validation cache. const MAX_PROOF_RANGES: usize = 128; -/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions. -/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never -/// reused across unmaps or remaps. -pub(crate) struct SpanProof { +/// Bounded cache of validated page-aligned GPUVM spans and permissions. +struct ProofCache { epoch: Option, ranges: [(u64, u64, u8); MAX_PROOF_RANGES], count: usize, overflow: bool, } -impl SpanProof { - pub(crate) const fn new() -> Self { +impl ProofCache { + const fn new() -> Self { Self { epoch: None, ranges: [(0, 0, 0); MAX_PROOF_RANGES], @@ -668,7 +666,7 @@ impl SpanProof { }) } - pub(crate) fn invalidate(&mut self) { + fn invalidate(&mut self) { self.epoch = None; self.count = 0; self.overflow = false; @@ -680,13 +678,7 @@ impl SpanProof { .any(|&range| Self::contains(range, req)) } - pub(crate) fn covers_aligned( - &self, - epoch: Option, - first: u64, - size: u64, - access: u8, - ) -> bool { + fn covers_aligned(&self, epoch: Option, first: u64, size: u64, access: u8) -> bool { self.epoch.is_some() && self.epoch == epoch && self.covers_entry((first, size, access)) } @@ -726,7 +718,7 @@ impl SpanProof { self.count += 1; } - pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { if epoch.is_none() { self.invalidate(); return; @@ -761,6 +753,63 @@ impl SpanProof { } } +/// Heap-resident validation scratch paired with [`ProofCache`] so `Prepared::validate` never +/// stages kilobytes of span/command arrays on the kernel stack. +struct ValidateScratch { + batch: SpanBatch, + missing: [(u64, u64, u8); 48], + vdm_vas: [u64; MAX_COMMANDS as usize], + cdm_ranges: [(u64, u64); MAX_COMMANDS as usize], +} + +impl ValidateScratch { + const fn new() -> Self { + Self { + batch: SpanBatch::new(), + missing: [(0, 0, 0); 48], + vdm_vas: [0; MAX_COMMANDS as usize], + cdm_ranges: [(0, 0); MAX_COMMANDS as usize], + } + } +} + +/// One logical queue's bounded cache of validated page-aligned GPUVM spans and permissions, +/// together with reusable scratch buffers for `Prepared::validate`. +/// Mapping mutations invalidate or hide the VM's validation epoch so stale proofs are never +/// reused across unmaps or remaps. +pub(crate) struct SpanProof { + cache: ProofCache, + scratch: ValidateScratch, +} + +impl SpanProof { + #[allow(dead_code)] + pub(crate) const fn new() -> Self { + Self { + cache: ProofCache::new(), + scratch: ValidateScratch::new(), + } + } + + pub(crate) fn invalidate(&mut self) { + self.cache.invalidate(); + } + + pub(crate) fn covers_aligned( + &self, + epoch: Option, + first: u64, + size: u64, + access: u8, + ) -> bool { + self.cache.covers_aligned(epoch, first, size, access) + } + + pub(crate) fn record_one(&mut self, epoch: Option, first: u64, size: u64, access: u8) { + self.cache.record_one(epoch, first, size, access); + } +} + /// Batches page-aligned GPUVM coverage checks under one `gpuvm.lock_inner()` hold while /// preserving exact per-span `ENOENT` / `EACCES` / `EINVAL` error reporting on failure. struct SpanBatch { @@ -820,18 +869,26 @@ impl SpanBatch { Self::report_failure(vm, &self.ranges[..n]) } - fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { + fn clear(&mut self) { + self.len = 0; + } + + fn flush_with_proof_parts( + &mut self, + vm: &mmu::Vm, + cache: &mut ProofCache, + missing: &mut [(u64, u64, u8); 48], + ) -> Result { let n = self.len; if n == 0 { return Ok(()); } self.len = 0; let epoch = vm.mapping_validation_epoch(); - if proof.epoch.is_some() && proof.epoch == epoch { - let mut missing = [(0u64, 0u64, 0u8); 48]; + if cache.epoch.is_some() && cache.epoch == epoch { let mut missing_len = 0usize; for &req in &self.ranges[..n] { - if !proof.covers_entry(req) { + if !cache.covers_entry(req) { missing[missing_len] = req; missing_len += 1; } @@ -840,30 +897,35 @@ impl SpanBatch { return Ok(()); } let (mut covered, mut walked) = vm.covers_ranges_batch(&missing[..missing_len]); - if covered && walked != proof.epoch { + if covered && walked != cache.epoch { (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); } if covered { - proof.record_slice(walked, &self.ranges[..n]); + cache.record_slice(walked, &self.ranges[..n]); return Ok(()); } - proof.invalidate(); + cache.invalidate(); return Self::report_failure(vm, &self.ranges[..n]); } let (covered, walked) = vm.covers_ranges_batch(&self.ranges[..n]); if covered { - proof.record_slice(walked, &self.ranges[..n]); + cache.record_slice(walked, &self.ranges[..n]); return Ok(()); } - proof.invalidate(); + cache.invalidate(); Self::report_failure(vm, &self.ranges[..n]) } - fn flush_locked_with_proof( + #[allow(dead_code)] + fn flush_with_proof(&mut self, vm: &mmu::Vm, proof: &mut SpanProof) -> Result { + self.flush_with_proof_parts(vm, &mut proof.cache, &mut proof.scratch.missing) + } + + fn flush_locked_with_cache( &mut self, guard: &mut mmu::VmReadGuard<'_>, epoch: Option, - proof: &mut SpanProof, + cache: &mut ProofCache, ) -> Result { let n = self.len; if n == 0 { @@ -872,14 +934,14 @@ impl SpanBatch { self.len = 0; let mut had_miss = false; for &(first, size, access) in &self.ranges[..n] { - if proof.covers_aligned(epoch, first, size, access) { + if cache.covers_aligned(epoch, first, size, access) { continue; } had_miss = true; let read = access & 1 != 0; let write = access & 2 != 0; if !guard.covers_range(first, size, read, write) { - proof.invalidate(); + cache.invalidate(); return if guard.covers_range(first, size, false, false) { Err(EACCES) } else { @@ -888,10 +950,20 @@ impl SpanBatch { } } if had_miss { - proof.record_slice(epoch, &self.ranges[..n]); + cache.record_slice(epoch, &self.ranges[..n]); } Ok(()) } + + #[allow(dead_code)] + fn flush_locked_with_proof( + &mut self, + guard: &mut mmu::VmReadGuard<'_>, + epoch: Option, + proof: &mut SpanProof, + ) -> Result { + self.flush_locked_with_cache(guard, epoch, &mut proof.cache) + } } /// Attachment spans, 128-byte granular, actually mapped with `write` or read access. @@ -1434,6 +1506,34 @@ impl ParsedStream { } } +impl SpanProof { + /// Allocates a [`SpanProof`] directly on the heap without staging its range or scratch arrays + /// on the kernel stack. + #[inline(never)] + pub(crate) fn new_boxed() -> Result> { + Ok(KBox::init( + init!(Self { + cache <- init!(ProofCache { + epoch: None, + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + count: 0, + overflow: false, + }), + scratch <- init!(ValidateScratch { + batch <- init!(SpanBatch { + ranges <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + len: 0, + }), + missing <- ::pin_init::init_array_from_fn(|_| (0, 0, 0)), + vdm_vas <- ::pin_init::init_array_from_fn(|_| 0), + cdm_ranges <- ::pin_init::init_array_from_fn(|_| (0, 0)), + }), + }), + GFP_KERNEL, + )?) + } +} + impl Prepared { /// Checks each command's spans, programs and stream gates, with a job reference on the VM /// already held so that the checked mappings are retained until the job retires. @@ -1450,35 +1550,40 @@ impl Prepared { if commands.is_empty() { return Err(EINVAL); } - let mut batch = SpanBatch::new(); - let mut vdm_vas = [0u64; MAX_COMMANDS as usize]; let mut vdm_count = 0usize; - let mut cdm_ranges = [(0u64, 0u64); MAX_COMMANDS as usize]; let mut cdm_count = 0usize; - for command in commands.iter() { - match command { - Command::Render(render) => { - check_render( - &mut batch, - context, - &render.cmd, - &render.vertex_attachments, - &render.fragment_attachments, - )?; - if vdm_count >= vdm_vas.len() { - return Err(EINVAL); + { + let scratch = &mut proof.scratch; + scratch.batch.clear(); + for command in commands.iter() { + match command { + Command::Render(render) => { + check_render( + &mut scratch.batch, + context, + &render.cmd, + &render.vertex_attachments, + &render.fragment_attachments, + )?; + if vdm_count >= scratch.vdm_vas.len() { + return Err(EINVAL); + } + scratch.vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; + vdm_count += 1; } - vdm_vas[vdm_count] = render.cmd.vdm_ctrl_stream_base; - vdm_count += 1; - } - Command::Compute(compute) => { - let range = - check_compute(&mut batch, context, &compute.cmd, &compute.attachments)?; - if cdm_count >= cdm_ranges.len() { - return Err(EINVAL); + Command::Compute(compute) => { + let range = check_compute( + &mut scratch.batch, + context, + &compute.cmd, + &compute.attachments, + )?; + if cdm_count >= scratch.cdm_ranges.len() { + return Err(EINVAL); + } + scratch.cdm_ranges[cdm_count] = range; + cdm_count += 1; } - cdm_ranges[cdm_count] = range; - cdm_count += 1; } } } @@ -1495,12 +1600,14 @@ impl Prepared { let mut guard = Some(context.vm.read_lock().map_err(|_| EFAULT)?); let mut epoch = guard.as_ref().and_then(|g| g.epoch()); if let Some(g) = guard.as_mut() { - batch.flush_locked_with_proof(g, epoch, proof)?; + let SpanProof { cache, scratch } = proof; + scratch.batch.flush_locked_with_cache(g, epoch, cache)?; if need_vdm { - gate::vdm_batch_locked(g, &vdm_vas[..vdm_count])?; + gate::vdm_batch_locked(g, &scratch.vdm_vas[..vdm_count])?; } } - for &(base, end) in &cdm_ranges[..cdm_count] { + for i in 0..cdm_count { + let (base, end) = proof.scratch.cdm_ranges[i]; gate::cdm_locked( context.vm, &mut guard, @@ -1512,7 +1619,10 @@ impl Prepared { )?; } } else { - batch.flush_with_proof(context.vm, proof)?; + let SpanProof { cache, scratch } = proof; + scratch + .batch + .flush_with_proof_parts(context.vm, cache, &mut scratch.missing)?; } Ok(Submission { counts, diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 6d7286fdd6610..53e5d968c6467 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -407,7 +407,7 @@ enum PublicationError { } /// Engine statistics, printed by `aurora-g16/stats`. -#[derive(Default)] +#[derive(Default, Zeroable)] pub(crate) struct Stats { pub(crate) pub_ns: u64, pub(crate) idle_from_ns: u64, @@ -465,7 +465,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)] +#[derive(Default, Zeroable)] pub(crate) struct Prof { /// Published prefixes timed. pub(crate) prefixes: u64, @@ -520,17 +520,21 @@ struct Scratch { } impl Scratch { - fn new() -> Result { + #[inline(never)] + fn new_boxed() -> Result> { let z = |n| KVec::from_elem(0u8, n, GFP_KERNEL); - Ok(Self { - cw: z(work::compute::WORK_SIZE)?, - cq: z(work::compute::SEQ_SIZE)?, - ta: z(work::ta::WORK_SIZE)?, - tas: z(work::ta::SEQ_SIZE)?, - fs: z(work::fs::WORK_SIZE)?, - fss: z(work::fs::SEQ_SIZE)?, - scene: z(work::scene::ACTIVE_SIZE)?, - }) + KBox::try_init( + try_init!(Self { + cw: z(work::compute::WORK_SIZE)?, + cq: z(work::compute::SEQ_SIZE)?, + ta: z(work::ta::WORK_SIZE)?, + tas: z(work::ta::SEQ_SIZE)?, + fs: z(work::fs::WORK_SIZE)?, + fss: z(work::fs::SEQ_SIZE)?, + scene: z(work::scene::ACTIVE_SIZE)?, + }), + GFP_KERNEL, + ) } } @@ -601,6 +605,7 @@ pub(crate) struct Engine { } impl Engine { + #[inline(never)] pub(crate) fn new() -> Result { // Wrapped native stamps are safe only while pending references fit within the // signed half-window: at most FLIGHTS commands are published at once, far inside it. @@ -633,12 +638,12 @@ impl Engine { short_repoll: false, progress_flight: [0; 3], progress: [None; 4], - stats: KBox::new(Stats::default(), GFP_KERNEL)?, - prof: KBox::new(Prof::default(), GFP_KERNEL)?, + stats: KBox::zeroed(GFP_KERNEL)?, + prof: KBox::zeroed(GFP_KERNEL)?, debugfs: None, // Allocate host encoder buffers before any submitted fence can depend on // the device mutex. Publication must never enter direct reclaim here. - scratch: Some(KBox::new(Scratch::new()?, GFP_KERNEL)?), + scratch: Some(Scratch::new_boxed()?), }) } @@ -1844,6 +1849,7 @@ impl Firmware { /// producer writes and queue kicks. EAGAIN defers while storage/channel state is held; /// The error records whether firmware may see a counter/producer update, independently /// of errno; unpublished EIO is still an ordinary job failure. + #[inline(never)] fn publish_prefix( &mut self, job: &Arc, diff --git a/drivers/gpu/drm/asahi/g16/graph.rs b/drivers/gpu/drm/asahi/g16/graph.rs index 4514454acbe15..f23f4936ab3aa 100644 --- a/drivers/gpu/drm/asahi/g16/graph.rs +++ b/drivers/gpu/drm/asahi/g16/graph.rs @@ -278,6 +278,7 @@ pub(crate) struct Graphs { pub(crate) render: RenderGraph, } impl Graphs { + #[inline(never)] pub(crate) fn new(dev: &AsahiDrmDevice, o: &mut Objects) -> Result { // Host polls sched_ctx from WC during register_context(); keep uncached and share one // scheduling context across all compute pipes and the render graph. @@ -295,6 +296,7 @@ impl Graphs { } } impl Firmware { + #[inline(never)] pub(crate) fn init_graphs(&mut self) -> Result { for ch in [Channel::Ta, Channel::Fs, Channel::Compute] { if self.channels.read(ch)? != 0 || self.channels.write_cell(ch)? != 0 { diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index 01861b790a62d..e4898529be5c7 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -93,6 +93,7 @@ fn pair(graph: &[Arc], state: usize, ring: usize) -> Ring { /// Builds the complete unpublished M4 graph. The return shape is shared with /// the other backend, while all object layouts and policy are M4-specific. +#[inline(never)] pub(crate) fn build( dev: &device::Device, adt: &GpuAdt, diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 670a85634528a..30c26d3bc62a5 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -206,6 +206,33 @@ const WAIT_HINT_GAP_NS: u64 = 4_000_000; const WAIT_HINT_STREAK_ON: u32 = 8; const WAIT_HINT_LINGER_NS: u64 = 8_000_000; +/// A firmware session retained until reboot after a failed boot or backend start. +pub(crate) enum Retained { + Orphan(KBox), + Booted(KBox), + Firmware(KBox), +} + +impl Retained { + fn drain(&mut self) -> Result { + match self { + Self::Orphan(orphan) => orphan.drain(), + Self::Booted(booted) => { + let booted = &mut **booted; + booted + .channels + .drain_rings(&booted.session.dev, &mut booted.events) + } + Self::Firmware(firmware) => { + let firmware = &mut **firmware; + firmware + .channels + .drain_rings(&firmware.session.dev, &mut firmware.events) + } + } + } +} + /// Device state shared with the RTKit callbacks and the poll work. #[pin_data] pub(crate) struct Shared { @@ -282,7 +309,7 @@ pub(crate) struct Shared { /// Dedicated unbound workqueue for cpufreq `FREQ_QOS_MIN` updates outside `Shared::state`. pub(crate) feed_wq: OwnedQueue, #[pin] - pub(crate) orphan: Mutex>>, + pub(crate) orphan: Mutex>, #[pin] pub(crate) poll: DelayedWork, #[pin] @@ -290,7 +317,7 @@ pub(crate) struct Shared { #[pin] pub(crate) fast_poll_unbound: Work, #[pin] - pub(crate) scrub_queue: SpinLock, + pub(crate) scrub_queue: SpinLock>, #[pin] pub(crate) scrub_work: Work, #[pin] @@ -499,36 +526,26 @@ impl Shared { /// Keeps a firmware session that did not complete until reboot; its receive rings stay /// drained by the poll work. - pub(crate) fn orphan(&self, orphan: boot::Orphan) { + #[cold] + #[inline(never)] + pub(crate) fn retain_failed(&self, retained: Retained) { let mut slot = self.orphan.lock(); if slot.is_some() { // Never replace and drop an already firmware-reachable session. - core::mem::forget(orphan); + core::mem::forget(retained); dev_err!( self.dev.as_ref(), "G16: additional failed session retained without drain\n" ); return; } - match KBox::::new_uninit(GFP_KERNEL) { - Ok(storage) => { - *slot = Some(KBox::write(storage, orphan)); - self.orphaned.store(true, Ordering::Release); - } - // Without memory for the box, leak the parts as they are. - Err(_) => { - core::mem::forget(orphan); - dev_err!( - self.dev.as_ref(), - "G16: cannot keep the failed session; leaked\n" - ); - } - } + *slot = Some(retained); + self.orphaned.store(true, Ordering::Release); } /// Drains the receive rings of an orphaned session. fn drain_orphan(&self) { - if let Some(orphan) = self.orphan.lock().as_deref_mut() { + if let Some(orphan) = &mut *self.orphan.lock() { let _ = orphan.drain(); } } @@ -562,7 +579,7 @@ pub(crate) struct Firmware { /// PMP thermal vote and firmware DVFS ceiling state. pub(crate) power: power::Power, /// Render UMA/PB allocators, their spare set and parameter-buffer growth. - pub(crate) pools: pools::Pools, + pub(crate) pools: KBox, /// Live VMs and their exclusive TTBAT slots, and the client aliases of every user VM. pub(crate) vms: Arc, /// Monotonic timestamp (ns) of the last full housekeeping pass (power, health, hang poll). @@ -591,6 +608,7 @@ impl Gpu { /// Admits and boots a G16 GPU: identity checks, PMP AGX vote, RTKit, UAT handoff, initdata, /// READY, then the compute and render graphs. On success the module is pinned: the /// firmware session lasts until reboot. + #[inline(never)] pub(crate) fn new( pdev: &platform::Device>, dev: &AsahiDrmDevice, @@ -610,6 +628,7 @@ impl Gpu { let scrub_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)?; let feed = feed::Feed::new()?; let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; + let scrub_queue = slots::ScrubQueue::new_boxed()?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -650,7 +669,7 @@ impl Gpu { poll <- new_delayed_work!("g16::Shared::poll"), fast_poll <- new_work!("g16::Shared::fast_poll"), fast_poll_unbound <- new_work!("g16::Shared::fast_poll_unbound"), - scrub_queue <- new_spinlock!(slots::ScrubQueue::new(), "g16::Shared::scrub_queue"), + scrub_queue <- new_spinlock!(scrub_queue, "g16::Shared::scrub_queue"), scrub_work <- new_work!("g16::Shared::scrub_work"), feed_work <- new_work!("g16::Shared::feed_work"), resnap <- HrTimer::new(), @@ -705,48 +724,19 @@ impl Firmware { #[inline(never)] fn start_backend( dev: &AsahiDrmDevice, - booted: boot::Booted, + mut booted: KBox, shared: &Arc, mut power: power::Power, ) -> Result> { - let boot::Booted { - session, - init, - mut objects, - channels, - events, - .. - } = booted; dev_info!( dev.as_ref(), "G16: firmware at READY, starting the backend\n" ); - power.set_table(init.rows); - let orphan = |session: boot::Session, - objects: object::Objects, - channels: channel::Channels, - init: initdata::InitData, - events: event::Events, - error: Error| - -> Error { - dev_err!( - dev.as_ref(), - "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", - error - ); - shared.orphan(boot::Orphan { - session, - _objects: objects, - channels: Some(channels), - _init: Some(init), - events, - }); - error - }; + power.set_table(booted.init.rows); let backend = (|| -> Result<_> { - let graph = graph::Graphs::new(dev, &mut objects)?; + let graph = graph::Graphs::new(dev, &mut booted.objects)?; let slots = slots::Slots::new()?; - let pools = pools::Pools::new(dev); + let pools = pools::Pools::new_boxed(dev)?; let vms = vm::Registry::new()?; let engine = engine::Engine::new()?; let slot = KBox::::new_uninit(GFP_KERNEL)?; @@ -754,14 +744,30 @@ impl Firmware { })(); let (graph, slots, pools, vms, engine, slot) = match backend { Ok(backend) => backend, - Err(e) => return Err(orphan(session, objects, channels, init, events, e)), + Err(error) => { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Booted(booted)); + return Err(error); + } }; - let mut firmware = KBox::write( - slot, - Firmware { + let boot::Booted { + session, + init, + mut objects, + channels, + events, + .. + } = KBox::into_inner(booted); + let private_factory = objects.private_factory(); + let mut firmware = slot + .write_init(init!(Firmware { session, init, - private_factory: objects.private_factory(), + private_factory, objects, channels, events, @@ -774,18 +780,16 @@ impl Firmware { vms, last_housekeeping_ns: 0, last_aux_drain_ns: 0, - }, - ); - if let Err(e) = firmware.init_graphs() { - let Firmware { - session, - init, - objects, - channels, - events, - .. - } = KBox::into_inner(firmware); - return Err(orphan(session, objects, channels, init, events, e)); + })) + .unwrap_or_else(|e| match e {}); + if let Err(error) = firmware.init_graphs() { + dev_err!( + dev.as_ref(), + "G16: backend start failed ({:?}); firmware retained at READY until reboot\n", + error + ); + shared.retain_failed(Retained::Firmware(firmware)); + return Err(error); } Ok(firmware) } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 61567df95f16b..cdc0359c33a0c 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1358,6 +1358,7 @@ impl Firmware { /// Retire the flight at `index` (the oldest of its engine class). Only a full normal receipt /// retires its storage; a passed abort quarantines it. Job failure independently drops /// remaining unpublished commands even when the storage fully retired. + #[inline(never)] pub(crate) fn retire_oldest( &mut self, index: usize, diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index c186086064292..54306b109d66c 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -380,6 +380,7 @@ pub(crate) struct Pools { quarantined_epochs: [Option>; sizes::PB_SLOTS], } impl Pools { + #[allow(dead_code)] pub(crate) fn new(dev: &AsahiDrmDevice) -> Self { Self { dev: dev.as_ref().as_ref().into(), @@ -398,6 +399,31 @@ impl Pools { quarantined_epochs: [const { None }; sizes::PB_SLOTS], } } + /// Allocates [`Pools`] directly on the heap so probe/backend bring-up does not stage the + /// per-slot lease arrays on the kernel stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed(dev: &AsahiDrmDevice) -> Result> { + Ok(KBox::init( + init!(Self { + dev: dev.as_ref().as_ref().into(), + stats: PbStats::default(), + owners: [const { None }; sizes::PB_SLOTS], + owner_vms: [const { None }; sizes::PB_SLOTS], + owner_arenas: [const { None }; sizes::PB_SLOTS], + pending_vms: [const { None }; sizes::PB_SLOTS], + pending_arenas: [const { None }; sizes::PB_SLOTS], + binds: [0; sizes::PB_SLOTS], + keep: [false; sizes::PB_SLOTS], + active: None, + last_clean_retired: None, + inflight: [0; sizes::PB_SLOTS], + quarantined: [false; sizes::PB_SLOTS], + quarantined_epochs: [const { None }; sizes::PB_SLOTS], + }), + GFP_KERNEL, + )?) + } /// Number of contiguous PB/UMA allocator slots (`0..n`) each rendering VM should prepare /// so at least [`sizes::BASE_PB_SLOTS`] healthy slots remain available across quarantines. #[allow(dead_code)] diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 08cf2543c9c24..4dc9d7d2f837c 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -198,7 +198,7 @@ impl Queue { }, GFP_KERNEL, )?; - let proof = KBox::new(command::SpanProof::new(), GFP_KERNEL)?; + let proof = command::SpanProof::new_boxed()?; Ok(Self { scheduler, state, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 9f20506a0b0f9..8e9b9a61e3bab 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -172,6 +172,7 @@ impl Firmware { /// Protocol errors and transport loss always retain uncertain owners. /// A deadline without a firmware recovery notification is not permission /// to manipulate undocumented preemption controls. + #[inline(never)] pub(crate) fn check_hangs(&mut self, done: &mut Completions) -> Result { if let Some(error) = self.recovery.failed { return Err(error); diff --git a/drivers/gpu/drm/asahi/g16/sleep.rs b/drivers/gpu/drm/asahi/g16/sleep.rs index 261d872d2113a..08ae0c679aa88 100644 --- a/drivers/gpu/drm/asahi/g16/sleep.rs +++ b/drivers/gpu/drm/asahi/g16/sleep.rs @@ -115,14 +115,16 @@ impl Shared { } self.events.drain(); self.events_unbound.drain(); - // `sleeping` is already set, so taking the queued scrubs under `scrub_queue` + // `sleeping` is already set, so draining queued scrubs under `scrub_queue` // guarantees no concurrent `enqueue_scrubs()` can still queue onto `scrub_wq` - // while `scrub_wq.drain()` runs. Drop the drained batch outside the spinlock. - let pending_scrubs = { - let mut queue = self.scrub_queue.lock(); - core::mem::replace(&mut *queue, super::slots::ScrubQueue::new()) - }; - drop(pending_scrubs); + // while `scrub_wq.drain()` runs. Drop each drained item outside the spinlock. + loop { + let item = self.scrub_queue.lock().pop(); + let Some(item) = item else { + break; + }; + drop(item); + } self.scrub_wq.drain(); self.feed.pause(); self.feed_wq.drain(); diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 7bcb1ca24913c..7a4cfeb10aeb6 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -594,16 +594,21 @@ impl Drop for PendingScrub { } } +/// Maximum displaced render pass slots staged in one stack-resident [`ScrubBatch`]. +/// Keeping the batch bounded avoids multi-kilobyte stack frames in poll/submit paths while +/// any additional displaced slots remain flagged for the next pass. +const MAX_SCRUB_BATCH: usize = 8; + /// Zero-allocation batch of displaced render pass slots to scrub after dropping `Shared::state`. pub(crate) struct ScrubBatch { - items: [Option; sizes::RENDER_SLOTS], + items: [Option; MAX_SCRUB_BATCH], len: usize, } impl ScrubBatch { pub(crate) const fn new() -> Self { Self { - items: [const { None }; sizes::RENDER_SLOTS], + items: [const { None }; MAX_SCRUB_BATCH], len: 0, } } @@ -612,8 +617,12 @@ impl ScrubBatch { self.len == 0 } + fn is_full(&self) -> bool { + self.len >= MAX_SCRUB_BATCH + } + fn push(&mut self, item: PendingScrub) -> bool { - if self.len >= sizes::RENDER_SLOTS { + if self.len >= MAX_SCRUB_BATCH { return false; } self.items[self.len] = Some(item); @@ -637,6 +646,19 @@ impl ScrubQueue { } } + /// Allocates an empty [`ScrubQueue`] directly on the heap to keep `Shared` setup off the + /// probe stack. + #[allow(dead_code)] + #[inline(never)] + pub(crate) fn new_boxed() -> Result> { + Ok(KBox::init( + init!(Self { + slots: [const { None }; sizes::RENDER_SLOTS], + }), + GFP_KERNEL, + )?) + } + /// Moves every staged scrub from `batch` into the queue. Returns `true` if any was queued. pub(crate) fn push_batch(&mut self, mut batch: ScrubBatch) -> bool { let mut pushed = false; @@ -698,6 +720,7 @@ pub(crate) struct Slots { render: KBox, } impl Slots { + #[inline(never)] pub(crate) fn new() -> Result { Ok(Self { cursor: 0, @@ -706,8 +729,8 @@ impl Slots { scrub_gen: 0, stats: SlotStats::default(), scrub: Arc::new(ScrubState::new(), GFP_KERNEL)?, - compute: KBox::new( - ComputeOwners { + compute: KBox::init( + init!(ComputeOwners { lifetime: Lifetime::new(true), owner: [const { None }; sizes::COMPUTE_UNITS], pending_retarget: [None; sizes::COMPUTE_UNITS], @@ -716,11 +739,11 @@ impl Slots { pending_arena: [const { None }; sizes::COMPUTE_UNITS], scrub_full: [true; sizes::COMPUTE_UNITS], last_full: [true; sizes::COMPUTE_UNITS], - }, + }), GFP_KERNEL, )?, - render: KBox::new( - RenderOwners { + render: KBox::init( + init!(RenderOwners { lifetime: Lifetime::new(true), owner: [const { None }; sizes::RENDER_SLOTS], pending_retarget: [None; sizes::RENDER_SLOTS], @@ -731,7 +754,7 @@ impl Slots { last_full: [true; sizes::RENDER_SLOTS], staged: ScrubBatch::new(), scrub_pending: false, - }, + }), GFP_KERNEL, )?, }) @@ -876,6 +899,10 @@ impl Slots { let Some(arena) = self.render.arena[k].clone() else { continue; }; + if self.render.staged.is_full() { + self.render.scrub_pending = true; + break; + } self.scrub.scrubbing.fetch_or(bit, Ordering::SeqCst); let generation = self.scrub.generation.load(Ordering::Acquire); let item = PendingScrub { @@ -886,6 +913,7 @@ impl Slots { done: false, }; if !self.render.staged.push(item) { + self.render.scrub_pending = true; break; } } diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py index 4b85232352011..3d1e261e301bc 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-command-stream.py @@ -697,6 +697,7 @@ pub(crate) vm: &'a mmu::Vm, pub(crate) usc_base: u64, } + use super::MAX_COMMANDS; RENDER_ADMISSION fn check_render_one( 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 5f3741b9824d6..be994dc4e53eb 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -44,9 +44,10 @@ def module(text, name): pub const ETIMEDOUT:Error=Error(110);pub const ERESTARTSYS:Error=Error(512); pub const GFP_KERNEL:u32=0; pub type Result = std::result::Result; +macro_rules! init { ($($tt:tt)*) => { $($tt)* }; } pub mod prelude {pub use crate::{Result,KVec,KBox,GFP_KERNEL,EINVAL,EAGAIN,E2BIG,EBUSY,EOVERFLOW,EIO,ETIMEDOUT,ERESTARTSYS};} pub struct KBox(Box); -implKBox{pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))}} +implKBox{pub fn new(x:T,_:u32)->Result{Ok(Self(Box::new(x)))} pub fn init(x:T,_:u32)->Result{Ok(Self(Box::new(x)))}} implstd::ops::Deref for KBox{type Target=T;fn deref(&self)->&T{&self.0}} implstd::ops::DerefMut for KBox{fn deref_mut(&mut self)->&mut T{&mut self.0}} pub struct KVec(Vec); From 6a873a29fcb9d7ab66d273bfdd6ab6339f2fa2a9 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 08:32:53 -0500 Subject: [PATCH 02/10] drm/asahi: g16: resolve same-VM cross-queue fences into firmware barriers Cross-queue Vulkan binary and timeline semaphore waits on the same G16 device and VM previously fell through to drm_sched, forcing the producer job to retire on the CPU and wake the scheduler worker before the consumer could enter the engine. Tag G16 queue output fences with their originating GPU, VM, queue, and per-engine ordinals (FenceOrigin), and mark the origin enqueued once Firmware::enqueue accepts the job. On submission, walk the input fence tree via g17::sync_input::collect and, when every unsignalled leaf is an already-enqueued same-GPU same-VM G16 fence (bounded to 8 waits), convert them into job.fw_waits so try_start_inline hands the consumer straight to the firmware engine. Extend dependency checking, timestamp-query serialization, compute and render stamp resolution, single-pipe compute selection, and transitive failure doom propagation in poll.rs to cover job.fw_waits, while keeping horizon folding disabled when cross-queue waits are present. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 301 ++++++++++++------ drivers/gpu/drm/asahi/g16/fence.rs | 197 +++++++++++- drivers/gpu/drm/asahi/g16/job.rs | 43 ++- drivers/gpu/drm/asahi/g16/poll.rs | 29 +- drivers/gpu/drm/asahi/g16/queue.rs | 28 +- drivers/gpu/drm/asahi/g17/mod.rs | 2 +- drivers/gpu/drm/asahi/g17/sync_input.rs | 8 +- .../drivers/gpu/asahi-m4/test-job-failure.py | 67 +++- .../drivers/gpu/asahi-m4/test-publication.py | 129 ++++++-- 9 files changed, 662 insertions(+), 142 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 53e5d968c6467..8e098a6e0eed0 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -929,6 +929,7 @@ impl Firmware { } self.engine.pending.push(job.clone(), GFP_NOWAIT)?; job.progress.set_pending(true); + job.origin.mark_enqueued(); let q = &job.queue; let owned = self.engine.queue_published(&job) + self @@ -1418,7 +1419,7 @@ impl Firmware { // retirement, so dispatches without DRM_ASAHI_COMPUTE_NO_QUERY_ACCESS must wait // for prior timestamped flights in their dependency prefix to retire first. let waits_for_timestamps = c.query_access - && job.command_order(sent).is_some_and(|o| { + && (job.command_order(sent).is_some_and(|o| { let waits_class = |class: usize| { o.wait_through[class].is_some_and(|last| { e.flights.iter().any(|f| { @@ -1437,7 +1438,25 @@ impl Firmware { }) }; waits_class(super::command::COMPUTE) || waits_class(super::command::RENDER) - }); + }) || job.fw_waits.iter().any(|w| { + (0..2).any(|class| { + w.last_ordinal[class].is_some_and(|last| { + e.flights.iter().any(|f| { + let matches_class = if class == super::command::RENDER { + f.renders != 0 + } else { + f.computes != 0 + }; + matches_class + && f.has_timestamps + && Arc::ptr_eq(&f.job.queue, &w.queue) + && f.job + .command_order(f.first as u32) + .is_none_or(|fo| fo.sequence <= last) + }) + }) + }) + })); let cross_vm_render = e .flights .iter() @@ -1481,10 +1500,10 @@ impl Firmware { } } - /// Resolves a same-queue target stamp and producer `InitBM` state for `class` (`RENDER` -> - /// `r_fs_stamp`, `COMPUTE` -> `cstamp`) when `target_seq` names an in-flight command of - /// `job.queue` or an earlier member of an in-progress render batch `current`. Returns - /// `Ok(None)` when no barrier was requested or the waited prefix has already retired. + /// Resolves the newest in-flight target stamp and producer `InitBM` state for `class` + /// (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`) across `job`'s same-queue `target_seq` + /// and any cross-queue `job.fw_waits` (plus an earlier member of an in-progress render batch + /// `current`). Returns `Ok(None)` when no barrier is needed or every waited prefix retired. fn wait_stamp_for_with( &self, job: &Arc, @@ -1492,97 +1511,128 @@ impl Firmware { target_seq: Option, current: Option<&Flight>, ) -> Result> { - let Some(last) = target_seq else { - return Ok(None); - }; - if job.queue.completed[class].load(Ordering::Acquire) >= last { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[class].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[class] else { + continue; + }; + if wait.queue.completed[class].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { return Ok(None); } - if class == super::command::COMPUTE { - for flight in &self.engine.flights { - if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { - continue; - } - let mut member = 0usize; - for k in flight.first..flight.first + flight.count { - if flight.job.command_order(k as u32).is_some_and(|fo| { - fo.engine == super::command::COMPUTE && fo.sequence == last - }) { - return Ok(Some(WaitTarget { - stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, - initbm: flight.initbm, - })); - } - member += 1; - } - for j2 in flight.group.iter() { - for k in 0..j2.progress.count() { - if j2.command_order(k).is_some_and(|fo| { - fo.engine == super::command::COMPUTE && fo.sequence == last - }) { - return Ok(Some(WaitTarget { - stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, - initbm: flight.initbm, - })); - } - member += 1; - } + let mut newest: Option = None; + let scan_flight = |flight: &Flight, + targets: &mut [Option<(&Arc, u64, bool)>], + newest: &mut Option| + -> Result { + if class == super::command::COMPUTE { + if flight.computes == 0 { + return Ok(()); } + } else if flight.renders == 0 { + return Ok(()); } - return Err(EAGAIN); - } - let find_render = |flight: &Flight| -> Option { - if flight.renders == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { - return None; + if !targets + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { + return Ok(()); } - let max_members = (flight.renders as usize).min(flight.r_fs_stamp.len()); + let max_members = if class == super::command::COMPUTE { + (flight.computes as usize).min(flight.cstamp.len()) + } else { + (flight.renders as usize).min(flight.r_fs_stamp.len()) + }; let mut member = 0usize; for k in flight.first..flight.first + flight.count { if member >= max_members { - return None; + break; } - if flight - .job - .command_order(k as u32) - .is_some_and(|fo| fo.engine == super::command::RENDER && fo.sequence == last) - { - return Some(WaitTarget { - stamp: flight.r_fs_stamp[member], - initbm: flight.initbm, - }); + if let Some(fo) = flight.job.command_order(k as u32) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } } member += 1; } for j2 in flight.group.iter() { for k in 0..j2.progress.count() { if member >= max_members { - return None; + break; } - if j2.command_order(k).is_some_and(|fo| { - fo.engine == super::command::RENDER && fo.sequence == last - }) { - return Some(WaitTarget { - stamp: flight.r_fs_stamp[member], - initbm: flight.initbm, - }); + if let Some(fo) = j2.command_order(k) { + if fo.engine == class { + for (q, last, found) in targets.iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence == *last { + *found = true; + let stamp = if class == super::command::COMPUTE { + flight.cstamp[member] + } else { + flight.r_fs_stamp[member] + }; + *newest = Some(WaitTarget { + stamp, + initbm: flight.initbm, + }); + } + } + } } member += 1; } } - None + Ok(()) }; - if let Some(target) = current.and_then(find_render) { - return Ok(Some(target)); - } for flight in &self.engine.flights { - if let Some(target) = find_render(flight) { - return Ok(Some(target)); - } + scan_flight(flight, &mut targets[..count], &mut newest)?; + } + if let Some(cur) = current { + scan_flight(cur, &mut targets[..count], &mut newest)?; } - Err(EAGAIN) + if targets[..count].iter().flatten().any(|(_, _, found)| !*found) { + return Err(EAGAIN); + } + Ok(newest) } - /// Resolves a same-queue target stamp for `class` across published in-flight flights. + /// Resolves a same-queue or cross-queue target stamp for `class` across published flights. fn wait_stamp_for( &self, job: &Arc, @@ -1592,10 +1642,9 @@ impl Firmware { self.wait_stamp_for_with(job, class, target_seq, None) } - /// Resolves a same-queue cross-engine barrier target when `job`'s command `index` waits on - /// an in-flight command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`). - /// Returns `Ok(None)` when no cross-engine barrier was requested or the waited prefix has - /// already retired. + /// Resolves a cross-engine barrier target when `job`'s command `index` waits on an in-flight + /// command of `other` engine (`RENDER` -> `r_fs_stamp`, `COMPUTE` -> `cstamp`), including + /// cross-queue `fw_waits`. Returns `Ok(None)` when no barrier is needed or retired. fn cross_engine_wait( &self, job: &Arc, @@ -1608,26 +1657,55 @@ impl Firmware { self.wait_stamp_for(job, other, target_seq) } - /// Resolves the newest in-flight same-queue compute producer on each compute pipe with - /// ordinal `<= target_seq`. Returns `Ok([None; COMPUTE_PIPES])` when no barrier was - /// requested or the entire prefix through `target_seq` has already retired, and `Err(EAGAIN)` - /// if `target_seq` is neither in flight nor retired. + /// Resolves the newest in-flight compute producer on each compute pipe across `job`'s + /// same-queue `target_seq` and any cross-queue `job.fw_waits`. Returns + /// `Ok([None; COMPUTE_PIPES])` when no barrier is needed or every waited prefix retired, + /// and `Err(EAGAIN)` if any unretired target ordinal is missing from `flights`. fn wait_compute_stamps_for( &self, job: &Arc, target_seq: Option, ) -> Result<[Option; sizes::COMPUTE_PIPES]> { - let Some(last) = target_seq else { - return Ok([None; sizes::COMPUTE_PIPES]); - }; - if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + let mut targets: [Option<(&Arc, u64, bool)>; + 1 + super::fence::MAX_FW_WAITS] = [None; 1 + super::fence::MAX_FW_WAITS]; + let mut count = 0usize; + if let Some(last) = target_seq { + if job.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) < last { + targets[count] = Some((&job.queue, last, false)); + count += 1; + } + } + for wait in job.fw_waits.iter() { + let Some(last) = wait.last_ordinal[super::command::COMPUTE] else { + continue; + }; + if wait.queue.completed[super::command::COMPUTE].load(Ordering::Acquire) >= last { + continue; + } + if let Some(slot) = targets[..count] + .iter_mut() + .flatten() + .find(|(q, _, _)| Arc::ptr_eq(q, &wait.queue)) + { + slot.1 = slot.1.max(last); + } else if count < targets.len() { + targets[count] = Some((&wait.queue, last, false)); + count += 1; + } else { + return Err(EAGAIN); + } + } + if count == 0 { return Ok([None; sizes::COMPUTE_PIPES]); } let mut waits = [None; sizes::COMPUTE_PIPES]; - let mut best_seq = [0u64; sizes::COMPUTE_PIPES]; - let mut found_last = false; for flight in &self.engine.flights { - if flight.computes == 0 || !Arc::ptr_eq(&flight.job.queue, &job.queue) { + if flight.computes == 0 + || !targets[..count] + .iter() + .flatten() + .any(|(q, _, _)| Arc::ptr_eq(&flight.job.queue, q)) + { continue; } let pipe = flight.compute_pipe as usize; @@ -1637,12 +1715,17 @@ impl Firmware { let mut member = 0usize; for k in flight.first..flight.first + flight.count { if let Some(fo) = flight.job.command_order(k as u32) { - if fo.engine == super::command::COMPUTE && fo.sequence <= last { - if fo.sequence == last { - found_last = true; + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } } - if fo.sequence >= best_seq[pipe] { - best_seq[pipe] = fo.sequence; + if matched { waits[pipe] = Some(WaitTarget { stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, initbm: flight.initbm, @@ -1655,12 +1738,17 @@ impl Firmware { for j2 in flight.group.iter() { for k in 0..j2.progress.count() { if let Some(fo) = j2.command_order(k) { - if fo.engine == super::command::COMPUTE && fo.sequence <= last { - if fo.sequence == last { - found_last = true; + if fo.engine == super::command::COMPUTE { + let mut matched = false; + for (q, last, found) in targets[..count].iter_mut().flatten() { + if Arc::ptr_eq(&flight.job.queue, q) && fo.sequence <= *last { + if fo.sequence == *last { + *found = true; + } + matched = true; + } } - if fo.sequence >= best_seq[pipe] { - best_seq[pipe] = fo.sequence; + if matched { waits[pipe] = Some(WaitTarget { stamp: *flight.cstamp.get(member).ok_or(EAGAIN)?, initbm: flight.initbm, @@ -1672,8 +1760,10 @@ impl Firmware { } } } - if !found_last && !job.queue.is_compute_retired(last) { - return Err(EAGAIN); + for (q, last, found) in targets[..count].iter().flatten() { + if !*found && !q.is_compute_retired(*last) { + return Err(EAGAIN); + } } Ok(waits) } @@ -2919,8 +3009,19 @@ impl Firmware { .rev() .find(|fl| fl.renders != 0) .is_some_and(|fl| !Arc::ptr_eq(&fl.job.vm, &job.vm)); + let plan_flags = if !staged + && job + .fw_waits + .iter() + .any(|w| w.last_ordinal[super::command::RENDER].is_some()) + { + cmd.cmd.flags + & !kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS + } else { + cmd.cmd.flags + }; let plan = plan_render_barriers( - cmd.cmd.flags, + plan_flags, has_prior_render, params::early_tiling(), prev_fs, diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 2890428717f57..1e90a148b3d0b 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -12,6 +12,7 @@ //! queue teardown). Fences of one context must signal in order, so a [`Timeline`] holds a //! completed fence back until every earlier fence of the queue has completed. +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use kernel::{ c_str, dma_fence::{Fence, FenceContexts, FenceObject, FenceOps, RawDmaFence, UserFence}, @@ -21,6 +22,7 @@ use kernel::{ sync::{Arc, LockClassKey, Mutex}, }; +use super::queue::QueueState; use crate::file::SyncItem; /// Inline storage for the common 0-2 input fences, spilling to a heap `KVec` above 2. @@ -119,9 +121,105 @@ pub(crate) fn wait_dependencies(inputs: &[Fence]) -> Result { static TIMELINE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); static ERROR_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); +static JOB_FENCE_OPS: AtomicUsize = AtomicUsize::new(0); + +/// Maximum distinct cross-queue firmware waits carried inline/on-heap by one job. +pub(crate) const MAX_FW_WAITS: usize = 8; + +/// Immutable origin and atomic lifecycle flags attached to every G16 job fence so another +/// logical queue on the same GPU and VM can resolve a binary or timeline semaphore into an +/// in-firmware ring barrier instead of round-tripping through `drm_sched` and CPU retirement. +pub(crate) struct FenceOrigin { + pub(crate) gpu_id: usize, + pub(crate) vm_id: u64, + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + enqueued: AtomicBool, + failed: AtomicBool, +} + +impl FenceOrigin { + pub(crate) fn new( + gpu_id: usize, + vm_id: u64, + queue: Arc, + last_ordinal: [Option; 2], + ) -> Self { + Self { + gpu_id, + vm_id, + queue, + last_ordinal, + enqueued: AtomicBool::new(false), + failed: AtomicBool::new(false), + } + } + + pub(crate) fn mark_enqueued(&self) { + self.enqueued.store(true, Ordering::Release); + } + + pub(crate) fn is_enqueued(&self) -> bool { + self.enqueued.load(Ordering::Acquire) + } + + pub(crate) fn mark_failed(&self) { + self.failed.store(true, Ordering::Release); + } + + pub(crate) fn is_failed(&self) -> bool { + self.failed.load(Ordering::Acquire) + } +} + +/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 entries, bounded to +/// [`MAX_FW_WAITS`]). +pub(crate) enum FwWaits { + Empty, + One([Arc; 1]), + Heap(KVec>), +} + +impl FwWaits { + fn push_unique(&mut self, origin: Arc) -> Result { + if self.iter().any(|existing| Arc::ptr_eq(existing, &origin)) { + return Ok(()); + } + if self.len() >= MAX_FW_WAITS { + return Err(E2BIG); + } + match self { + Self::Empty => *self = Self::One([origin]), + Self::One(_) => { + let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; + if let Self::One([first]) = core::mem::replace(self, Self::Empty) { + let _ = vec.push_within_capacity(first); + let _ = vec.push_within_capacity(origin); + } + *self = Self::Heap(vec); + } + Self::Heap(vec) => vec.push(origin, GFP_KERNEL)?, + } + Ok(()) + } +} + +impl core::ops::Deref for FwWaits { + type Target = [Arc]; + + fn deref(&self) -> &[Arc] { + match self { + Self::Empty => &[], + Self::One(items) => items, + Self::Heap(vec) => vec, + } + } +} /// Fence operations of G16 job fences. -pub(crate) struct JobFenceOps; +pub(crate) struct JobFenceOps { + origin: Arc, +} #[vtable] impl FenceOps for JobFenceOps { @@ -134,6 +232,85 @@ impl FenceOps for JobFenceOps { } } +/// Fence operations of pre-signalled refused-submission fences (distinct vtable from +/// [`JobFenceOps`] so refused error fences never match [`origin_from_raw`]). +struct RefusedFenceOps; + +#[vtable] +impl FenceOps for RefusedFenceOps { + fn get_driver_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("aurora") + } + + fn get_timeline_name<'a>(self: &'a FenceObject) -> &'a CStr { + c_str!("g16-refused") + } +} + +/// Resolves a G16 [`FenceOrigin`] from a raw `dma_fence` pointer if and only if its vtable +/// pointer matches the registered [`JobFenceOps`] vtable. +/// +/// # Safety +/// +/// `raw` must be null or point to a live, initialized `dma_fence` whose reference is held for +/// the duration of this call. +unsafe fn origin_from_raw(raw: *mut kernel::bindings::dma_fence) -> Option> { + let expected = JOB_FENCE_OPS.load(Ordering::Acquire); + if expected == 0 || raw.is_null() { + return None; + } + // SAFETY: Caller retains a live dma_fence reference. `JobFenceOps` has a distinct timeline + // name and nontrivial payload drop (`Arc`). No cast precedes the exact + // registered vtable check, and `FenceObject` begins with its `dma_fence`. + let object = unsafe { + if (*raw).ops as usize != expected { + return None; + } + &*(raw as *const FenceObject) + }; + Some(object.origin.clone()) +} + +/// Resolves `inputs` into same-GPU, same-VM in-firmware cross-queue waits outside the device +/// lock. Returns `None` if any leaf is failed, foreign, cross-VM, not yet enqueued, or exceeds +/// [`MAX_FW_WAITS`], leaving the caller to retain normal `drm_sched` / `InputFences` waits. +pub(crate) fn resolve_fw_waits(inputs: &[Fence], gpu_id: usize, vm_id: u64) -> Option { + if inputs.is_empty() { + return Some(FwWaits::Empty); + } + let mut waits = FwWaits::Empty; + for input in inputs { + let status = dependency_status(input); + if status < 0 { + return None; + } + if status > 0 { + continue; + } + let leaves = crate::g17::sync_input::collect(input)?; + for leaf in leaves.iter() { + if leaf.status < 0 { + return None; + } + if leaf.status > 0 { + continue; + } + // SAFETY: `leaf` retains an owned reference to `leaf.fence` until dropped. + let origin = unsafe { origin_from_raw(leaf.fence) }?; + if origin.gpu_id != gpu_id + || origin.vm_id != vm_id + || !origin.is_enqueued() + || origin.is_failed() + || origin.last_ordinal == [None, None] + { + return None; + } + waits.push_unique(origin).ok()?; + } + } + Some(waits) +} + /// Stack batch size for signalling completed fences outside `Timeline::pending`. const SIGNAL_BATCH: usize = 8; @@ -192,11 +369,23 @@ impl Timeline { /// Creates the fence of the next accepted job. Fences are created in submission order: the /// caller holds the queue (SUBMIT is serialized per queue). - pub(crate) fn next(self: &Arc) -> Result { + pub(crate) fn next(self: &Arc, origin: Arc) -> Result { // SUBMIT already holds the logical queue, so allocating the next sequence before // taking pending preserves creation order. Fence completion needs pending too: // never enter reclaim while holding that mutex. - let fence: UserFence = self.jobs.new_fence(0, JobFenceOps)?.into(); + let fence: UserFence = self.jobs.new_fence(0, JobFenceOps { origin })?.into(); + // SAFETY: `fence` is a live `UserFence` whose `dma_fence::ops` is static. + let ops = unsafe { (*fence.raw()).ops as usize }; + let previous = JOB_FENCE_OPS.load(Ordering::Acquire); + if previous == 0 { + match JOB_FENCE_OPS.compare_exchange(0, ops, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => {} + Err(existing) if existing == ops => {} + Err(_) => return Err(EIO), + } + } else if previous != ops { + return Err(EIO); + } let mut pending = self.pending.lock(); pending.reserve(1, GFP_NOWAIT)?; pending @@ -276,7 +465,7 @@ impl Timeline { /// A fence on `contexts` signalled with `error`. Every fence of an error context signals at /// creation, so the context's fences signal in order. fn error_fence(contexts: &FenceContexts, error: Error) -> Result { - let fence = contexts.new_fence(0, JobFenceOps)?; + let fence = contexts.new_fence(0, RefusedFenceOps)?; fence.set_error(error); fence.signal(); Ok(Fence::from_fence(&fence)) diff --git a/drivers/gpu/drm/asahi/g16/job.rs b/drivers/gpu/drm/asahi/g16/job.rs index 6547895cceef8..c52f60a11e2b8 100644 --- a/drivers/gpu/drm/asahi/g16/job.rs +++ b/drivers/gpu/drm/asahi/g16/job.rs @@ -45,7 +45,7 @@ use kernel::{ use super::{ command::{Command, Commands, Order, Orders}, - fence::{InputFences, JobFence}, + fence::{FenceOrigin, FwWaits, InputFences, JobFence}, hw, queue::QueueState, vm::VmState, @@ -107,6 +107,10 @@ pub(crate) struct Job { pub(crate) progress: super::engine::Progress, /// Inputs and resolved historical-prefix dependencies, held through every command. inputs: InputFences, + /// Exported fence identity for same-GPU, same-VM cross-queue firmware handoff. + pub(crate) origin: Arc, + /// Same-GPU, same-VM cross-queue waits resolved into firmware ring barriers. + pub(crate) fw_waits: FwWaits, /// Bitmask of commands (`0..MAX_COMMANDS`) with full owner-retirement proof; an aborted /// receipt never sets its bit. Tracks per-command bits so concurrent compute/render /// commands within one job may retire in either hardware completion order. @@ -141,6 +145,8 @@ impl Job { fence: JobFence, guard: mmu::VmJobGuard, inputs: InputFences, + origin: Arc, + fw_waits: FwWaits, ) -> Result> { if commands.len() != orders.len() { return Err(EINVAL); @@ -161,6 +167,8 @@ impl Job { fence, progress, inputs, + origin, + fw_waits, full_retired: AtomicU64::new(0), terminal_retired: AtomicBool::new(false), // Scheduler free can race the final off-lock completion reference. @@ -178,6 +186,7 @@ impl Job { /// Latches a hardware/publication failure before any later work can be published. /// Called under the device lock; it deliberately does not signal the fence. pub(crate) fn latch_failure(&self, error: Error) { + self.origin.mark_failed(); if error == ECANCELED || (self.terminal_retired.load(Ordering::Acquire) && error != EIO @@ -217,6 +226,7 @@ impl Job { return; } if let Err(error) = result { + self.origin.mark_failed(); if error == ECANCELED || ((!engine || self.terminal_retired.load(Ordering::Acquire)) && error != EIO @@ -321,7 +331,10 @@ impl Job { /// Whether command `index` is a ready, barrier-free compute command continuing a compute /// horizon at queue-local compute ordinal `expected`. pub(crate) fn can_fold_horizon_cmd(&self, index: u32, expected: u64) -> bool { - if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { return false; } let Some(Command::Compute(_)) = self.commands.get(index as usize) else { @@ -342,6 +355,7 @@ impl Job { pub(crate) fn can_fold_horizon_job(&self, first_expected: u64) -> bool { let count = self.progress.count(); if count == 0 + || !self.fw_waits.is_empty() || self.progress.sent() != 0 || self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 @@ -374,7 +388,10 @@ impl Job { /// at queue-local render ordinal `expected` (treating `expected - 1` as already published /// within the in-progress render flight). pub(crate) fn can_fold_render_cmd(&self, index: u32, expected: u64) -> bool { - if self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 { + if !self.fw_waits.is_empty() + || self.terminal_retired.load(Ordering::Acquire) + || self.vm.status.get() != 0 + { return false; } let Some(Command::Render(_)) = self.commands.get(index as usize) else { @@ -411,6 +428,7 @@ impl Job { pub(crate) fn can_fold_render_horizon_job(&self, first_expected: u64) -> bool { let count = self.progress.count(); if count == 0 + || !self.fw_waits.is_empty() || self.progress.sent() != 0 || self.terminal_retired.load(Ordering::Acquire) || self.vm.status.get() != 0 @@ -471,6 +489,19 @@ impl Job { let order = self.orders.get(index as usize).ok_or(EINVAL)?; self.queue.check(order)?; super::fence::check_dependencies(&self.inputs)?; + for wait in self.fw_waits.iter() { + if wait.is_failed() { + return Err(ECANCELED); + } + for engine in 0..2 { + if let Some(seq) = wait.last_ordinal[engine] { + wait.queue.cancelled_through(engine, seq)?; + if wait.queue.published[engine].load(Ordering::Acquire) < seq { + return Err(EAGAIN); + } + } + } + } let completed = self .queue .completed @@ -599,6 +630,11 @@ impl Job { Ok(()) } + /// Whether this job holds a cross-queue firmware wait on `queue`. + pub(crate) fn waits_on_queue(&self, queue: &Arc) -> bool { + self.fw_waits.iter().any(|w| Arc::ptr_eq(&w.queue, queue)) + } + /// Cancels a job the scheduler never ran (queue teardown, or a failed submission). fn cancel_unstarted(&self) { if self.started.swap(true, Ordering::AcqRel) { @@ -608,6 +644,7 @@ impl Job { self.finish(Err(ECANCELED), false); } else if !self.progress.signaled.swap(true, Ordering::AcqRel) { // A refused submission's job: its fence orders nothing and was never published. + self.origin.mark_failed(); self.fence.signal(Err(ECANCELED)); } } diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index cdc0359c33a0c..103423bee3626 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1539,11 +1539,34 @@ impl Firmware { let p = &job.progress; p.next.store(p.next() + f.count as u32, Ordering::Relaxed); if result.is_err() { - // Its queue's later commands queued behind it fail with it, as unpublished ones - // are cancelled: they never report a successful receipt after this hole. + // Later commands of this queue, and any cross-queue flights transitively waiting + // on it via firmware handoff, fail with it so no dependent command reports success + // after an upstream failure. + let mut changed = false; for later in self.engine.flights.iter_mut() { - if Arc::ptr_eq(&later.job.queue, &job.queue) { + if !later.doomed + && (Arc::ptr_eq(&later.job.queue, &job.queue) + || later.job.waits_on_queue(&job.queue)) + { later.doomed = true; + changed = true; + } + } + while changed { + changed = false; + for i in 0..self.engine.flights.len() { + if self.engine.flights[i].doomed { + continue; + } + let dep_doomed = self.engine.flights.iter().any(|other| { + other.doomed + && (Arc::ptr_eq(&other.job.queue, &self.engine.flights[i].job.queue) + || self.engine.flights[i].job.waits_on_queue(&other.job.queue)) + }); + if dep_doomed { + self.engine.flights[i].doomed = true; + changed = true; + } } } } diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 4dc9d7d2f837c..bc4423839f133 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -101,6 +101,15 @@ impl QueueState { Ok(()) } + /// Whether any accepted ordinal of `engine` at or before `seq` was cancelled. + pub(crate) fn cancelled_through(&self, engine: usize, seq: u64) -> Result { + let first = self.cancelled_at[engine].load(Ordering::Acquire); + if first != 0 && first <= seq { + return Err(ECANCELED); + } + Ok(()) + } + /// Whether compute ordinal `seq` already has a full successful firmware receipt, either /// at or below the contiguous `completed[COMPUTE]` frontier or recorded in `compute_ooo`. pub(crate) fn is_compute_retired(&self, seq: u64) -> bool { @@ -264,7 +273,22 @@ impl Queue { .as_ref() .ok_or(EIO)? .prepare(&self.vm, &submission.commands, hints)?; - let fence = self.timeline.next()?; + let gpu_id = Arc::as_ptr(&self.shared) as usize; + let last_ordinal = [ + (submission.counts[command::RENDER] != 0) + .then_some(self.accepted[command::RENDER] + submission.counts[command::RENDER]), + (submission.counts[command::COMPUTE] != 0) + .then_some(self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]), + ]; + let origin = Arc::new( + super::fence::FenceOrigin::new(gpu_id, self.vm.id, self.state.clone(), last_ordinal), + GFP_KERNEL, + )?; + let (inputs, fw_waits) = match super::fence::resolve_fw_waits(&inputs, gpu_id, self.vm.id) { + Some(waits) => (InputFences::new(), waits), + None => (inputs, super::fence::FwWaits::Empty), + }; + let fence = self.timeline.next(origin.clone())?; let job = Job::new( id, self.state.clone(), @@ -275,6 +299,8 @@ impl Queue { fence, guard, inputs, + origin, + fw_waits, )?; let published = job.fence.fence(); // Publish output syncs (including fallible cumulative scope allocation) before pushing diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ca362da3e93f5..6ab44208a4f84 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -34,7 +34,7 @@ mod completion; pub(crate) mod context; mod data_segment; mod dependency; -mod sync_input; +pub(crate) mod sync_input; pub(crate) mod exec_share; pub(crate) mod sync_output; mod trace; diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 33ac3f94d4f21..356fca680b23c 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -6,9 +6,9 @@ use kernel::{bindings, dma_fence::{Fence, RawDmaFence}, prelude::*}; #[repr(C)] -pub(super) struct Leaf { - pub(super) fence: *mut bindings::dma_fence, - pub(super) status: i32, +pub(crate) struct Leaf { + pub(crate) fence: *mut bindings::dma_fence, + pub(crate) status: i32, } unsafe extern "C" { @@ -43,7 +43,7 @@ impl Drop for Leaf { } /// Allocation, unsupported containers, or a large prefix retain normal waits. -pub(super) fn collect(input: &Fence) -> Option> { +pub(crate) fn collect(input: &Fence) -> Option> { let mut capacity = 4; loop { let mut leaves = KVec::with_capacity(capacity, GFP_KERNEL).ok()?; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py index 6cbe422995dff..fe6818252cc83 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-job-failure.py @@ -32,8 +32,8 @@ def function_from(text, marker_text): def function(text, name): return function_from(text, 'fn ' + name + '(') -queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'is_compute_retired']) -methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired']) +queue_methods = '\n'.join(function(queue_source, name) for name in ['cancel', 'check', 'cancelled_through', 'is_compute_retired']) +methods = '\n'.join(function(source, name) for name in ['latch_failure', 'complete', 'finish', 'is_started', 'try_start_inline', 'start', 'check_command_dependencies', 'command_retired', 'note_full_retirement', 'mark_terminal_retired', 'waits_on_queue']) push_method = function_from(source, 'pub(crate) fn push(&mut self, job: Arc') fence_methods = '\n'.join(function(fence_source, name) for name in ['dependency_status', 'check_dependencies', 'wait_dependencies']) harness = r''' @@ -102,7 +102,13 @@ def function(text, name): mod command { pub(crate) use super::{Order, COMPUTE}; } struct QueueState { completed:[AtomicU64;2],published:[AtomicU64;2],cancelled_at:[AtomicU64;2],compute_ooo:AtomicU64 } impl QueueState { QUEUE_METHODS } -struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,orders:Vec,queue:Arc,full_retired:AtomicU64,terminal_retired:AtomicBool } +struct FenceOrigin { queue:Arc, last_ordinal:[Option;2], failed:AtomicBool } +impl FenceOrigin { + fn new(queue:Arc, last_ordinal:[Option;2])->Arc { Arc::new(Self{queue,last_ordinal,failed:AtomicBool::new(false)}) } + fn mark_failed(&self) { self.failed.store(true,Ordering::Release); } + fn is_failed(&self)->bool { self.failed.load(Ordering::Acquire) } +} +struct Job { id:u64,vm:Vm,_guard:Guard,progress:Progress,started:AtomicBool,accepted:AtomicBool,fence:Fence,commands:Vec<()>,inputs:Vec,origin:Arc,fw_waits:Vec>,orders:Vec,queue:Arc,full_retired:AtomicU64,terminal_retired:AtomicBool } struct Shared { crashed:AtomicBool,sleeping:AtomicBool,recovering:AtomicBool,contended:AtomicBool,submitted:Mutex>,submit_result:Result } impl Shared { fn new()->Arc { @@ -183,9 +189,10 @@ def function(text, name): job_with_orders(id,status,inputs,orders,Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)})) } fn job_with_orders(id:u64,status:Arc,inputs:Vec,orders:Vec,queue:Arc)->Arc { + let origin=FenceOrigin::new(queue.clone(),[None,Some(orders.len() as u64)]); Arc::new(Job{id,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)},started:AtomicBool::new(false),accepted:AtomicBool::new(true), - fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,orders,queue, + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![();orders.len()],inputs,origin,fw_waits:vec![],orders,queue, full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false)}) } #[test] @@ -581,6 +588,56 @@ def function(text, name): assert_eq!(queue.completed[COMPUTE].load(Ordering::Acquire),4); assert_eq!(queue.compute_ooo.load(Ordering::Acquire),0); } +#[test] +fn fw_wait_defers_until_producer_queue_publishes_and_propagates_failure() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders,q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2.clone(), + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert!(cons.waits_on_queue(&q1)); + assert!(!cons.waits_on_queue(&q2)); + // Producer not yet published -> consumer defers with EAGAIN. + assert_eq!(cons.check_command_dependencies(0),Err(EAGAIN)); + // Once producer publishes ordinal 1, consumer is ready for firmware handoff. + q1.published[COMPUTE].store(1,Ordering::Release); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + // Producer failure marks origin failed and cancels consumer with ECANCELED. + prod.latch_failure(ECANCELED); + assert!(prod.origin.is_failed()); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} +#[test] +fn fw_wait_cancels_when_producer_queue_cancels_ordinal() { + let q1=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[AtomicU64::new(0),AtomicU64::new(1)],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let q2=Arc::new(QueueState{completed:[const{AtomicU64::new(0)};2],published:[const{AtomicU64::new(0)};2],cancelled_at:[const{AtomicU64::new(0)};2],compute_ooo:AtomicU64::new(0)}); + let status=Arc::new(Status::new()); + let p_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let c_orders=vec![Order::new([0,0],[0,0],[NONE;2],[0;2],1).unwrap()]; + let prod=job_with_orders(1,status.clone(),vec![],p_orders.clone(),q1.clone()); + let cons=Arc::new(Job{ + id:2,vm:Vm{status:status.clone()},_guard:Guard(AtomicBool::new(false)), + progress:Progress{signaled:AtomicBool::new(false),sent:AtomicU32::new(0),next:AtomicU32::new(0),pending:AtomicBool::new(false)}, + started:AtomicBool::new(false),accepted:AtomicBool::new(true), + fence:Fence{vm:status,signals:Mutex::new(vec![])},commands:vec![()],inputs:vec![], + origin:FenceOrigin::new(q2.clone(),[None,Some(1)]), + fw_waits:vec![prod.origin.clone()],orders:c_orders,queue:q2, + full_retired:AtomicU64::new(0),terminal_retired:AtomicBool::new(false), + }); + assert_eq!(cons.check_command_dependencies(0),Ok(())); + q1.cancel(&p_orders,0); + assert_eq!(cons.check_command_dependencies(0),Err(ECANCELED)); +} '''.replace('QUEUE_METHODS', queue_methods).replace('ORDER_SOURCE', order_source).replace('FENCE_METHODS', fence_methods).replace('METHODS', methods.replace('super::fence::','fence::').replace('super::command::','command::')).replace('PUSH_METHOD', push_method) with tempfile.TemporaryDirectory(prefix='m4-rust-job-') as directory: @@ -592,6 +649,6 @@ def function(text, name): (OUT/'job-failure-host.log').write_text(result.stdout+result.stderr) (OUT/'job-failure-host.json').write_text(json.dumps({ 'source':str(SOURCE),'sha256':hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result':'pass','test_groups':23, + 'result':'pass','test_groups':25, 'limitations':'Production Job methods with host VM/fence mocks; actual DRM scheduler and firmware publication gates require kernel and execution integration validation.' },indent=2)+'\n') 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 e01576c044d1a..f15af074a6221 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -698,8 +698,15 @@ def item(declaration): } } +mod fence { + pub const MAX_FW_WAITS: usize = 8; + pub struct FwWait { + pub queue: std::sync::Arc, + pub last_ordinal: [Option; 2], + } +} #[derive(Copy,Clone)]struct Order{engine:usize,sequence:u64,wait_through:[Option;2]} -struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources} +struct QueueBehindJob{id:u32,vm:Arc,queue:Arc,progress:Progress,commands:Vec,order:Order,extra_orders:Vec,dependency:Result,resources:Resources,fw_waits:Vec} impl QueueBehindJob{ fn check_command_dependencies(&self,_index:u32)->Result{self.dependency} fn command_order(&self,index:u32)->Option{ @@ -788,7 +795,7 @@ def item(declaration): id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let j1=mk(1,vm1.clone(),q1.clone(),false); let j2=mk(2,vm1.clone(),q1.clone(),false); @@ -833,7 +840,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access})], order:Order{engine:command::COMPUTE,sequence:u64::from(id),wait_through:[wait_vdm,wait_cdm]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let timed=mk(1,q1.clone(),true,None,None); let query_copy=mk(2,q1.clone(),true,None,Some(1)); @@ -856,7 +863,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let pr=QueueBehindHost{ graph:QueueBehindGraph::new(), @@ -876,7 +883,7 @@ def item(declaration): id,vm,queue:q1.clone(),progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:true})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r1=mk(1,vm1.clone(),true); let r2=mk(2,vm1.clone(),true); @@ -921,7 +928,7 @@ def item(declaration): id,vm,queue,progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let vm1_r=mk(1,vm1.clone(),q1.clone(),true); let vm1_c=mk(2,vm1.clone(),q1.clone(),false); @@ -963,7 +970,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r1=mk(1,q1.clone(),true,1,[None,None]); let c1=mk(2,q1.clone(),false,1,[Some(1),None]); @@ -1000,7 +1007,7 @@ def item(declaration): Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, Order{engine:command::COMPUTE,sequence:3,wait_through:[None,None]}, ], - dependency:Ok(()),resources:Resources, + dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_wait_c2=mk(7,q1.clone(),true,3,[None,Some(2)]); let r_wait_c3=mk(8,q1.clone(),true,4,[None,Some(3)]); @@ -1035,7 +1042,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_initbm=mk(1,true,1,[None,None]); let c_after_r=mk(2,false,1,[Some(1),None]); @@ -1077,14 +1084,14 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_job=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q_rend.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut p=QueueBehindHost{ graph:QueueBehindGraph::new(), @@ -1114,7 +1121,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access:false})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:seq,wait_through:wait}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,false,1,[None,None]); let c2=mk(2,false,2,[None,None]); @@ -1153,14 +1160,14 @@ def item(declaration): Order{engine:command::RENDER,sequence:2,wait_through:[Some(1),None]}, Order{engine:command::RENDER,sequence:3,wait_through:[Some(2),None]}, ], - dependency:Ok(()),resources:Resources, + dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let next_r=Arc::new(QueueBehindJob{ id:2,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:4,wait_through:[Some(3),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut r_fs=[0u32;16]; r_fs[0]=0x100;r_fs[1]=0x200;r_fs[2]=0x300; @@ -1192,14 +1199,14 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:5,wait_through:[Some(4),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_fold_b=Arc::new(QueueBehindJob{ id:11,vm:vm1.clone(),queue:q1.clone(), progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:6,wait_through:[Some(5),None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let mut grp_fs=[0u32;16]; grp_fs[0]=0x400;grp_fs[1]=0x500;grp_fs[2]=0x600; @@ -1226,7 +1233,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Render(())], order:Order{engine:command::RENDER,sequence:u64::from(id),wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let r_live=mk(1); let next_r=mk(2); @@ -1272,7 +1279,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![if render{Command::Render(())}else{Command::Compute(ComputeCommand{query_access})}], order:Order{engine:if render{command::RENDER}else{command::COMPUTE},sequence:u64::from(id),wait_through:wait}, - extra_orders:vec![],dependency:dep,resources:Resources, + extra_orders:vec![],dependency:dep,resources:Resources,fw_waits:vec![], }); let r_live=mk(1,vm1.clone(),true,Ok(()),false,[None,None]); let r_same=mk(2,vm1.clone(),true,Ok(()),false,[None,None]); @@ -1616,7 +1623,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,None]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,vm1.clone(),q1.clone(),1); let c2=mk(2,vm1.clone(),q1.clone(),2); @@ -1661,7 +1668,7 @@ def item(declaration): progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, commands:vec![Command::Compute(ComputeCommand{query_access:false})], order:Order{engine:command::COMPUTE,sequence:seq,wait_through:[None,wait_c]}, - extra_orders:vec![],dependency:Ok(()),resources:Resources, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], }); let c1=mk(1,1,None); let c2=mk(2,2,None); @@ -1712,6 +1719,73 @@ def item(declaration): q1.compute_ooo.store(0, Ordering::Release); assert_eq!(host.wait_compute_stamps_for(&c4, Some(2)), Ok([None, None])); } + #[test]fn cross_queue_fw_waits_resolve_stamps_reuse_compute_pipe_and_guard_timestamps(){ + let vm1=Arc::new(Vm{status:Status(AtomicU32::new(0)),slot:1}); + let q1=Queue::new(0,2); + let q2=Queue::new(0,2); + let c1=Arc::new(QueueBehindJob{ + id:1,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let r1=Arc::new(QueueBehindJob{ + id:2,vm:vm1.clone(),queue:q1.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Render(())], + order:Order{engine:command::RENDER,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources,fw_waits:vec![], + }); + let c2_wait_q1=Arc::new(QueueBehindJob{ + id:3,vm:vm1.clone(),queue:q2.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:false})], + order:Order{engine:command::COMPUTE,sequence:1,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[Some(1),Some(1)]}], + }); + let c2_query_wait_q1=Arc::new(QueueBehindJob{ + id:4,vm:vm1.clone(),queue:q2.clone(), + progress:Progress{sent:AtomicU32::new(0),count:1,pending:AtomicBool::new(true)}, + commands:vec![Command::Compute(ComputeCommand{query_access:true})], + order:Order{engine:command::COMPUTE,sequence:2,wait_through:[None,None]}, + extra_orders:vec![],dependency:Ok(()),resources:Resources, + fw_waits:vec![fence::FwWait{queue:q1.clone(),last_ordinal:[None,Some(1)]}], + }); + let host=QueueBehindHost{ + graph:QueueBehindGraph::new(), + engine:QueueBehindEngine{ordinal:1,draw:1,ta_target:0,next_compute_pipe:0,flights:vec![ + QueueBehindFlight{ + job:c1,group:vec![],first:0,count:1,computes:1,renders:0,compute_pipe:0,target:0x100, + cstamp:{let mut a=[0;16];a[0]=0x100;a},r_ta_stamp:[0;16],r_fs_stamp:[0;16],fs_target:0, + initbm:false,has_timestamps:true,doomed:false,recovery_suspect:false, + }, + QueueBehindFlight{ + job:r1,group:vec![],first:0,count:1,computes:0,renders:1,compute_pipe:0,target:0, + cstamp:[0;16],r_ta_stamp:[0;16],r_fs_stamp:{let mut a=[0;16];a[0]=0x200;a},fs_target:0x200, + initbm:false,has_timestamps:false,doomed:false,recovery_suspect:false, + }, + ]}, + slots:QueueBehindSlots{compute_exhausted:false,render_exhausted:false,compute_available:true,pass_available:true}, + pools:QueueBehindPools{exhausted:false,can_pipeline:true,block_pipeline_vm:None}, + }; + // Cross-queue compute wait resolves pipe 0 stamp 0x100 and keeps q2 on pipe 0 (zero c2c). + let cw=host.wait_compute_stamps_for(&c2_wait_q1,None).unwrap(); + assert_eq!(cw,[Some(WaitTarget{stamp:0x100,initbm:false}),None]); + assert_eq!(host.choose_compute_pipe(cw,24),0); + // Cross-queue render wait resolves q1's FS stamp 0x200. + assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(Some(WaitTarget{stamp:0x200,initbm:false}))); + // query_access compute waiting via fw_waits on a timestamped q1 flight must wait to retire; + // non-query compute queues directly behind q1 in firmware. + assert!(!host.can_queue_behind(&c2_query_wait_q1)); + assert!(host.can_queue_behind(&c2_wait_q1)); + // Once q1 retires, fw_waits resolves to no barriers. + q1.completed[command::COMPUTE].store(1,Ordering::Release); + q1.completed[command::RENDER].store(1,Ordering::Release); + assert_eq!(host.wait_compute_stamps_for(&c2_wait_q1,None),Ok([None,None])); + assert_eq!(host.wait_stamp_for(&c2_wait_q1,command::RENDER,None),Ok(None)); + } } #[allow(non_camel_case_types, deprecated)] mod queue_limits_scope { @@ -1844,6 +1918,7 @@ def item(declaration): commands: Vec, orders: Vec, inputs: Vec, + fw_waits: Vec<()>, terminal_retired: AtomicBool, } impl Job { @@ -1865,6 +1940,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; let ok_job = mk( @@ -1925,6 +2001,15 @@ def item(declaration): 2, ); assert!(!cancelled.can_fold_horizon_job(2)); + let mut with_fw_wait = mk( + vec![Command::Compute(())], + vec![Order { engine: command::COMPUTE, sequence: 2, wait_through: [None, None] }], + vec![], + 0, + ); + with_fw_wait.fw_waits.push(()); + assert!(!with_fw_wait.can_fold_horizon_cmd(0, 2)); + assert!(!with_fw_wait.can_fold_horizon_job(2)); } #[test] @@ -1940,6 +2025,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; let multi = mk( @@ -1986,6 +2072,7 @@ def item(declaration): commands: cmds, orders, inputs, + fw_waits: vec![], terminal_retired: AtomicBool::new(false), }; // Two-pass render job waiting on primary flight pass 1 and its own pass 2. @@ -2417,7 +2504,7 @@ def item(declaration): '__RENDER_BARRIER_PLAN__': 'struct RenderBarrierPlan {', '__PLAN_RENDER_BARRIERS__': 'fn plan_render_barriers(', }.items(): - harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::")) + harness = harness.replace(token, item(declaration).replace("super::command::", "crate::command::").replace("super::recovery::", "crate::recovery::").replace("super::hw::", "crate::hw::").replace("super::resources::", "crate::resources::").replace("super::queue::QueueState", "crate::Queue").replace("super::fence::", "crate::fence::")) unit = output / 'publication.rs' unit.write_text(harness) log = '' From 4ec367549fb63835d0872689ea7293c8f3ffda32 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 09:52:40 -0500 Subject: [PATCH 03/10] drm/asahi: g16: coalesce timeline fence chains per queue for fw barriers Timeline semaphores on G16 attach each submitted JobFence into a dma_fence_chain across participating queues. Previously, two issues forced alternating cross-queue timeline ping-pongs permanently onto drm_sched after the first few hops: 1. asahi_g17_collect_fences() emitted every leaf in the chain without skipping signalled leaves or coalescing same-context leaves, hitting -ENOSPC once chain depth grew past the buffer capacity. 2. FwWaits::push_unique() deduplicated only identical FenceOrigin allocations instead of coalescing per logical queue, overflowing MAX_FW_WAITS (8) by hop 9 and cascading every subsequent hop onto drm_sched because the bounced producer stayed !is_enqueued(). Add asahi_g17_collect_fences_coalesced() (skipping already-signalled non-error leaves and keeping only the latest unsignalled leaf per dma_fence context while preserving every status < 0 error leaf), record cumulative accepted render/compute ordinals in FenceOrigin::last_ordinal so coalescing to a queue's newest fence retains earlier unretired work on both engines, coalesce FwWaits per logical queue, and check that a cross-queue render wait is still unretired before clearing fragment barriers. Add host unit tests covering 256-hop 2-queue timeline chain coalescing, error leaf preservation, and per-queue FwWaits ordinal merging. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 9 +- drivers/gpu/drm/asahi/g16/fence.rs | 70 +++- drivers/gpu/drm/asahi/g16/queue.rs | 11 +- drivers/gpu/drm/asahi/g17/sync_input.c | 62 +++- drivers/gpu/drm/asahi/g17/sync_input.h | 3 + drivers/gpu/drm/asahi/g17/sync_input.rs | 27 +- .../gpu/asahi-m4/test-fence-signalling.py | 331 +++++++++++++++++- 7 files changed, 478 insertions(+), 35 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 8e098a6e0eed0..773207879b5e9 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -3010,10 +3010,11 @@ impl Firmware { .find(|fl| fl.renders != 0) .is_some_and(|fl| !Arc::ptr_eq(&fl.job.vm, &job.vm)); let plan_flags = if !staged - && job - .fw_waits - .iter() - .any(|w| w.last_ordinal[super::command::RENDER].is_some()) + && job.fw_waits.iter().any(|w| { + w.last_ordinal[super::command::RENDER].is_some_and(|last| { + w.queue.completed[super::command::RENDER].load(Ordering::Acquire) < last + }) + }) { cmd.cmd.flags & !kernel::uapi::drm_asahi_render_flags_DRM_ASAHI_RENDER_FRAGMENT_BARRIERS diff --git a/drivers/gpu/drm/asahi/g16/fence.rs b/drivers/gpu/drm/asahi/g16/fence.rs index 1e90a148b3d0b..75ca2b6768c81 100644 --- a/drivers/gpu/drm/asahi/g16/fence.rs +++ b/drivers/gpu/drm/asahi/g16/fence.rs @@ -172,42 +172,90 @@ impl FenceOrigin { } } -/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 entries, bounded to -/// [`MAX_FW_WAITS`]). +/// One per-queue cross-queue firmware barrier target, coalescing multiple fences from the same +/// logical queue (e.g. from a timeline semaphore chain or repeated input syncs) to the highest +/// required render and compute ordinals on that queue. +pub(crate) struct FwWait { + pub(crate) queue: Arc, + pub(crate) last_ordinal: [Option; 2], + origin: Arc, +} + +impl FwWait { + pub(crate) fn is_failed(&self) -> bool { + self.origin.is_failed() + } +} + +/// Cross-queue firmware waits resolved at `SUBMIT` (inline for 0-1 queues, bounded to +/// [`MAX_FW_WAITS`] distinct logical queues). pub(crate) enum FwWaits { Empty, - One([Arc; 1]), - Heap(KVec>), + One([FwWait; 1]), + Heap(KVec), } impl FwWaits { fn push_unique(&mut self, origin: Arc) -> Result { - if self.iter().any(|existing| Arc::ptr_eq(existing, &origin)) { + let existing = match self { + Self::Empty => None, + Self::One(items) => items + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + Self::Heap(vec) => vec + .iter_mut() + .find(|wait| Arc::ptr_eq(&wait.queue, &origin.queue)), + }; + if let Some(wait) = existing { + let mut newer = false; + for engine in 0..2 { + if let Some(seq) = origin.last_ordinal[engine] { + match wait.last_ordinal[engine] { + Some(cur) if seq > cur => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + None => { + wait.last_ordinal[engine] = Some(seq); + newer = true; + } + _ => {} + } + } + } + if newer { + wait.origin = origin; + } return Ok(()); } if self.len() >= MAX_FW_WAITS { return Err(E2BIG); } + let wait = FwWait { + queue: origin.queue.clone(), + last_ordinal: origin.last_ordinal, + origin, + }; match self { - Self::Empty => *self = Self::One([origin]), + Self::Empty => *self = Self::One([wait]), Self::One(_) => { let mut vec = KVec::with_capacity(4, GFP_KERNEL)?; if let Self::One([first]) = core::mem::replace(self, Self::Empty) { let _ = vec.push_within_capacity(first); - let _ = vec.push_within_capacity(origin); + let _ = vec.push_within_capacity(wait); } *self = Self::Heap(vec); } - Self::Heap(vec) => vec.push(origin, GFP_KERNEL)?, + Self::Heap(vec) => vec.push(wait, GFP_KERNEL)?, } Ok(()) } } impl core::ops::Deref for FwWaits { - type Target = [Arc]; + type Target = [FwWait]; - fn deref(&self) -> &[Arc] { + fn deref(&self) -> &[FwWait] { match self { Self::Empty => &[], Self::One(items) => items, @@ -287,7 +335,7 @@ pub(crate) fn resolve_fw_waits(inputs: &[Fence], gpu_id: usize, vm_id: u64) -> O if status > 0 { continue; } - let leaves = crate::g17::sync_input::collect(input)?; + let leaves = crate::g17::sync_input::collect_coalesced(input)?; for leaf in leaves.iter() { if leaf.status < 0 { return None; diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index bc4423839f133..27130582a881b 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -274,11 +274,14 @@ impl Queue { .ok_or(EIO)? .prepare(&self.vm, &submission.commands, hints)?; let gpu_id = Arc::as_ptr(&self.shared) as usize; + // Record cumulative queue ordinals across both engines so coalescing multiple + // same-queue fences in a timeline semaphore chain to the latest fence preserves + // any earlier unretired render or compute command on that queue. + let total_render = self.accepted[command::RENDER] + submission.counts[command::RENDER]; + let total_compute = self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]; let last_ordinal = [ - (submission.counts[command::RENDER] != 0) - .then_some(self.accepted[command::RENDER] + submission.counts[command::RENDER]), - (submission.counts[command::COMPUTE] != 0) - .then_some(self.accepted[command::COMPUTE] + submission.counts[command::COMPUTE]), + (total_render != 0).then_some(total_render), + (total_compute != 0).then_some(total_compute), ]; let origin = Arc::new( super::fence::FenceOrigin::new(gpu_id, self.vm.id, self.state.clone(), last_ordinal), diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 145a5955c8796..6c68414b49fd4 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -8,19 +8,43 @@ static int collect_leaf(struct dma_fence *leaf, struct asahi_g17_fence_leaf *out, size_t capacity, - size_t *count) + size_t *count, bool coalesce_contexts) { + int status = dma_fence_get_status(leaf); + size_t i; + + /* Already-signalled non-error leaves need no further wait or barrier. */ + if (status > 0) + return 0; + + for (i = 0; i < *count; ++i) { + if (out[i].fence == leaf) { + if (status < 0 && out[i].status >= 0) + out[i].status = status; + return 0; + } + if (coalesce_contexts && status == 0 && out[i].status == 0 && + out[i].fence->context == leaf->context) { + if (dma_fence_is_later(leaf, out[i].fence)) { + dma_fence_put(out[i].fence); + out[i].fence = dma_fence_get(leaf); + } + return 0; + } + } + if (*count == capacity) return -ENOSPC; out[*count].fence = dma_fence_get(leaf); - out[*count].status = dma_fence_get_status(leaf); + out[*count].status = status; ++*count; return 0; } /* Called without the device mutex: status polling may run fence callbacks. */ -int asahi_g17_collect_fences(struct dma_fence *head, - struct asahi_g17_fence_leaf *out, size_t capacity) +static int collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity, + bool coalesce_contexts) { struct dma_fence *pending[128]; size_t count = 0, depth = 1; @@ -34,11 +58,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, if (asahi_g17_is_scope(node)) { struct dma_fence *children[2]; - unsigned int n = asahi_g17_scope_children(node, children), i; + unsigned int n, i; + int status = dma_fence_get_status(node); + + if (status > 0) { + dma_fence_put(node); + continue; + } + n = asahi_g17_scope_children(node, children); if (!n) { /* Preserve a failed scope as a failed leaf, never drop its error. */ - if (dma_fence_get_status(node) < 0) - error = collect_leaf(node, out, capacity, &count); + if (status < 0) + error = collect_leaf(node, out, capacity, &count, + coalesce_contexts); } else if (depth + n > ARRAY_SIZE(pending)) { for (i = 0; i < n; ++i) dma_fence_put(children[i]); @@ -60,7 +92,8 @@ int asahi_g17_collect_fences(struct dma_fence *head, } else if (dma_fence_is_container(leaf)) { error = -EOPNOTSUPP; } else { - error = collect_leaf(leaf, out, capacity, &count); + error = collect_leaf(leaf, out, capacity, &count, + coalesce_contexts); } if (error) break; @@ -79,6 +112,19 @@ int asahi_g17_collect_fences(struct dma_fence *head, return count; } +int asahi_g17_collect_fences(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, size_t capacity) +{ + return collect_fences(head, out, capacity, false); +} + +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity) +{ + return collect_fences(head, out, capacity, true); +} + void asahi_g17_put_fence(struct dma_fence *fence) { dma_fence_put(fence); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.h b/drivers/gpu/drm/asahi/g17/sync_input.h index 44d3e338c1977..9fd39e223cf34 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.h +++ b/drivers/gpu/drm/asahi/g17/sync_input.h @@ -13,6 +13,9 @@ struct asahi_g17_fence_leaf { int asahi_g17_collect_fences(struct dma_fence *head, struct asahi_g17_fence_leaf *out, size_t capacity); +int asahi_g17_collect_fences_coalesced(struct dma_fence *head, + struct asahi_g17_fence_leaf *out, + size_t capacity); void asahi_g17_put_fence(struct dma_fence *fence); struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t count); diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index 356fca680b23c..4d7629a8ffe77 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -14,6 +14,8 @@ pub(crate) struct Leaf { unsafe extern "C" { fn asahi_g17_collect_fences(head: *mut bindings::dma_fence, out: *mut Leaf, capacity: usize) -> i32; + fn asahi_g17_collect_fences_coalesced(head: *mut bindings::dma_fence, + out: *mut Leaf, capacity: usize) -> i32; fn asahi_g17_put_fence(fence: *mut bindings::dma_fence); fn asahi_g17_merge_fences(fences: *const *mut bindings::dma_fence, count: usize) -> *mut bindings::dma_fence; @@ -42,27 +44,40 @@ impl Drop for Leaf { } } -/// Allocation, unsupported containers, or a large prefix retain normal waits. -pub(crate) fn collect(input: &Fence) -> Option> { +fn collect_with( + input: &Fence, + collector: unsafe extern "C" fn(*mut bindings::dma_fence, *mut Leaf, usize) -> i32, +) -> Option> { let mut capacity = 4; loop { let mut leaves = KVec::with_capacity(capacity, GFP_KERNEL).ok()?; // SAFETY: The input owns its fence. The C helper writes at most capacity // fully initialized records and releases every reference on failure. - let count = unsafe { - asahi_g17_collect_fences(input.raw(), leaves.as_mut_ptr(), capacity) - }; + let count = unsafe { collector(input.raw(), leaves.as_mut_ptr(), capacity) }; if count == ENOSPC.to_errno() && capacity < 128 { capacity = (capacity * 4).min(128); continue; } - if count < 0 { return None; } + if count < 0 { + return None; + } // SAFETY: The helper returned this many initialized, owned records. unsafe { leaves.set_len(count as usize) }; return Some(leaves); } } +/// Allocation, unsupported containers, or a large prefix retain normal waits. +pub(crate) fn collect(input: &Fence) -> Option> { + collect_with(input, asahi_g17_collect_fences) +} + +/// Like [`collect`], coalescing unsignalled non-error leaves sharing a `dma_fence` context to +/// their latest sequence number so deep timeline chains stay bounded by distinct contexts. +pub(crate) fn collect_coalesced(input: &Fence) -> Option> { + collect_with(input, asahi_g17_collect_fences_coalesced) +} + use super::fence::Submission; use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index c0dd3e2616dcc..0843277bc9368 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -3,7 +3,9 @@ """Exercise production DMA-fence lockdep guard and Timeline off-pending signalling.""" from common import kernel_root, output_dir, rustc, sha import json +import os import pathlib +import shlex import subprocess import tempfile @@ -92,6 +94,10 @@ def extract_function(text, name): fence_source.index('/// Inline storage for the common 0-2 input fences'): fence_source.index('/// Reads a retained dependency') ] +fw_waits_src = fence_source[ + fence_source.index('/// Maximum distinct cross-queue firmware waits'): + fence_source.index('/// Fence operations of G16 job fences.') +] syncs_src = fence_source[ fence_source.index('/// The syncs of one SUBMIT.'): ] @@ -417,9 +423,92 @@ def extract_function(text, name): assert_eq!(log2.borrow().failed, vec![Fence(ENOMEM.0)]); } } + +mod fw_waits_test { + use super::{Error, Result, GFP_KERNEL}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; + + const E2BIG: Error = Error(-7); + + pub(crate) struct QueueState(u32); + + pub(crate) struct KVec(Vec); + impl KVec { + fn with_capacity(cap: usize, _flags: u32) -> Result { + Ok(Self(Vec::with_capacity(cap))) + } + fn push(&mut self, v: T, _flags: u32) -> Result { + self.0.push(v); + Ok(()) + } + fn push_within_capacity(&mut self, v: T) -> std::result::Result<(), T> { + self.0.push(v); + Ok(()) + } + } + impl core::ops::Deref for KVec { + type Target = [T]; + fn deref(&self) -> &[T] { &self.0 } + } + impl core::ops::DerefMut for KVec { + fn deref_mut(&mut self) -> &mut [T] { &mut self.0 } + } + + FW_WAITS_SRC + + #[test] + fn fw_waits_coalesces_deep_two_queue_timeline_chain_and_merges_engines() { + let q0 = Arc::new(QueueState(0)); + let q1 = Arc::new(QueueState(1)); + let mut waits = FwWaits::Empty; + // 64 alternating timeline hops across 2 queues coalesce to 2 per-queue entries. + for hop in 1..=64u64 { + let (q, r, c) = if hop % 2 == 1 { + (q0.clone(), Some((hop + 1) / 2), Some(hop)) + } else { + (q1.clone(), None, Some(hop / 2)) + }; + let origin = Arc::new(FenceOrigin::new(1, 7, q, [r, c])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), 2); + let w0 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q0)).unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w0.last_ordinal, [Some(32), Some(63)]); + assert_eq!(w1.last_ordinal, [None, Some(32)]); + + // Merging an earlier render-only origin with a later compute-only origin on q1 keeps both. + waits + .push_unique(Arc::new(FenceOrigin::new(1, 7, q1.clone(), [Some(5), None]))) + .unwrap(); + let w1 = waits.iter().find(|w| Arc::ptr_eq(&w.queue, &q1)).unwrap(); + assert_eq!(w1.last_ordinal, [Some(5), Some(32)]); + } + + #[test] + fn fw_waits_caps_distinct_queues_at_max_fw_waits() { + let mut waits = FwWaits::Empty; + for idx in 0..MAX_FW_WAITS { + let q = Arc::new(QueueState(idx as u32)); + let origin = Arc::new(FenceOrigin::new(1, 7, q, [None, Some(1)])); + waits.push_unique(origin).unwrap(); + } + assert_eq!(waits.len(), MAX_FW_WAITS); + let extra = Arc::new(FenceOrigin::new( + 1, + 7, + Arc::new(QueueState(99)), + [None, Some(1)], + )); + assert_eq!(waits.push_unique(extra), Err(E2BIG)); + } +} '''.replace('SIGNAL_BATCH_LINE', signal_batch_line).replace( 'TIMELINE_COMPLETE_FN', timeline_complete_fn ).replace('INPUT_FENCES_SRC', input_fences_src).replace( + 'FW_WAITS_SRC', fw_waits_src +).replace( 'SYNCS_SRC', syncs_src.replace('crate::g17::', 'g17::') ) @@ -439,9 +528,247 @@ def extract_function(text, name): if result.returncode: raise SystemExit(result.returncode) +# Exercise the actual production g17/sync_input.c collector against lightweight C dma_fence +# and dma_fence_chain shims to prove deep 2-queue timeline chains coalesce without -ENOSPC, +# skip signalled leaves, and preserve error leaves. +sync_input_c = root / 'drivers/gpu/drm/asahi/g17/sync_input.c' +sync_input_dir = sync_input_c.parent +c_harness = r''' +#include +#include +#include +#include +#include +#include +#include + +typedef uint64_t u64; +#define ASAHI_G17_SYNC_SCOPE_H 1 +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define GFP_KERNEL 0 + +struct dma_fence { + uint64_t context; + uint64_t seqno; + int status; + int refcount; + bool is_chain; + bool is_container; + struct dma_fence *chain_next; + struct dma_fence *chain_fence; +}; + +struct dma_fence_unwrap { + struct dma_fence *chain; + struct dma_fence *array; + unsigned int index; +}; + +static inline struct dma_fence *dma_fence_get(struct dma_fence *f) +{ + if (f) + ++f->refcount; + return f; +} + +static inline void dma_fence_put(struct dma_fence *f) +{ + if (f) { + assert(f->refcount > 0); + --f->refcount; + } +} + +static inline int dma_fence_get_status(struct dma_fence *f) +{ + return f ? f->status : 1; +} + +static inline bool dma_fence_is_later(struct dma_fence *f1, struct dma_fence *f2) +{ + return f1->seqno > f2->seqno; +} + +static inline bool dma_fence_is_container(struct dma_fence *f) +{ + return f && (f->is_chain || f->is_container); +} + +static inline struct dma_fence *dma_fence_unwrap_first(struct dma_fence *head, + struct dma_fence_unwrap *cursor) +{ + cursor->chain = NULL; + cursor->array = NULL; + cursor->index = 0; + if (!head) + return NULL; + if (head->is_chain) { + cursor->chain = dma_fence_get(head); + return head->chain_fence; + } + return head; +} + +static inline struct dma_fence *dma_fence_unwrap_next(struct dma_fence_unwrap *cursor) +{ + struct dma_fence *next; + + if (!cursor->chain) + return NULL; + next = cursor->chain->chain_next; + dma_fence_put(cursor->chain); + if (!next) { + cursor->chain = NULL; + return NULL; + } + cursor->chain = dma_fence_get(next); + return next->chain_fence; +} + +#define dma_fence_unwrap_for_each(fence, cursor, head) \ + for ((fence) = dma_fence_unwrap_first((head), (cursor)); (fence); \ + (fence) = dma_fence_unwrap_next((cursor))) + +static inline void *kmalloc_array(size_t n, size_t size, int flags) +{ + (void)flags; + return calloc(n, size); +} + +static inline void kfree(void *p) +{ + free(p); +} + +static inline struct dma_fence *__dma_fence_unwrap_merge(unsigned int n, + struct dma_fence **f, + struct dma_fence_unwrap *c) +{ + (void)n; + (void)f; + (void)c; + return NULL; +} + +static inline bool asahi_g17_is_scope(struct dma_fence *f) +{ + (void)f; + return false; +} + +static inline unsigned int asahi_g17_scope_children(struct dma_fence *f, + struct dma_fence *out[2]) +{ + (void)f; + (void)out; + return 0; +} + +#include "sync_input.h" +#include "sync_input.c" + +int main(void) +{ + enum { HOPS = 256 }; + struct dma_fence leaves[HOPS]; + struct dma_fence chains[HOPS]; + struct asahi_g17_fence_leaf out[4]; + int n, i; + + /* 256 alternating unsignalled hops across 2 contexts (10 and 20). */ + memset(leaves, 0, sizeof(leaves)); + memset(chains, 0, sizeof(chains)); + for (i = 0; i < HOPS; ++i) { + leaves[i].context = (i % 2 == 0) ? 10 : 20; + leaves[i].seqno = (uint64_t)(i / 2 + 1); + leaves[i].status = 0; + leaves[i].refcount = 1; + + chains[i].is_chain = true; + chains[i].refcount = 1; + chains[i].chain_fence = &leaves[i]; + chains[i].chain_next = (i > 0) ? &chains[i - 1] : NULL; + } + + /* Coalesced collector fits a 256-hop 2-queue timeline chain into capacity=4 with 2 leaves. */ + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 2); + assert((out[0].fence == &leaves[HOPS - 1] && out[1].fence == &leaves[HOPS - 2]) || + (out[1].fence == &leaves[HOPS - 1] && out[0].fence == &leaves[HOPS - 2])); + for (i = 0; i < n; ++i) { + assert(out[i].status == 0); + asahi_g17_put_fence(out[i].fence); + } + + /* Non-coalesced collector still sees distinct unsignalled leaves and hits -ENOSPC at cap=4. */ + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == -ENOSPC); + + /* Already-signalled leaves (status > 0) are skipped by both collectors. */ + for (i = 0; i < HOPS; ++i) + leaves[i].status = 1; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 0); + n = asahi_g17_collect_fences(&chains[HOPS - 1], out, 4); + assert(n == 0); + + /* Error leaf (status < 0) is preserved even when a later same-context leaf is unsignalled. */ + leaves[5].status = -5; + leaves[HOPS - 1].status = 0; + leaves[HOPS - 2].status = 0; + n = asahi_g17_collect_fences_coalesced(&chains[HOPS - 1], out, 4); + assert(n == 3); + { + bool saw_err = false, saw_ctx10 = false, saw_ctx20 = false; + for (i = 0; i < n; ++i) { + if (out[i].fence == &leaves[5] && out[i].status == -5) + saw_err = true; + else if (out[i].fence == &leaves[HOPS - 2] && out[i].status == 0) + saw_ctx10 = true; + else if (out[i].fence == &leaves[HOPS - 1] && out[i].status == 0) + saw_ctx20 = true; + asahi_g17_put_fence(out[i].fence); + } + assert(saw_err && saw_ctx10 && saw_ctx20); + } + + /* Every refcount returns cleanly to 1 (no leaks or double puts). */ + for (i = 0; i < HOPS; ++i) { + assert(leaves[i].refcount == 1); + assert(chains[i].refcount == 1); + } + printf("sync_input C coalescing tests passed (256-hop chain -> 2 leaves, error preserved)\n"); + return 0; +} +''' + +with tempfile.TemporaryDirectory(prefix='m4-c-sync-input-') as directory: + directory = pathlib.Path(directory) + (directory / 'linux').mkdir() + for hdr in ('dma-fence.h', 'dma-fence-unwrap.h', 'slab.h', 'types.h'): + (directory / 'linux' / hdr).write_text('/* host shim */\n') + (directory / 'linux' / 'errno.h').write_text('#define ENOSPC 28\n#define EOPNOTSUPP 95\n') + (directory / 'sync_scope.h').write_text('/* host shim */\n') + c_unit = directory / 'test_sync_input.c' + c_unit.write_text(c_harness) + c_bin = directory / 'test_sync_input' + cc = shlex.split(os.environ.get('CC', 'cc')) + for command in [ + cc + ['-Wall', '-Wextra', '-Werror', '-I', str(directory), '-I', str(sync_input_dir), + str(c_unit), '-o', str(c_bin)], + [str(c_bin)], + ]: + result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + logs += result.stdout + print(result.stdout, end='') + (out / 'fence-signalling.log').write_text(logs) + if result.returncode: + raise SystemExit(result.returncode) + (out / 'fence-signalling.json').write_text(json.dumps({ - 'passed': True, 'tests': 8, 'negative_compile_checks': 1, 'cpu_only': True, - 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants and g16 Timeline::complete() off-pending FIFO batch signalling.', + 'passed': True, 'tests': 11, 'negative_compile_checks': 1, 'cpu_only': True, + 'scope': 'Production RAII annotation compiled in both CONFIG_LOCKDEP variants, g16 Timeline::complete() off-pending FIFO batch signalling, FwWaits per-queue coalescing, and g17/sync_input.c chain coalescing.', 'source_sha256': sha(production), 'timeline_source_sha256': sha(fence_source_path), + 'sync_input_source_sha256': sha(sync_input_c), }, indent=2) + '\n') From 9cd259d4c29051ae2633a481c7ee3c946ab78b4c Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 08:34:11 -0500 Subject: [PATCH 04/10] drm/asahi: g16: prefer warm VM-affine compute units when claiming When multiple processes interleave compute submissions on G16, pure round-robin compute-unit claiming rotates each VM onto another VM's recently retired unit, forcing a full WC scrub, 160-byte WC descriptor read-back, and 8 KiB full work write on every dispatch. Update Slots::claim_compute_for_pipe() to prefer a displaced warm unit already owned by the requesting VM (!scrub_full), then an unowned unit, before falling back to round-robin over the pipe's eligible range. This keeps concurrent multi-VM compute workloads on their own warm units while preserving base-unit pipe-0 isolation and quarantine fallback. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/slots.rs | 71 +++++++++++++------ .../drivers/gpu/asahi-m4/test-resources.py | 67 +++++++++++++++++ 2 files changed, 118 insertions(+), 20 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 7a4cfeb10aeb6..9f27082581230 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -1025,7 +1025,8 @@ impl Slots { if f.slot_count as usize >= f.slot.len() { return Ok(None); } - // Round robin over this VM's units eligible for `pipe`: pipe 0 spans `0..n`, while + // Prefer a warm unit already owned by `vm_id` (`!scrub_full`), then an unowned unit, + // before falling back to round-robin over `start..n`: pipe 0 spans `0..n`, while // secondary pipes stay in `BASE_COMPUTE_UNITS..n` so base units `0..2` only ever hold // pipe-0 leases and a 2-unit VM can never hit `compute_exhausted_within(2)`. let n = units.compute_units()?.min(sizes::COMPUTE_UNITS); @@ -1039,28 +1040,58 @@ impl Slots { } let span = n - start; let base_cursor = (self.cursor as usize).saturating_sub(start) % span; - for i in 0..span { - let k = start + (base_cursor + i) % span; - if self.compute.lifetime.claim(k) { - let full = self.compute.scrub_full[k] - || vm_id.is_none_or(|id| { - self.compute.owner[k] - .as_ref() - .is_none_or(|prev| prev.id != id) - }); - if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub(full)) { - self.compute.lifetime.cancel(k); - return Err(e); + let mut chosen = None; + if let Some(id) = vm_id { + for i in 0..span { + let k = start + (base_cursor + i) % span; + if !self.compute.scrub_full[k] + && self.compute.owner[k] + .as_ref() + .is_some_and(|prev| prev.id == id) + && self.compute.lifetime.claim(k) + { + chosen = Some(k); + break; + } + } + if chosen.is_none() { + for i in 0..span { + let k = start + (base_cursor + i) % span; + if self.compute.owner[k].is_none() && self.compute.lifetime.claim(k) { + chosen = Some(k); + break; + } } - self.compute.last_full[k] = full; - f.slot[f.slot_count as usize] = k as u32; - f.slot_count += 1; - f.compute_pipe = pipe as u8; - self.cursor = ((k + 1) % n) as u32; - return Ok(Some(k)); } } - Ok(None) + if chosen.is_none() { + for i in 0..span { + let k = start + (base_cursor + i) % span; + if self.compute.lifetime.claim(k) { + chosen = Some(k); + break; + } + } + } + let Some(k) = chosen else { + return Ok(None); + }; + let full = self.compute.scrub_full[k] + || vm_id.is_none_or(|id| { + self.compute.owner[k] + .as_ref() + .is_none_or(|prev| prev.id != id) + }); + if let Err(e) = units.compute_unit(k).and_then(|unit| unit.scrub(full)) { + self.compute.lifetime.cancel(k); + return Err(e); + } + self.compute.last_full[k] = full; + f.slot[f.slot_count as usize] = k as u32; + f.slot_count += 1; + f.compute_pipe = pipe as u8; + self.cursor = ((k + 1) % n) as u32; + Ok(Some(k)) } #[allow(dead_code)] pub(crate) fn pick_pass( 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 be994dc4e53eb..7687dfb409bab 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -1755,6 +1755,73 @@ def module(text, name): assert!(p.reusable_for_within(1, &vm1, 2, 2048).is_some()); } + #[test]fn vm_affine_compute_claiming_keeps_four_interleaved_vms_warm(){ + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut units = KVec::new(); + for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { + units.push(g16::slots::ComputeSlot::new(&mut o, k).unwrap(), 0).unwrap(); + } + let prep = g16::resources::ComputeArena { compute: units, render: None }; + let vms = [vm(1), vm(2), vm(3), vm(4)]; + // Round 0 warms one unit per VM (4 units out of 24); VM2's retirement displaces VM1's + // unit immediately so from round 1 onward every sequential interleaved claim is warm. + for v in &vms { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + assert!(s.compute_needs_full_work(k)); + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + s.retire(&mut c).unwrap(); + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + for _round in 0..4 { + for v in &vms { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + assert!(!s.compute_needs_full_work(k)); + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + s.retire(&mut c).unwrap(); + } + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + // Pipelined depth-2 per VM across 4 concurrent VMs warms one additional unit per VM + // from the unowned pool and then reuses warm VM-owned units with zero cross-VM scrubs. + let mut live: Vec = Vec::new(); + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if idx < 3 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + live.push(c); + } + for _round in 0..4 { + for (idx, v) in vms.iter().enumerate() { + let mut c = Claims::new(); + let k = s.claim_compute_for(&prep, &mut c, Some(v.id)).unwrap().unwrap(); + if _round > 0 { + assert!(!s.compute_needs_full_work(k)); + } + s.hold_vm(&c, v).unwrap(); + s.publish(&mut c).unwrap(); + s.note_published(&c); + let mut old = std::mem::replace(&mut live[idx], c); + s.retire(&mut old).unwrap(); + } + } + for mut c in live { + s.retire(&mut c).unwrap(); + } + assert_eq!(s.stats.cross_vm_retargets[0], 0); + } + } ''' poll_source = (production/'poll.rs').read_text() From e30cdb92b4f596a5c183f35abb8d401e4ca84320 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 12:56:36 -0500 Subject: [PATCH 05/10] drm/asahi: g16: scale warm render PB/UMA slots to 16 and keep pass slots VM-affine Multi-process render workloads with d=4, 8, or 16 concurrent VMs thrashed the two shared base PB/UMA allocator slots, forcing full engine drains and InitBM epoch reinitializations on every cross-VM handoff as well as cross-VM full pass-slot scrubs. Expand the device-wide warm PB/UMA allocator pool to 16 slots (WARM_PB_SLOTS = 16, hardware UMA slots 33..48) plus 4 lazy quarantine spares (EXT_PB_SLOTS = 4, hardware UMA slots 49..52) while keeping every VM's client VA footprint unchanged at 2 base units (local indices 0..2, assigned rotating [home, alt] pairs) and up to 4 lazy recovery spares (local indices 2..6). Add mask-based Pools selection that prefers a VM's unused home slot so 16 concurrent VMs bind 16 disjoint warm slots regardless of arrival order and pipeline with zero InitBM after warmup. Add VM-affine render pass selection (Slots::pick_pass_in_for) and scale bursting VMs to Tier 1 pass headroom (18 slots) when active_render_vms >= 8 while keeping PB_HEAP_EXT_TIERS gated on single-VM pass demand so concurrent light renders do not expand to 256 MiB PB heaps. Also trim PbEpoch::prepare WC list seeding to the active heap_blocks prefix (plus any shrink tail on unpublished retries). Verified with asahi-m4 (25/25) and asahi-g15 (81/81) host selftests and checkpatch.pl (0 errors, 0 warnings). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 41 ++- drivers/gpu/drm/asahi/g16/hw.rs | 28 +- drivers/gpu/drm/asahi/g16/mod.rs | 13 +- drivers/gpu/drm/asahi/g16/poll.rs | 4 +- drivers/gpu/drm/asahi/g16/pools.rs | 196 +++++++++++- drivers/gpu/drm/asahi/g16/queue.rs | 4 +- drivers/gpu/drm/asahi/g16/resources.rs | 212 ++++++++++--- drivers/gpu/drm/asahi/g16/slots.rs | 70 ++++- .../drivers/gpu/asahi-m4/test-publication.py | 5 +- .../drivers/gpu/asahi-m4/test-resources.py | 290 +++++++++++++++--- 10 files changed, 717 insertions(+), 146 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 773207879b5e9..722b2fba551f8 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -1127,8 +1127,8 @@ impl Firmware { && matches!(command(&job, job.progress.sent()), Some(Command::Render(_))) && (job .resources - .pb_slots() - .is_ok_and(|n| self.pools.exhausted_for_within(&job.vm, n)) + .pb_slot_mask() + .is_ok_and(|(mask, home)| self.pools.exhausted_for_mask(&job.vm, mask, home)) || job .resources .render_passes() @@ -1305,10 +1305,11 @@ impl Firmware { || (is_render && !job .resources - .pb_slots() - .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(n, blocks)| { - self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + .pb_slot_mask() + .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(mask, home, blocks)| { + self.pools + .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) })) } @@ -1486,10 +1487,11 @@ impl Firmware { && super::recovery::logic::next_ordinal(e.draw).is_some() && job .resources - .pb_slots() - .and_then(|n| Ok((n, job.resources.pb_heap_blocks()?))) - .is_ok_and(|(n, blocks)| { - self.pools.can_pipeline_within_blocks(&job.vm, n, blocks) + .pb_slot_mask() + .and_then(|(mask, home)| Ok((mask, home, job.resources.pb_heap_blocks()?))) + .is_ok_and(|(mask, home, blocks)| { + self.pools + .can_pipeline_in_mask_blocks(&job.vm, mask, home, blocks) }) && job .resources @@ -1829,13 +1831,13 @@ impl Firmware { let mut a = job .resources .prepare_pb_in_flight(alloc_slot, draw, render_pipelined)?; - let pb_slots = job.resources.pb_slots()?; + let (pb_mask, _) = job.resources.pb_slot_mask()?; let heap_blocks = job.resources.pb_heap_blocks()?; // Reuse this VM's retired epoch of the allocator slot when still bound and sized for the // VM's current PB heap (no reseed/InitBM); if the PB heap grew, rotate onto a fresh epoch. let (epoch, reused) = match self .pools - .reusable_for_within(alloc_slot, &job.vm, pb_slots, heap_blocks) + .reusable_for_mask(alloc_slot, &job.vm, pb_mask, heap_blocks) { Some(e) => { self.pools.stats.reused += 1; @@ -2271,7 +2273,10 @@ impl Firmware { }) { return Err(E2BIG); } - let Some(k) = self.slots.pick_pass_in(&job.resources, &geometry, 0) else { + let Some(k) = + self.slots + .pick_pass_in_for(&job.resources, &geometry, 0, Some(job.vm.id)) + else { self.engine.slot_wait = true; return Err(EAGAIN); }; @@ -2328,10 +2333,11 @@ impl Firmware { break; } let geo2 = Geometry::new(&r2.cmd, 0); - let Some(k2) = self.slots.pick_pass_in( + let Some(k2) = self.slots.pick_pass_in_for( &job.resources, &geo2, f.claims.pass_mask, + Some(job.vm.id), ) else { break; }; @@ -2457,10 +2463,11 @@ impl Firmware { break; }; let geo2 = Geometry::new(&r2.cmd, 0); - let Some(slot) = self.slots.pick_pass_in( + let Some(slot) = self.slots.pick_pass_in_for( &job.resources, &geo2, picked_mask, + Some(job.vm.id), ) else { precheck_ok = false; break; @@ -3039,11 +3046,11 @@ impl Firmware { .claim_pass_in(resources, k, Some(job.vm.id), geometry.tilemap_bytes)?; self.slots.hold_render_pass(k, &job.vm, resources)?; let (refs, init_buffer) = if member == 0 { - let pb_slots = resources.pb_slots()?; + let (pb_mask, pb_home) = resources.pb_slot_mask()?; let heap_blocks = resources.pb_heap_blocks()?; let alloc_slot = self .pools - .pick_slot_within_blocks(&job.vm, behind, pb_slots, heap_blocks) + .pick_slot_in_mask_blocks(&job.vm, behind, pb_mask, pb_home, heap_blocks) .ok_or(EAGAIN)?; let slot_pipelined = self.pools.slot_inflight(alloc_slot) > 0; let (refs, init_buffer, epoch, binding) = diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index a9c5cad5814db..155c8f528abb2 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -607,9 +607,9 @@ pub(crate) mod client { pub(crate) const CWORK_STRIDE: u64 = 0x4000; // Render allocator units contain one 32 MiB UMA pool and its persistent lists in a - // 64 MiB stride. Slots 0..4 live in 0x7010000000..0x7020000000; slots 4..PB_SLOTS - // live in 0x7008000000..0x7010000000, above base compute units 0..2 (ending at - // 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). + // 64 MiB stride. Per-VM local slots 0..4 live in 0x7010000000..0x7020000000; local slots + // 4..MAX_VM_PB_SLOTS live in 0x7008000000..0x7010000000, above base compute units 0..2 + // (ending at 0x70070c0000) and below the render pass slot window (0x7020000000..0x7040000000). pub(crate) const fn render_base(k: u64) -> u64 { if k < 4 { 0x7010000000 + k * 0x04000000 @@ -714,11 +714,23 @@ pub(crate) mod sizes { pub(crate) const COMPUTE_SLOTS: usize = COMPUTE_UNITS; /// Base physical PB/UMA allocator slots allocated per VM on first render. pub(crate) const BASE_PB_SLOTS: usize = 2; - /// Physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware UMA slot 33). - /// Base slots `0..BASE_PB_SLOTS` serve normal cross-VM switching; extra slots are allocated - /// lazily per VM only after a render hang permanently quarantines an allocator slot. - pub(crate) const PB_SLOTS: usize = 6; - const _: () = assert!(PB_SLOTS >= BASE_PB_SLOTS && PB_SLOTS <= 6); + /// Device-wide warm physical PB/UMA allocator slots (`parameter_id` `0..WARM_PB_SLOTS`, + /// hardware UMA slots `33..33 + WARM_PB_SLOTS`). Each VM maps two base units (`local_idx` + /// `0..BASE_PB_SLOTS`) bound to a rotating `[home, alt]` pair in this pool so up to + /// `WARM_PB_SLOTS` concurrent render VMs stay warm without extra per-VM memory. + pub(crate) const WARM_PB_SLOTS: usize = 16; + /// Lazily allocated recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`, mapped at + /// per-VM local VA indices `BASE_PB_SLOTS..MAX_VM_PB_SLOTS`) claimed only after a render + /// hang permanently quarantines an allocator slot. + pub(crate) const EXT_PB_SLOTS: usize = 4; + /// Maximum PB/UMA allocator slots mapped in one VM's client VA space (`render_base(0..6)`). + pub(crate) const MAX_VM_PB_SLOTS: usize = BASE_PB_SLOTS + EXT_PB_SLOTS; + /// Total device-wide physical PB/UMA allocator slots (`parameter_id` `0..PB_SLOTS`, hardware + /// UMA slots `RENDER_UMA_SLOT..RENDER_UMA_SLOT + PB_SLOTS`). + pub(crate) const PB_SLOTS: usize = WARM_PB_SLOTS + EXT_PB_SLOTS; + const _: () = assert!(WARM_PB_SLOTS >= BASE_PB_SLOTS); + const _: () = assert!(MAX_VM_PB_SLOTS >= BASE_PB_SLOTS && MAX_VM_PB_SLOTS <= 6); + const _: () = assert!(PB_SLOTS <= 32); const _: () = assert!(super::client::compute_context(1) + 0x40000 <= super::client::render_base(4)); const _: () = diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 30c26d3bc62a5..4a3c7a2196658 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -292,8 +292,12 @@ pub(crate) struct Shared { pub(crate) base_compute_quarantined: AtomicBool, /// Whether any base render pass slot (`0..BASE_RENDER_SLOTS`) has been quarantined. pub(crate) base_render_quarantined: AtomicBool, - /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. - pub(crate) needed_pb_slots: AtomicU32, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: AtomicU32, + /// Round-robin cursor assigning each rendering VM a `[home, alt]` pair in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: AtomicU32, + /// Live open VMs that own a `RenderArena`, used to size multi-VM pass-slot headroom. + pub(crate) active_render_vms: Arc, /// The GFX power state word from before a system sleep. sleep_ps: AtomicU32, /// The stop left to a system sleep's commit, until `.complete` finishes it. @@ -629,6 +633,7 @@ impl Gpu { let feed = feed::Feed::new()?; let feed_wq = OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_feed"), false)?; let scrub_queue = slots::ScrubQueue::new_boxed()?; + let active_render_vms = Arc::new(AtomicU32::new(0), GFP_KERNEL)?; let shared = Arc::pin_init( pin_init!(Shared { dev: dev.as_ref().as_ref().into(), @@ -657,7 +662,9 @@ impl Gpu { recovering: AtomicBool::new(false), base_compute_quarantined: AtomicBool::new(false), base_render_quarantined: AtomicBool::new(false), - needed_pb_slots: AtomicU32::new(hw::sizes::BASE_PB_SLOTS as u32), + quarantined_pb_mask: AtomicU32::new(0), + next_pb_slot: AtomicU32::new(0), + active_render_vms, sleep_ps: AtomicU32::new(0), sleep_commit: AtomicPtr::new(core::ptr::null_mut()), events, diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 103423bee3626..3ae477db64104 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1350,8 +1350,8 @@ impl Firmware { .base_render_quarantined .store(self.slots.base_render_quarantined(), Ordering::Release); shared - .needed_pb_slots - .store(self.pools.needed_slots() as u32, Ordering::Release); + .quarantined_pb_mask + .store(self.pools.quarantined_mask(), Ordering::Release); } } diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 54306b109d66c..ed445f21829fd 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -131,7 +131,23 @@ fn write_records( Ok(()) } impl Allocator { + /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. + #[allow(dead_code)] pub(crate) fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { + Self::new_at(o, k, k as u32, heap) + } + /// Render allocator mapped at per-VM local VA index `local_idx` (`0..MAX_VM_PB_SLOTS`) + /// and bound to device-wide hardware slot `hw_slot` (`parameter_id`, UMA slot + /// `RENDER_UMA_SLOT + hw_slot`). + pub(crate) fn new_at( + o: &mut Objects, + local_idx: u64, + hw_slot: u32, + heap: &Arc, + ) -> Result { + if local_idx >= sizes::MAX_VM_PB_SLOTS as u64 || (hw_slot as usize) >= sizes::PB_SLOTS { + return Err(EINVAL); + } let nc = |va| Some((va, pte::LEAF_NC)); // Native UMA software metadata is ASC-owned and never needs a client GPU alias. // In particular its firmware pointers, +0x54 completion and +0x5c exclusion flag @@ -141,18 +157,30 @@ impl Allocator { o, 0x4000, Class::Shared, - nc(client::render_descriptor(k)), + nc(client::render_descriptor(local_idx)), false, )?; let pool = alloc( o, 0x2000000, Class::Shared, - nc(client::render_pool(k)), + nc(client::render_pool(local_idx)), false, )?; - let state = alloc(o, 0x20000, Class::Shared, nc(client::render_state(k)), true)?; - let list = alloc(o, 0x4000, Class::Shared, nc(client::render_list(k)), true)?; + let state = alloc( + o, + 0x20000, + Class::Shared, + nc(client::render_state(local_idx)), + true, + )?; + let list = alloc( + o, + 0x4000, + Class::Shared, + nc(client::render_list(local_idx)), + true, + )?; let submitted = alloc(o, 0x40, Class::Fw, None, true)?; let heap = heap.clone(); super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; @@ -160,7 +188,7 @@ impl Allocator { 0, &buffer::uma_manager_image( descriptor.va, - engine::RENDER_UMA_SLOT + k as u32, + engine::RENDER_UMA_SLOT + hw_slot, gva(&state)?, gva(&list)?, submitted.va, @@ -175,9 +203,13 @@ impl Allocator { submitted, heap, published: AtomicBool::new(false), - id: k as u32, + id: hw_slot, }) } + /// Device-wide hardware PB/UMA slot (`parameter_id`) owned by this allocator unit. + pub(crate) fn id(&self) -> u32 { + self.id + } pub(crate) fn refs(&self) -> Result { let prior = read64(&self.submitted, 0)?; if prior & 1 != 0 { @@ -271,6 +303,14 @@ pub(crate) fn alloc_pb_heap_chunk( impl PoolSet { pub(crate) fn new(o: &mut Objects) -> Result { + Self::new_with_slots(o, [0, 1]) + } + /// Base render allocator units mapped at per-VM local VA indices `0..BASE_PB_SLOTS` and + /// bound to device-wide physical PB/UMA slots `slots`. + pub(crate) fn new_with_slots( + o: &mut Objects, + slots: [usize; sizes::BASE_PB_SLOTS], + ) -> Result { // The firmware copes with a full PB without the host (its overflow counters move and // the scene completes), so the heap is sized well below the 256 MiB window. let heap_blocks = super::params::pb_heap_blocks().min(buffer::MAX_BLOCKS); @@ -282,8 +322,11 @@ impl PoolSet { false, )?; let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; - for k in 0..sizes::BASE_PB_SLOTS as u64 { - units.push(Allocator::new(o, k, &heap)?, GFP_KERNEL)?; + for (local, &hw_slot) in slots.iter().enumerate() { + units.push( + Allocator::new_at(o, local as u64, hw_slot as u32, &heap)?, + GFP_KERNEL, + )?; } Ok(Self { units, @@ -424,6 +467,16 @@ impl Pools { GFP_KERNEL, )?) } + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) fn quarantined_mask(&self) -> u32 { + let mut mask = 0u32; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + mask |= 1u32 << k; + } + } + mask + } /// Number of contiguous PB/UMA allocator slots (`0..n`) each rendering VM should prepare /// so at least [`sizes::BASE_PB_SLOTS`] healthy slots remain available across quarantines. #[allow(dead_code)] @@ -451,6 +504,10 @@ impl Pools { let n = limit.min(sizes::PB_SLOTS); (0..n).any(|k| self.slot_displaced(k)) } + /// Whether at least one displaced physical PB allocator slot exists in `slot_mask`. + fn has_displaced_slot_in_mask(&self, slot_mask: u32) -> bool { + (0..sizes::PB_SLOTS).any(|k| (slot_mask & (1u32 << k)) != 0 && self.slot_displaced(k)) + } /// Allocator slot `k`'s owner epoch, if its render retired normally while the slot was still /// bound to it, it belongs to `vm` and was exposed (its InitBM ran). InitBM binds the /// device-wide slot to one epoch and VM; a fresh epoch handed to the slot rebinds it, so @@ -465,6 +522,26 @@ impl Pools { .then(|| owner.clone()) } /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew + /// past the retired epoch's `heap_blocks` and a displaced slot in `slot_mask` is available + /// to rotate onto safely. + pub(crate) fn reusable_for_mask( + &self, + k: usize, + vm: &Arc, + slot_mask: u32, + min_blocks: u32, + ) -> Option> { + if k >= sizes::PB_SLOTS || (slot_mask & (1u32 << k)) == 0 { + return None; + } + let owner = self.reusable(k, vm)?; + if owner.heap_blocks() >= min_blocks || !self.has_displaced_slot_in_mask(slot_mask) { + Some(owner) + } else { + None + } + } + /// Like [`Self::reusable`], but forces a fresh `InitBM` epoch when the VM's PB heap grew /// past the retired epoch's `heap_blocks` and a displaced slot within `0..limit` is available /// to rotate onto safely. #[allow(dead_code)] @@ -482,6 +559,91 @@ impl Pools { None } } + /// Selects a physical PB/UMA allocator slot in `slot_mask` for `vm`, preferring `home` when + /// claiming an unused warm slot (`0..WARM_PB_SLOTS`) so up to `WARM_PB_SLOTS` concurrent VMs + /// bind disjoint warm slots regardless of arrival order. + pub(crate) fn pick_slot_in_mask_blocks( + &self, + vm: &Arc, + behind: bool, + slot_mask: u32, + home: usize, + min_blocks: u32, + ) -> Option { + let in_mask = |k: usize| k < sizes::PB_SLOTS && (slot_mask & (1u32 << k)) != 0; + if let Some(a) = self.active { + if in_mask(a) + && self + .reusable_for_mask(a, vm, slot_mask, min_blocks) + .is_some() + { + return Some(a); + } + } + if let Some(k) = (0..sizes::PB_SLOTS).find(|&k| { + in_mask(k) + && self + .reusable_for_mask(k, vm, slot_mask, min_blocks) + .is_some() + }) { + return Some(k); + } + if behind { + return None; + } + // Cold (drained): claim the VM's unused home slot first, then any unused warm slot, + // then a displaced warm slot (preferring home), and finally recovery spares. + if home < sizes::WARM_PB_SLOTS + && in_mask(home) + && self.slot_displaced(home) + && self.owners[home].is_none() + { + return Some(home); + } + if let Some(k) = (0..sizes::WARM_PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_none()) + { + return Some(k); + } + if home < sizes::WARM_PB_SLOTS && in_mask(home) && self.slot_displaced(home) { + return Some(home); + } + if let Some(k) = + (0..sizes::WARM_PB_SLOTS).find(|&k| in_mask(k) && self.slot_displaced(k)) + { + return Some(k); + } + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k) && self.owners[k].is_some()) + .or_else(|| { + (sizes::WARM_PB_SLOTS..sizes::PB_SLOTS) + .find(|&k| in_mask(k) && self.slot_displaced(k)) + }) + } + /// Whether `vm` has a warm reusable PB slot in `slot_mask` covering `min_blocks` so it can + /// pipeline without InitBM. + pub(crate) fn can_pipeline_in_mask_blocks( + &self, + vm: &Arc, + slot_mask: u32, + home: usize, + min_blocks: u32, + ) -> bool { + self.pick_slot_in_mask_blocks(vm, true, slot_mask, home, min_blocks) + .is_some() + } + /// Whether no allocator slot in `slot_mask` can accept a render for `vm` once drained. + pub(crate) fn exhausted_for_mask( + &self, + vm: &Arc, + slot_mask: u32, + home: usize, + ) -> bool { + self.inflight.iter().all(|&c| c == 0) + && self + .pick_slot_in_mask_blocks(vm, false, slot_mask, home, 0) + .is_none() + } /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`, requiring any reused /// epoch to cover at least `min_blocks` when a displaced slot is available for rotation. /// @@ -492,6 +654,7 @@ impl Pools { /// When `behind` is false (engine drained), a qualifying warm reusable slot for `vm` is /// preferred; otherwise an already-used displaced slot is chosen first (preserving the 2-slot /// working set) or the lowest fresh slot is claimed. + #[allow(dead_code)] pub(crate) fn pick_slot_within_blocks( &self, vm: &Arc, @@ -518,6 +681,7 @@ impl Pools { .or_else(|| (0..n).find(|&k| self.slot_displaced(k))) } /// Selects a physical PB/UMA allocator slot within `0..limit` for `vm`. + #[allow(dead_code)] pub(crate) fn pick_slot_within( &self, vm: &Arc, @@ -739,6 +903,9 @@ pub(crate) struct PbEpochInner { pub(crate) initbm: Arc, assigned: AtomicU32, heap_blocks: AtomicU32, + /// High-water block count previously written into the zero-allocated `pages`/`blocks` lists, + /// so fresh `InitBM` seeding writes only the active prefix (plus any shrink tail). + seeded_blocks: AtomicU32, exposed: AtomicBool, // Unmap private records before releasing the VM's aliases and ASID. _objects: Objects, @@ -764,6 +931,7 @@ impl PbEpoch { initbm: FwObject::view(&records, 0x400, 0x20)?, assigned: AtomicU32::new(u32::MAX), heap_blocks: AtomicU32::new(0), + seeded_blocks: AtomicU32::new(0), exposed: AtomicBool::new(false), _objects: o, _vm: vm.clone(), @@ -786,13 +954,18 @@ impl PbEpoch { { return Err(EINVAL); } - // Only the backed part of the heap is named; the rest of the lists stays zero. + // Only the backed part of the heap is named; the rest of the zero-allocated lists stays + // zero. On an unpublished retry with fewer blocks, clear the previously seeded tail. + let prev_blocks = self.seeded_blocks.load(Ordering::Acquire); + let write_blocks = heap_blocks.max(prev_blocks); + self.seeded_blocks.store(write_blocks, Ordering::Release); let pages = heap_blocks * buffer::PAGES_PER_BLOCK; - write_records(&self.pages, buffer::MAX_PAGES as usize, |i| { + let write_pages = write_blocks * buffer::PAGES_PER_BLOCK; + write_records(&self.pages, write_pages as usize, |i| { let i = i as u32; (if i < pages { buffer::page_record(heap, i) } else { 0 }).to_le_bytes() })?; - write_records(&self.blocks, buffer::MAX_BLOCKS as usize, |i| { + write_records(&self.blocks, write_blocks as usize, |i| { let b = i as u32; u64::from(if b < heap_blocks { buffer::block_record(heap, b) } else { 0 }).to_le_bytes() })?; @@ -812,6 +985,7 @@ impl PbEpoch { heap_blocks, ), )?; + self.seeded_blocks.store(heap_blocks, Ordering::Release); self.assigned.store(k as u32, Ordering::Release); self.heap_blocks.store(heap_blocks, Ordering::Release); Ok(()) diff --git a/drivers/gpu/drm/asahi/g16/queue.rs b/drivers/gpu/drm/asahi/g16/queue.rs index 27130582a881b..f8e8462a063f1 100644 --- a/drivers/gpu/drm/asahi/g16/queue.rs +++ b/drivers/gpu/drm/asahi/g16/queue.rs @@ -265,7 +265,9 @@ impl Queue { let hints = super::resources::PrepareHints { expand_compute_ext: self.shared.base_compute_quarantined.load(Ordering::Acquire), expand_render_ext: self.shared.base_render_quarantined.load(Ordering::Acquire), - pb_slots: self.shared.needed_pb_slots.load(Ordering::Acquire) as usize, + quarantined_pb_mask: self.shared.quarantined_pb_mask.load(Ordering::Acquire), + next_pb_slot: &self.shared.next_pb_slot, + active_render_vms: &self.shared.active_render_vms, }; let resources = self .vm diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 84871c04b1675..aad844d07e73e 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -106,7 +106,7 @@ const _: () = assert!(EXT_RENDER_TIERS[1].1 == EXT_RENDER_TIERS[2].0); const _: () = assert!(EXT_RENDER_TIERS[2].1 == EXT_RENDER_TIERS[3].0); const _: () = assert!(EXT_RENDER_TIERS[3].1 == super::hw::sizes::RENDER_SLOTS); const BASE_PB_SLOTS: usize = super::hw::sizes::BASE_PB_SLOTS; -const EXT_PB_SLOTS: usize = super::hw::sizes::PB_SLOTS - BASE_PB_SLOTS; +const EXT_PB_SLOTS: usize = super::hw::sizes::EXT_PB_SLOTS; /// Demand-grown contiguous PB heap extensions within the 256 MiB /// [`super::hw::client::PB_HEAP_SIZE`] window so steady 60/120 Hz single-pass clients stay on /// the 64 MiB base heap while multi-pass and heavy 3D workloads expand to 128 MiB (Tier 0) and @@ -124,14 +124,18 @@ const _: () = assert!( const RENDER_BURST_COMMANDS: usize = BASE_RENDER_SLOTS; /// Device-wide hints read locklessly in `SUBMIT` to size per-VM extension backing. -#[derive(Copy, Clone, Default)] -pub(crate) struct PrepareHints { +#[derive(Copy, Clone)] +pub(crate) struct PrepareHints<'a> { /// A base compute unit (`0..BASE_COMPUTE_UNITS`) is quarantined: allocate extension units. pub(crate) expand_compute_ext: bool, /// A base render pass slot (`0..BASE_RENDER_SLOTS`) is quarantined: allocate extension slots. pub(crate) expand_render_ext: bool, - /// Contiguous PB/UMA allocator slots (`BASE_PB_SLOTS..=PB_SLOTS`) needed across quarantines. - pub(crate) pb_slots: usize, + /// Bitmask of permanently quarantined device-wide PB/UMA allocator slots (`0..PB_SLOTS`). + pub(crate) quarantined_pb_mask: u32, + /// Round-robin cursor assigning a VM's `[home, alt]` base PB/UMA slots in `0..WARM_PB_SLOTS`. + pub(crate) next_pb_slot: &'a AtomicU32, + /// Live open VMs owning a `RenderArena`, used for multi-VM pass-slot headroom. + pub(crate) active_render_vms: &'a Arc, } /// Updates the consecutive-compute burst counter and reports whether this submission @@ -209,6 +213,51 @@ fn target_render_slots( target.min(super::hw::sizes::RENDER_SLOTS) } +/// Like [`target_render_slots`], returning `(effective_target, single_vm_target)`. +/// +/// When `active_render_vms` reaches Tier 0's pass-slot ceiling (`EXT_RENDER_TIERS[0].1 == 8`) +/// and this VM is already bursting (`single_vm_target > BASE_RENDER_SLOTS`), `effective_target` +/// expands up to Tier 1 (`EXT_RENDER_TIERS[1].1 == 18`) so up to 16 concurrent render VMs each +/// keep a warm pass slot without cross-VM full-scrub thrashing. Steady 60/120 Hz single-pass +/// clients stay at `BASE_RENDER_SLOTS`, and `single_vm_target` keeps `PB_HEAP_EXT_TIERS` gated +/// on actual single-VM pass demand so multi-VM light renders do not expand to 256 MiB PB heaps. +fn target_render_slots_for( + last_render_ns: &mut u64, + render_burst: &mut u32, + now: u64, + render_count: usize, + active_passes: u32, + base_quarantined: bool, + current_slots: usize, + single_vm_slots: usize, + active_render_vms: u32, +) -> (usize, usize) { + let single = target_render_slots( + last_render_ns, + render_burst, + now, + render_count, + active_passes, + base_quarantined, + single_vm_slots.max(BASE_RENDER_SLOTS), + ); + let mut target = current_slots.max(single); + if single > BASE_RENDER_SLOTS && (active_render_vms as usize) >= EXT_RENDER_TIERS[0].1 { + let multi_need = (active_render_vms as usize) + .saturating_add(1) + .min(EXT_RENDER_TIERS[1].1); + for &(start, end) in &EXT_RENDER_TIERS[..2] { + if target >= multi_need { + break; + } + if target < end && multi_need > start { + target = end; + } + } + } + (target.min(super::hw::sizes::RENDER_SLOTS), single) +} + pub(crate) struct RenderArena(crate::cleanup::Deferred); impl core::ops::Deref for RenderArena { type Target = RenderInner; @@ -219,6 +268,8 @@ impl core::ops::Deref for RenderArena { pub(crate) struct RenderInner { pub(crate) passes: KVec, pub(crate) pools: PoolSet, + /// Device-wide physical PB/UMA allocator slots `[home, alt]` bound to `pools.unit(0..2)`. + pub(crate) base_pb_slots: [usize; BASE_PB_SLOTS], pub(crate) tpc_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_dirty: [AtomicU64; BASE_RENDER_SLOTS], pub(crate) tilemap_last: [AtomicU64; BASE_RENDER_SLOTS], @@ -243,18 +294,20 @@ impl RenderArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, + base_pb_slots: [usize; BASE_PB_SLOTS], ) -> Result> { let mut objects = factory.objects(vm); let mut passes = KVec::with_capacity(BASE_RENDER_SLOTS, GFP_KERNEL)?; for k in 0..BASE_RENDER_SLOTS { passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; } - let pools = PoolSet::new(&mut objects)?; + let pools = PoolSet::new_with_slots(&mut objects, base_pb_slots)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderInner { passes, pools, + base_pb_slots, tpc_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_dirty: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], tilemap_last: [const { AtomicU64::new(0) }; BASE_RENDER_SLOTS], @@ -345,8 +398,9 @@ impl RenderExtArena { } } -/// One lazily allocated recovery PB/UMA allocator slot (`BASE_PB_SLOTS..PB_SLOTS`), -/// sharing the VM's base PB heap so non-fault VMs pay zero extra allocator memory. +/// One lazily allocated recovery PB/UMA allocator slot (`WARM_PB_SLOTS..PB_SLOTS`), +/// mapped at per-VM local VA index `BASE_PB_SLOTS..MAX_VM_PB_SLOTS` and sharing the VM's base PB +/// heap so non-fault VMs pay zero extra allocator memory. pub(crate) struct PoolExtArena(crate::cleanup::Deferred); impl core::ops::Deref for PoolExtArena { type Target = PoolExtInner; @@ -366,11 +420,13 @@ impl PoolExtArena { bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, - slot: usize, + local_idx: usize, + hw_slot: usize, heap: &Arc, ) -> Result> { let mut objects = factory.objects(vm); - let allocator = super::pools::Allocator::new(&mut objects, slot as u64, heap)?; + let allocator = + super::pools::Allocator::new_at(&mut objects, local_idx as u64, hw_slot as u32, heap)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(PoolExtInner { @@ -490,8 +546,13 @@ struct Ready { render_ext: [Option>; EXT_RENDER_TIERS.len()], /// Demand-grown contiguous PB heap extension tiers (`PB_HEAP_EXT_TIERS`). pb_heap_ext: [Option>; PB_HEAP_EXT_TIERS.len()], - /// Recovery PB/UMA allocator slots (`BASE_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. + /// Recovery PB/UMA allocator slots (`WARM_PB_SLOTS..PB_SLOTS`), allocated lazily after hangs. pb_ext: [Option>; EXT_PB_SLOTS], + /// Single-VM render pass slot target (excluding multi-VM Tier 1 expansion), gating + /// `PB_HEAP_EXT_TIERS` so concurrent light-render VMs do not allocate 256 MiB PB heaps. + single_vm_render_slots: usize, + /// Device-wide count of open rendering VMs; decremented once on `Cache::close()` or drop. + render_vm_counter: Option>, /// Last compute submission and the back-to-back run it continues. last_compute_ns: u64, burst: u32, @@ -499,6 +560,13 @@ struct Ready { last_render_ns: u64, render_burst: u32, } +impl Drop for Ready { + fn drop(&mut self) { + if let Some(counter) = self.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } + } +} struct Standby { /// Never-exposed epochs kept on standby for this VM's queued renders. /// Invariant: while open or while `reserved > 0`, `epochs.len() >= reserved as usize`. @@ -662,6 +730,9 @@ impl Cache { self.standby_available.notify_all(); let ready = { let mut ready = self.ready.lock(); + if let Some(counter) = ready.render_vm_counter.take() { + counter.fetch_sub(1, Ordering::AcqRel); + } ( ready.compute.take(), ready.compute_ext.take(), @@ -678,7 +749,7 @@ impl Cache { self: &Arc, vm: &Arc, commands: &[Command], - hints: PrepareHints, + hints: PrepareHints<'_>, ) -> Result { let computes = commands .iter() @@ -733,34 +804,63 @@ impl Cache { } } if render && ready.render.is_none() { + let home = (hints.next_pb_slot.fetch_add(1, Ordering::Relaxed) as usize) + % super::hw::sizes::WARM_PB_SLOTS; + let alt = (home + 1) % super::hw::sizes::WARM_PB_SLOTS; ready.render = Some(RenderArena::new( &self.factory, &self.bind, &vm.vm, &self.live, + [home, alt], )?); + if ready.render_vm_counter.is_none() { + hints.active_render_vms.fetch_add(1, Ordering::AcqRel); + ready.render_vm_counter = Some(hints.active_render_vms.clone()); + } } if render { - let target_pb = hints.pb_slots.clamp(BASE_PB_SLOTS, super::hw::sizes::PB_SLOTS); - if target_pb > BASE_PB_SLOTS { - if let Some(base) = ready.render.as_ref() { + if let Some(base) = ready.render.as_ref() { + let quarantined = hints.quarantined_pb_mask; + let mut healthy = base + .base_pb_slots + .iter() + .filter(|&&slot| (quarantined & (1u32 << slot)) == 0) + .count(); + for (idx, ext) in ready.pb_ext.iter().enumerate() { + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ext.is_some() && (quarantined & (1u32 << hw_slot)) == 0 { + healthy += 1; + } + } + if healthy < BASE_PB_SLOTS { let heap = base.pools.heap().clone(); - for k in BASE_PB_SLOTS..target_pb { - let idx = k - BASE_PB_SLOTS; - if ready.pb_ext[idx].is_none() { - // Best effort: without recovery slots, keep prior PB slots. - ready.pb_ext[idx] = PoolExtArena::new( - &self.factory, - &self.bind, - &vm.vm, - &self.live, - k, - &heap, - ) - .ok(); - if ready.pb_ext[idx].is_none() { - break; - } + for idx in 0..EXT_PB_SLOTS { + if healthy >= BASE_PB_SLOTS { + break; + } + let hw_slot = super::hw::sizes::WARM_PB_SLOTS + idx; + if ready.pb_ext[idx].is_some() + || (quarantined & (1u32 << hw_slot)) != 0 + { + continue; + } + let local_idx = BASE_PB_SLOTS + idx; + // Best effort: without recovery slots, keep prior PB slots. + ready.pb_ext[idx] = PoolExtArena::new( + &self.factory, + &self.bind, + &vm.vm, + &self.live, + local_idx, + hw_slot, + &heap, + ) + .ok(); + if ready.pb_ext[idx].is_some() { + healthy += 1; + } else { + break; } } } @@ -778,7 +878,8 @@ impl Cache { let now = unsafe { kernel::bindings::ktime_get() } as u64; let state = &mut *ready; let active_passes = self.active_render_passes.load(Ordering::Acquire); - let target = target_render_slots( + let active_vms = hints.active_render_vms.load(Ordering::Acquire); + let (target, single_target) = target_render_slots_for( &mut state.last_render_ns, &mut state.render_burst, now, @@ -786,7 +887,10 @@ impl Cache { active_passes, hints.expand_render_ext, current_slots, + state.single_vm_render_slots, + active_vms, ); + state.single_vm_render_slots = state.single_vm_render_slots.max(single_target); for (idx, &(start, end)) in EXT_RENDER_TIERS.iter().enumerate() { if start >= target { break; @@ -809,8 +913,11 @@ impl Cache { } if let Some(base) = ready.render.as_ref() { let base_blocks = base.pools.heap_blocks(); + let single_slots = ready.single_vm_render_slots; for (idx, &(start, end)) in PB_HEAP_EXT_TIERS.iter().enumerate() { - if ready.render_ext[idx].is_none() { + if single_slots < EXT_RENDER_TIERS[idx].1 + || ready.render_ext[idx].is_none() + { break; } if base_blocks >= end { @@ -1015,23 +1122,31 @@ impl Prepared { self.compute_ext.clone() } } - /// Contiguous PB/UMA allocator slots (`0..n`) this job can use. - pub(crate) fn pb_slots(&self) -> Result { - let _ = self.render()?; - let ext = self.pb_ext.iter().take_while(|slot| slot.is_some()).count(); - Ok(BASE_PB_SLOTS + ext) + /// Physical PB/UMA allocator slot bitmask and preferred home slot this job can use. + pub(crate) fn pb_slot_mask(&self) -> Result<(u32, usize)> { + let base = self.render()?; + let mut mask = 0u32; + for &slot in &base.base_pb_slots { + mask |= 1u32 << slot; + } + for (idx, ext) in self.pb_ext.iter().enumerate() { + if ext.is_some() { + mask |= 1u32 << (super::hw::sizes::WARM_PB_SLOTS + idx); + } + } + Ok((mask, base.base_pb_slots[0])) } fn pb_allocator(&self, k: usize) -> Result<&super::pools::Allocator> { let base = self.render()?; - if k < BASE_PB_SLOTS { - base.pools.unit(k).ok_or(EINVAL) - } else { - self.pb_ext - .get(k - BASE_PB_SLOTS) - .and_then(|slot| slot.as_deref()) - .map(|arena| &arena.allocator) - .ok_or(EINVAL) + if let Some(local) = base.base_pb_slots.iter().position(|&slot| slot == k) { + return base.pools.unit(local).ok_or(EINVAL); } + let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS).ok_or(EINVAL)?; + self.pb_ext + .get(idx) + .and_then(|slot| slot.as_deref()) + .map(|arena| &arena.allocator) + .ok_or(EINVAL) } pub(crate) fn prepare_pb_in_flight( &self, @@ -1071,11 +1186,12 @@ impl Prepared { pub(crate) fn pb_owner_arena(&self, k: usize) -> Option { let base = self.render.as_ref()?; let heap_ext = core::array::from_fn(|idx| self.pb_heap_ext[idx].clone()); - if k < BASE_PB_SLOTS { + if base.base_pb_slots.contains(&k) { Some(PbOwnerArena::Base(base.clone(), heap_ext)) } else { + let idx = k.checked_sub(super::hw::sizes::WARM_PB_SLOTS)?; self.pb_ext - .get(k - BASE_PB_SLOTS) + .get(idx) .and_then(|slot| slot.as_ref()) .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone(), heap_ext)) } diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 9f27082581230..900d25b725e0d 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -1147,10 +1147,27 @@ impl Slots { resources: &super::resources::Prepared, geo: &Geometry, picked: u64, + ) -> Option { + self.pick_pass_in_for(resources, geo, picked, None) + } + /// Selects a render pass slot in `resources` with capacity for `geo`, preferring slots + /// already owned by `vm_id` (clean before dirty) and unowned slots before retargeting + /// another VM's warm pass slot. + pub(crate) fn pick_pass_in_for( + &self, + resources: &super::resources::Prepared, + geo: &Geometry, + picked: u64, + vm_id: Option, ) -> Option { let n = resources.render_passes().ok()?.min(sizes::RENDER_SLOTS); - let mut clean_partial = None; - let mut fallback = None; + let mut same_clean_partial = None; + let mut same_dirty = None; + let mut unowned_clean = None; + let mut unowned_dirty = None; + let mut other_full_clean = None; + let mut other_clean_partial = None; + let mut other_dirty = None; let mut saw_scrubbing = false; for i in 0..n { let k = (self.pass_cursor as usize + i) % n; @@ -1166,22 +1183,55 @@ impl Slots { saw_scrubbing = true; continue; } - if self.scrub.is_clean(k) { - if let Ok(d) = resources.render_pass_dirty(k) { + let clean = self.scrub.is_clean(k); + let full_clean = clean + && resources.render_pass_dirty(k).is_ok_and(|d| { let need = d.tilemap.load(Ordering::Acquire).min(geo.tilemap_bytes); - if need <= d.tilemap_clean.load(Ordering::Acquire) + need <= d.tilemap_clean.load(Ordering::Acquire) && d.heap.load(Ordering::Acquire) == 0 - { + }); + if let Some(id) = vm_id { + let same_vm = !self.render.scrub_full[k] + && self.render.owner[k].as_ref().is_some_and(|o| o.id == id); + if same_vm { + if full_clean { return Some(k); } + if clean { + same_clean_partial.get_or_insert(k); + } else { + same_dirty.get_or_insert(k); + } + } else if self.render.owner[k].is_none() { + if full_clean { + unowned_clean.get_or_insert(k); + } else { + unowned_dirty.get_or_insert(k); + } + } else if full_clean { + other_full_clean.get_or_insert(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); } - clean_partial.get_or_insert(k); - continue; + } else if full_clean { + return Some(k); + } else if clean { + other_clean_partial.get_or_insert(k); + } else { + other_dirty.get_or_insert(k); } - fallback.get_or_insert(k); } } - if let Some(k) = clean_partial.or(fallback) { + if let Some(k) = same_clean_partial + .or(same_dirty) + .or(unowned_clean) + .or(unowned_dirty) + .or(other_full_clean) + .or(other_clean_partial) + .or(other_dirty) + { return Some(k); } if saw_scrubbing { 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 f15af074a6221..269925c85b000 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-publication.py @@ -117,7 +117,7 @@ def item(declaration): fn count(&self)->u32{self.count} fn set_pending(&self,v:bool){self.pending.store(v,Ordering::Relaxed)} } -struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}fn pb_slots(&self)->Result{Ok(2)}fn pb_heap_blocks(&self)->Result{Ok(512)}} +struct Resources;impl Resources{fn compute_units(&self)->Result{Ok(2)}fn render_passes(&self)->Result{Ok(8)}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} @@ -162,9 +162,11 @@ def item(declaration): fn exhausted(&self)->bool{self.exhausted} fn exhausted_for(&self,vm:&Vm)->bool{self.exhausted_vm==Some(vm.slot)} fn exhausted_for_within(&self,vm:&Vm,_limit:usize)->bool{self.exhausted_for(vm)} + fn exhausted_for_mask(&self,vm:&Vm,_mask:u32,_home:usize)->bool{self.exhausted_for(vm)} fn can_pipeline(&self,vm:&Arc)->bool{self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} + fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} } mod encode { pub struct ComputeRefs{pub invalid:bool} @@ -744,6 +746,7 @@ def item(declaration): fn can_pipeline(&self,vm:&Arc)->bool{self.can_pipeline&&self.block_pipeline_vm!=Some(vm.slot)} fn can_pipeline_within(&self,vm:&Arc,_limit:usize)->bool{self.can_pipeline(vm)} fn can_pipeline_within_blocks(&self,vm:&Arc,limit:usize,_min_blocks:u32)->bool{self.can_pipeline_within(vm,limit)} + fn can_pipeline_in_mask_blocks(&self,vm:&Arc,_mask:u32,_home:usize,_min_blocks:u32)->bool{self.can_pipeline(vm)} } struct QueueBehindHost{graph:QueueBehindGraph,engine:QueueBehindEngine,slots:QueueBehindSlots,pools:QueueBehindPools} mod queue_behind_scope { 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 7687dfb409bab..860e6f89d8240 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -97,10 +97,10 @@ def module(text, name): #[derive(Copy,Clone,Debug,Eq,PartialEq)]pub enum Class{Shared,Fw,FwCached,SharedCached,Mmio} pub enum Placement{Anywhere} pub struct Request{pub size:usize,pub class:Class,pub placement:Placement,pub offset:usize,pub client:Option<(u64,u64)>,pub lower:Option,pub cpu:bool} - pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool} + pub struct FwObject{pub class:Class,pub client_leaf:Option,pub va:u64,pub gva:Option,pub lower_gva:Option,pub lower_leaf:Option,pub size:usize,pub mapped:usize,pub offset:usize,pub data:std::sync::Arc>>,pub fills:std::sync::Mutex>,pub fail_fill:std::sync::atomic::AtomicBool,pub write_bytes:std::sync::atomic::AtomicUsize} impl FwObject{ - pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false)},0)} - pub fn write(&self,o:usize,b:&[u8])->Result{let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} + pub fn view(o:&Arc,offset:usize,size:usize)->Result>{Arc::new(Self{class:o.class,client_leaf:None,va:o.va+offset as u64,gva:None,lower_gva:None,lower_leaf:None,size,mapped:o.mapped,offset:o.offset+offset,data:o.data.clone(),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)} + pub fn write(&self,o:usize,b:&[u8])->Result{self.write_bytes.fetch_add(b.len(),std::sync::atomic::Ordering::Relaxed);let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+b.len()].copy_from_slice(b);Ok(())} pub fn fill(&self,o:usize,v:u8,n:usize)->Result{if self.fail_fill.swap(false,std::sync::atomic::Ordering::Relaxed){return Err(EIO);}self.fills.lock().unwrap().push((o,n));let mut d=self.data.lock().unwrap();d[self.offset+o..self.offset+o+n].fill(v);Ok(())} pub fn w32(&self,o:usize,v:u32)->Result{self.write(o,&v.to_le_bytes())} pub fn w64(&self,o:usize,v:u64)->Result{self.write(o,&v.to_le_bytes())} @@ -109,12 +109,13 @@ def module(text, name): } pub struct Factory; impl Factory{pub fn objects(&self,_:&())->Objects{Objects::new()}} + std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} pub struct Objects{pub objects:Vec>,next:u64} impl Objects{ pub fn new()->Self{Self{objects:vec![],next:0xfffffc2001000000}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=self.next;self.next+=bytes as u64+0x4000;let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false)},0)?;self.objects.push(x.clone());Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=self.next;self.next+=bytes as u64+0x4000;let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -605,9 +606,11 @@ def module(text, name): assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 24); let mut o=Objects::new(); let pools=PoolSet::new(&mut o).unwrap(); - for k in g16::hw::sizes::BASE_PB_SLOTS as u64..g16::hw::sizes::PB_SLOTS as u64 { - let ext=g16::pools::Allocator::new(&mut o,k,pools.heap()).unwrap(); - assert_eq!(ext.refs().unwrap().parameter_id,k as u32); + for idx in 0..g16::hw::sizes::EXT_PB_SLOTS { + let local=(g16::hw::sizes::BASE_PB_SLOTS+idx) as u64; + let hw_slot=(g16::hw::sizes::WARM_PB_SLOTS+idx) as u32; + let ext=g16::pools::Allocator::new_at(&mut o,local,hw_slot,pools.heap()).unwrap(); + 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,k).unwrap(); @@ -702,10 +705,31 @@ def module(text, name): #[test]fn render_allocators_use_distinct_uma_slots_within_firmware_window(){ let mut o=Objects::new(); - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new_with_slots(&mut o,[7,8]).unwrap(); + assert_eq!(pools.unit(0).unwrap().id(),7); + assert_eq!(pools.unit(1).unwrap().id(),8); + assert_eq!( + g16::pools::Allocator::new_at( + &mut o, + g16::hw::sizes::MAX_VM_PB_SLOTS as u64, + 0, + pools.heap() + ).err(), + Some(EINVAL) + ); + assert_eq!( + g16::pools::Allocator::new_at( + &mut o, + 0, + g16::hw::sizes::PB_SLOTS as u32, + pools.heap() + ).err(), + Some(EINVAL) + ); let mut uma_slots=Vec::new(); for k in 0..g16::hw::sizes::PB_SLOTS { - let alloc=g16::pools::Allocator::new(&mut o,k as u64,pools.heap()).unwrap(); + let local=(k % g16::hw::sizes::MAX_VM_PB_SLOTS) as u64; + let alloc=g16::pools::Allocator::new_at(&mut o,local,k as u32,pools.heap()).unwrap(); let refs=alloc.prepare_in_flight(1,false).unwrap(); assert_eq!(refs.parameter_id,k as u32); let desc=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); @@ -827,57 +851,61 @@ def module(text, name): e.prepare(slot,0x70c0000000,2048).unwrap();e.check_assignment(slot).unwrap();e.expose(); e }; + let warm=g16::hw::sizes::WARM_PB_SLOTS; + let ext=g16::hw::sizes::EXT_PB_SLOTS; + let total=g16::hw::sizes::PB_SLOTS; let mut p=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); - // Quarantine 4 slots (0..4): 2 healthy slots (4 and 5) remain for cross-VM switching. - for hang in 0..4usize { - let n=p.needed_slots(); - let slot=p.pick_slot_within(&vm1,false,n).unwrap(); - assert_eq!(slot,hang); + // A VM bound to [0, 1] with all 4 recovery spares (16..20) survives 4 hangs cleanly + // and keeps 2 healthy slots (18, 19) for cross-VM switching. + let vm_mask:u32=(1u32<<0)|(1u32<<1)|(((1u32< global pool exhaustion. + // Cross-VM switching still works cleanly across surviving spares 18 and 19. + let s_a=warm+2;let s_b=warm+3; + assert_eq!(p.pick_slot_in_mask_blocks(&vm1,false,vm_mask,0,0),Some(s_a)); + let ea=mk_epoch(&vm1,s_a); + let b=p.bind(s_a,false);p.publish_flight(s_a);p.retire_flight(s_a,&ea,b,true).unwrap(); + assert_eq!(p.pick_slot_in_mask_blocks(&vm2,false,vm_mask,0,0),Some(s_b)); + let eb=mk_epoch(&vm2,s_b); + let b=p.bind(s_b,false);p.publish_flight(s_b);p.retire_flight(s_b,&eb,b,true).unwrap(); + assert_eq!(p.pick_slot_in_mask_blocks(&vm1,false,vm_mask,0,0),Some(s_a)); + // 5th hang quarantines s_a: only s_b survives (reuse-only for VM2; VM1/VM3 exhausted). + p.publish_flight(s_a); + p.quarantine_flight(s_a,None); + assert!(!p.exhausted_for_mask(&vm2,vm_mask,0)); + assert_eq!(p.pick_slot_in_mask_blocks(&vm2,false,vm_mask,0,0),Some(s_b)); + assert!(p.exhausted_for_mask(&vm1,vm_mask,0)); + assert!(p.exhausted_for_mask(&vm3,vm_mask,0)); p.invalidate(); - assert!(p.exhausted()); + assert!(p.exhausted_for_mask(&vm2,vm_mask,0)); - // Quarantine 5 fresh slots leaving slot 5 fresh: VM2 claims and reuses slot 5 while - // other VMs report per-VM exhaustion without tripping global exhaustion until recovery. + // Quarantine all but the last global slot leaving slot (PB_SLOTS - 1) fresh: + // VM2 claims and reuses it while other VMs report exhaustion until recovery. let mut q=g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); - for _ in 0..5 { + for _ in 0..(total - 1) { let slot=q.pick_slot(&vm1,false).unwrap(); q.publish_flight(slot); q.quarantine_flight(slot,None); assert!(!q.exhausted()); } - assert_eq!(q.pick_slot(&vm2,false),Some(5)); - let qe5=mk_epoch(&vm2,5); - let qb=q.bind(5,false); - q.publish_flight(5); + let last=total-1; + assert_eq!(q.pick_slot(&vm2,false),Some(last)); + let qlast=mk_epoch(&vm2,last); + let qb=q.bind(last,false); + q.publish_flight(last); assert!(!q.exhausted_for(&vm3)); // in-flight: waits for drain first - q.retire_flight(5,&qe5,qb,true).unwrap(); + q.retire_flight(last,&qlast,qb,true).unwrap(); assert!(!q.exhausted()); assert!(!q.exhausted_for(&vm2)); - assert_eq!(q.pick_slot(&vm2,false),Some(5)); + assert_eq!(q.pick_slot(&vm2,false),Some(last)); assert!(q.exhausted_for(&vm1)); assert!(q.exhausted_for(&vm3)); // Recovery invalidates the last surviving slot's epoch -> global pool exhaustion. @@ -1822,6 +1850,177 @@ def module(text, name): assert_eq!(s.stats.cross_vm_retargets[0], 0); } + #[test]fn warm_pb_pool_keeps_sixteen_concurrent_vms_warm_and_handles_overflow(){ + let warm = g16::hw::sizes::WARM_PB_SLOTS; + assert_eq!(warm, 16); + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mk_epoch = |owner: &sync::Arc, slot: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + owner, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.check_assignment(slot).unwrap(); + e.expose(); + e + }; + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let vms: Vec<_> = (0..20usize).map(|i| vm(100 + i as u64)).collect(); + let mask_for = |i: usize| -> (u32, usize) { + let home = i % warm; + let alt = (home + 1) % warm; + ((1u32 << home) | (1u32 << alt), home) + }; + // Prime 16 VMs arriving in scrambled (reverse) order: each claims its own home slot! + let mut epochs = Vec::new(); + for i in (0..warm).rev() { + let (mask, home) = mask_for(i); + let slot = p.pick_slot_in_mask_blocks(&vms[i], false, mask, home, 512).unwrap(); + assert_eq!(slot, home, "VM {i} must claim its home slot {home} despite reverse arrival"); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + epochs.push((i, e)); + } + // All 16 VMs now pipeline concurrently (behind=true) on 16 disjoint warm slots with 0 InitBM. + let mut binds = Vec::new(); + for &(i, ref _e) in &epochs { + let (mask, home) = mask_for(i); + assert!(p.can_pipeline_in_mask_blocks(&vms[i], mask, home, 512)); + let slot = p.pick_slot_in_mask_blocks(&vms[i], true, mask, home, 512).unwrap(); + assert_eq!(slot, home); + assert!(p.reusable_for_mask(slot, &vms[i], mask, 512).is_some()); + let b = p.bind(slot, true); + p.publish_flight(slot); + binds.push((i, slot, b)); + } + for (idx, (i, slot, b)) in binds.into_iter().enumerate() { + assert_eq!(p.slot_inflight(slot), 1); + p.retire_flight(slot, &epochs[idx].1, b, true).unwrap(); + assert_eq!(p.slot_inflight(slot), 0); + let _ = i; + } + // Overflow d=20: VMs 16..20 share warm slots [0..4] cleanly on drained displaced rotation. + for i in warm..20 { + let (mask, home) = mask_for(i); + assert!(!p.can_pipeline_in_mask_blocks(&vms[i], mask, home, 512)); + let slot = p.pick_slot_in_mask_blocks(&vms[i], false, mask, home, 512).unwrap(); + assert_ne!(mask & (1u32 << slot), 0); + let e = mk_epoch(&vms[i], slot); + let b = p.bind(slot, false); + p.publish_flight(slot); + p.retire_flight(slot, &e, b, true).unwrap(); + } + } + + #[test]fn vm_affine_render_pass_claiming_keeps_sixteen_vms_warm_and_scales_tier1(){ + use g16::resources::{BASE_RENDER_SLOTS, EXT_RENDER_TIERS, target_render_slots_for}; + // Steady 60 Hz depth-1 VM stays at BASE_RENDER_SLOTS even when 16 render VMs are active. + let (mut last, mut burst) = (0u64, 0u32); + let (eff, single) = target_render_slots_for(&mut last, &mut burst, 10_000_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 16); + assert_eq!((eff, single), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + // Bursting VM with 4 active render VMs stays at Tier 0 (8 slots). + for step in 1..=3u64 { + let (e, s) = target_render_slots_for(&mut last, &mut burst, 10_000_000 + step * 500_000, 1, 0, false, BASE_RENDER_SLOTS, BASE_RENDER_SLOTS, 4); + if step < 3 { + assert_eq!((e, s), (BASE_RENDER_SLOTS, BASE_RENDER_SLOTS)); + } else { + assert_eq!((e, s), (EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1)); + } + } + // Once active_render_vms reaches 8 or 16, a bursting VM expands effective target to Tier 1 + // (18 slots) while keeping single_vm_target at Tier 0 (8) so PB_HEAP_EXT_TIERS[1] stays off. + let (eff8, single8) = target_render_slots_for(&mut last, &mut burst, 12_000_000, 1, 0, false, EXT_RENDER_TIERS[0].1, EXT_RENDER_TIERS[0].1, 8); + assert_eq!((eff8, single8), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + let (eff16, single16) = target_render_slots_for(&mut last, &mut burst, 12_500_000, 1, 0, false, eff8, single8, 16); + assert_eq!((eff16, single16), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[0].1)); + // Heavy single-VM multi-pass (8 passes) still advances single_vm_target to Tier 1. + let (eff_heavy, single_heavy) = target_render_slots_for(&mut last, &mut burst, 13_000_000, 8, 0, false, eff16, single16, 16); + assert_eq!((eff_heavy, single_heavy), (EXT_RENDER_TIERS[1].1, EXT_RENDER_TIERS[1].1)); + + // 16 concurrent VMs across 18 pass slots stay on 16 disjoint warm pass slots with 0 cross-VM retargets. + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut passes = KVec::new(); + for k in 0..EXT_RENDER_TIERS[1].1 { + passes.push(g16::slots::PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let render = sync::Arc::new(render_arena(passes), 0).unwrap(); + let prep = g16::resources::ComputeArena { + compute: KVec::new(), + render: Some(render), + }; + let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; + let vms: Vec<_> = (0..16u64).map(|i| vm(200 + i)).collect(); + let mut vm_slots = [usize::MAX; 16]; + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + vm_slots[i] = k; + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + // Subsequent interleaved rounds across all 16 VMs hit their own warm pass slots every time! + for _round in 0..4 { + for (i, v) in vms.iter().enumerate() { + let k = s.pick_pass_in_for(&prep, &geo, 0, Some(v.id)).unwrap(); + assert_eq!(k, vm_slots[i], "VM {i} must stay on its warm pass slot"); + s.claim_pass_in(&prep, k, Some(v.id), geo.tilemap_bytes).unwrap(); + assert!(!s.render_needs_full_work(k)); + let mut c = Claims::new(); + c.pass[0] = k as u32; c.pass_count = 1; c.pass_mask = 1u64 << k; + s.hold_render_pass(k, v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + } + assert_eq!(s.stats.cross_vm_retargets[1], 0); + } + + #[test]fn pb_epoch_prepare_seeds_active_prefix_and_clears_shrink_tail(){ + use g16::fw::buffer; + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let v = vm(300); + g16::object::ALL_OBJECTS.with(|a| a.borrow_mut().clear()); + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let (page_obj, block_obj) = g16::object::ALL_OBJECTS.with(|a| { + let objs = a.borrow(); + ( + objs.iter().find(|o| o.gva.is_some() && o.size == buffer::PAGE_LIST_SIZE).unwrap().clone(), + objs.iter().find(|o| o.gva.is_none() && o.size == buffer::BLOCK_LIST_SIZE).unwrap().clone(), + ) + }); + let heap = g16::hw::client::pb_heap(0); + // First prepare for 512 blocks writes ONLY 512*4*4 = 8192 page bytes and 512*8 = 4096 block bytes. + e.prepare(0, heap, 512).unwrap(); + assert_eq!(page_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 4 * 4); + assert_eq!(block_obj.write_bytes.load(std::sync::atomic::Ordering::Relaxed), 512 * 8); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + // Grow unpublished epoch to 1024 blocks, then shrink retry back to 512 blocks: + // tail [512..1024] must be zeroed cleanly. + e.prepare(1, heap, 1024).unwrap(); + assert_ne!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_ne!(block_obj.r32(512 * 8).unwrap(), 0); + e.prepare(2, heap, 512).unwrap(); + assert_eq!(page_obj.r32(512 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(512 * 8).unwrap(), 0); + assert_eq!(page_obj.r32(1023 * 4 * 4).unwrap(), 0); + assert_eq!(block_obj.r32(1023 * 8).unwrap(), 0); + } } ''' poll_source = (production/'poll.rs').read_text() @@ -1875,6 +2074,7 @@ def module(text, name): ) + '\npub(crate) ' + item(resources_source, 'fn should_expand_compute_ext(') + '\npub(crate) ' + item(resources_source, 'fn target_render_slots(') + + '\npub(crate) ' + item(resources_source, 'fn target_render_slots_for(') ) source = source.replace('__CMD_CLASSES__', '\n'.join(item(graph_source, decl) for decl in ('pub(crate) const fn graph_fw(', 'pub(crate) const fn qinfo_cached(', 'pub(crate) const fn cmd_fw(', 'pub(crate) const fn cmd_shared('))).replace('__SET_DIRTY__',item(resources_source,'pub(crate) fn set_dirty(')).replace('__RENDER_BURST__', render_burst_lines) graph_types = '\n'.join( @@ -1907,7 +2107,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 35, + 'result': 'pass', 'tests': 38, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 393cd79df2dd1319add833d5460b16f3a3c37746 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 16:27:28 -0500 Subject: [PATCH 06/10] drm/asahi/g16: reclaim displaced closed-VM slot leases and retain firmware PB/UMA records After a DRM client closes, Gpu::vm_closed() drops its registry and cache references, but device-wide slot tables (Pools::owners/owner_vms and owner_arenas across PB_SLOTS, Slots::render across 48 pass slots, and Slots::compute across 24 compute units) continued holding strong Arc and arena leases indefinitely until later traffic overwrote every slot. Under multi-process render and compute workloads, dead VMs stayed pinned after exit (multi-GiB Unevictable/Shmem and live TTBAT ASIDs), starving subsequent allocations with VK_ERROR_OUT_OF_DEVICE_MEMORY. At the same time, 26B123 RTKit firmware stores per-slot context-0 pointers in pb_mgr_table[0..15] and uma_mgr_table[1..48] that persist across subsequent work on other slots and are walked during GPU timeout recovery, so dropping the tiny firmware-owned metadata records before that exact hardware slot is overwritten would leave dangling firmware table pointers across timeout recovery. Reclaim displaced closed-VM leases cleanly without violating hardware displacement or firmware recovery contracts: - Add Lifetime::is_quarantined() so quarantined slots stay pinned forever without keeping reclaim armed. - Split the tiny firmware-owned metadata records (PbEpoch's pb_manager + counter, render Allocator's UMA descriptor + submitted, and ComputeSlot's kernel-lower work + counter) into VM-free FwLease objects allocated via Factory::fw_objects() without a Vm reference, and retain one FwLease per hardware slot in Pools and Slots until a later retired publication overwrites that exact hardware slot index. - Add Pools::reclaim_closed() and Slots::reclaim_closed() to drop owners, owner VMs, and owner arenas (Deferred-backed, safe under Shared::state) only for displaced, idle, non-pending, non-scrubbing, non-quarantined slots whose VM is closed via lock-free Vm::is_closed(). - Skip closed VMs in Slots::stage_displaced_pass_scrubs(), and arm ScrubState::waiter if a closed VM's displaced pass slot is mid-scrub. - Gate scanning behind Shared::closed_vm_reclaim (read-only Acquire load on the hot path), set in Gpu::vm_closed() and checked in idle/active poll_step(), submit_locked(), and run_housekeeping(). - Add host selftest coverage in test-resources.py and test-poll-retire.py. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/engine.rs | 1 + drivers/gpu/drm/asahi/g16/mod.rs | 5 + drivers/gpu/drm/asahi/g16/object.rs | 50 +- drivers/gpu/drm/asahi/g16/poll.rs | 33 ++ drivers/gpu/drm/asahi/g16/pools.rs | 112 +++- drivers/gpu/drm/asahi/g16/pools/lifetime.rs | 6 + drivers/gpu/drm/asahi/g16/resources.rs | 23 +- drivers/gpu/drm/asahi/g16/slots.rs | 114 ++++- .../drivers/gpu/asahi-m4/test-poll-retire.py | 70 ++- .../drivers/gpu/asahi-m4/test-resources.py | 483 ++++++++++++++++-- 10 files changed, 834 insertions(+), 63 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/engine.rs b/drivers/gpu/drm/asahi/g16/engine.rs index 722b2fba551f8..7994d956ac782 100644 --- a/drivers/gpu/drm/asahi/g16/engine.rs +++ b/drivers/gpu/drm/asahi/g16/engine.rs @@ -2569,6 +2569,7 @@ impl Firmware { f.pb_slot as usize, &job.vm, job.resources.pb_owner_arena(f.pb_slot as usize), + job.resources.pb_uma_lease(f.pb_slot as usize), )?; } // Reserve lifetime ownership before any counter or producer becomes reachable. diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index 4a3c7a2196658..9d12ae3e8df9a 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -250,6 +250,9 @@ pub(crate) struct Shared { /// Set by external state changes (VM teardown, unstarted queue cancellation) so the next /// `poll_step()` re-evaluates `publish_checked()` even while unrelated flights are active. pub(crate) publish_wake: AtomicBool, + /// Set on VM close (and re-armed while any non-quarantined slot still holds a closed VM) + /// so displaced closed-VM slot leases are reclaimed without scanning on the hot path. + pub(crate) closed_vm_reclaim: AtomicBool, /// CPU that last submitted work, for placing the per-CPU completion worker. pub(crate) submitter: AtomicU32, /// CPU whose cluster currently restricts `events_unbound` (`u32::MAX` before first pin). @@ -643,6 +646,7 @@ impl Gpu { crashed: AtomicBool::new(false), evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), submitter: AtomicU32::new(u32::MAX), unbound_cluster_cpu: AtomicU32::new(u32::MAX), unbound_pinning: AtomicBool::new(false), @@ -893,6 +897,7 @@ impl gpu::Gpu for Gpu { } fn vm_closed(&self, vm: &mmu::Vm) { self.vms.close(vm.id()); + self.shared.closed_vm_reclaim.store(true, Ordering::Release); self.shared.wake_publish(); } diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 767df69e03f3e..2ebe1a008fbbb 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -296,11 +296,28 @@ pub(crate) struct Request { /// Private allocation coordinates. Only normal non-cacheable objects may be reclaimed. struct Private { - vm: mmu::Vm, + vm: Option, firmware: core::ops::Range, pending: Option>, } +/// VM-independent firmware-object lease whose backing and firmware/lower mappings stay alive +/// until a later command overwrites the same hardware table slot in firmware RAM. +/// +/// Dropping an `Arc` offloads unmap to `cleanup::Deferred`, so replacing a lease under +/// `Shared::state` never sleeps or blocks fence producers. +pub(crate) struct FwLease(crate::cleanup::Deferred); + +impl FwLease { + pub(crate) fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Ok(Arc::new( + Self(crate::cleanup::Deferred::new(objects)?), + GFP_KERNEL, + )?) + } +} + /// Immutable factory shared by ioctl-side private arena construction. #[derive(Clone)] pub(crate) struct Factory { @@ -317,7 +334,28 @@ impl Factory { uat: self.uat.clone(), window: self.window.clone(), private: Some(Private { - vm: vm.clone(), + vm: Some(vm.clone()), + firmware: self.firmware.clone(), + pending: None, + }), + sealed: false, + fw_next: self.firmware.start, + retained: KVec::new(), + clients: KVec::new(), + mappings: KVec::new(), + error: None, + pages: 0, + } + } + + /// Allocates firmware-only and context-0 lower-alias objects with no client VM binding. + pub(crate) fn fw_objects(&self) -> Objects { + Objects { + dev: self.dev.clone(), + uat: self.uat.clone(), + window: self.window.clone(), + private: Some(Private { + vm: None, firmware: self.firmware.clone(), pending: None, }), @@ -473,7 +511,8 @@ impl Objects { None }; let client_gva = if let Some(range) = client_range { - let mapping = private.vm.map_in_range( + let vm = private.vm.as_ref().ok_or(EINVAL)?; + let mapping = vm.map_in_range( &backing.gem, 0..bytes, hw::PAGE, @@ -485,6 +524,7 @@ impl Objects { self.mappings.push(mapping, GFP_KERNEL)?; Some(address) } else if let Some((gva, leaf)) = req.client { + let vm = private.vm.as_ref().ok_or(EINVAL)?; let end = gva.checked_add(bytes as u64).ok_or(EOVERFLOW)?; if gva < hw::client::CLIENT_APERTURE.start || end > hw::client::CLIENT_APERTURE.end @@ -494,9 +534,7 @@ impl Objects { return Err(EINVAL); } self.mappings.push( - private - .vm - .map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, + vm.map_at(gva, bytes, &backing.gem, mmu::Prot::from_pte(leaf), false)?, GFP_KERNEL, )?; Some(gva) diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index 3ae477db64104..e3252e36b2799 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -272,6 +272,9 @@ impl Shared { }); } if pub_res.is_ok() { + if retired_any || !had_flights { + firmware.reclaim_closed_vm_slots(); + } pub_res = if recovery_pending { let r = firmware.publish(done); if r.is_ok() { @@ -579,6 +582,27 @@ pub(crate) fn ring_passed(c: u32, b: u32, h: u32, t: u32, m: u32) -> bool { } impl Firmware { + /// Reclaims displaced slot leases belonging to closed VMs so dead processes do not keep + /// multi-hundred-MiB render/compute arenas and TTBAT ASIDs pinned while idle. + /// + /// Respects all hardware displacement contracts (active, in-flight, undisplaced, scrubbing, + /// and quarantined slots are preserved) and re-arms `Shared::closed_vm_reclaim` whenever a + /// non-quarantined slot still holds a closed VM awaiting retirement, displacement, or scrub. + pub(crate) fn reclaim_closed_vm_slots(&mut self) { + let Some(shared) = self.engine.shared.as_ref() else { + return; + }; + if !shared.closed_vm_reclaim.load(Ordering::Acquire) + || !shared.closed_vm_reclaim.swap(false, Ordering::AcqRel) + { + return; + } + let remaining = self.pools.reclaim_closed() | self.slots.reclaim_closed(); + if remaining { + shared.closed_vm_reclaim.store(true, Ordering::Release); + } + } + /// One non-sleeping poll step under the device lock. /// /// Retires finished flights and publishes ready work before periodic 1 ms housekeeping so @@ -622,7 +646,12 @@ impl Firmware { self.last_aux_drain_ns = now; ran_housekeeping = true; self.drain_rings()?; + self.reclaim_closed_vm_slots(); if self.recovery_idle()? && self.engine.pending.is_empty() { + let _ = self.slots.take_scrub_woke(); + if let Some(shared) = self.engine.shared.as_ref() { + shared.publish_wake.store(false, Ordering::Release); + } return Ok(false); } } @@ -645,6 +674,9 @@ impl Firmware { .shared .as_ref() .is_some_and(|shared| shared.publish_wake.swap(false, Ordering::AcqRel)); + if retired_any || publish_woke || scrub_woke || housekeeping_due { + self.reclaim_closed_vm_slots(); + } // Skip redundant `publish_checked()` walks on busy polls where nothing could have // unblocked `engine.pending`. `Prepared::drop` releases standby PB epochs only for // `Cache::prepare` waiters (`standby_available`, which enter `submit_locked()` directly), @@ -750,6 +782,7 @@ impl Firmware { self.last_aux_drain_ns = now; } self.last_housekeeping_ns = now; + self.reclaim_closed_vm_slots(); if !self.engine.flights.is_empty() || recovery_pending { self.check_hangs(done)?; } diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index ed445f21829fd..78c93869d57dc 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -15,7 +15,7 @@ pub(crate) mod lifetime; use super::fw::buffer::{self, uma_manager}; use super::hw::{client, engine, pte, sizes}; -use super::object::{Class, FwObject, Objects, Placement, Request}; +use super::object::{Class, Factory, FwLease, FwObject, Objects, Placement, Request}; use super::Firmware; use crate::driver::AsahiDrmDevice; use core::{ @@ -57,6 +57,9 @@ pub(crate) struct Allocator { list: Arc, submitted: Arc, heap: Arc, + /// VM-free firmware lease retaining `descriptor` and `submitted` across closed-VM reclaim + /// until a later render overwrites this hardware UMA slot in firmware RAM. + uma_lease: Arc, published: AtomicBool, id: u32, } @@ -133,14 +136,20 @@ fn write_records( impl Allocator { /// Render allocator at per-VM VA index `k` and matching device-wide hardware slot `k`. #[allow(dead_code)] - pub(crate) fn new(o: &mut Objects, k: u64, heap: &Arc) -> Result { - Self::new_at(o, k, k as u32, heap) + pub(crate) fn new( + o: &mut Objects, + fw_factory: &Factory, + k: u64, + heap: &Arc, + ) -> Result { + Self::new_at(o, fw_factory, k, k as u32, heap) } /// Render allocator mapped at per-VM local VA index `local_idx` (`0..MAX_VM_PB_SLOTS`) /// and bound to device-wide hardware slot `hw_slot` (`parameter_id`, UMA slot /// `RENDER_UMA_SLOT + hw_slot`). pub(crate) fn new_at( o: &mut Objects, + fw_factory: &Factory, local_idx: u64, hw_slot: u32, heap: &Arc, @@ -150,9 +159,12 @@ impl Allocator { } let nc = |va| Some((va, pte::LEAF_NC)); // Native UMA software metadata is ASC-owned and never needs a client GPU alias. - // In particular its firmware pointers, +0x54 completion and +0x5c exclusion flag - // must not share a writable GPU page with the engine auxiliary records. - let descriptor = alloc(o, uma_manager::SIZE, Class::Fw, None, true)?; + // Keep descriptor + submitted in a VM-free FwLease so firmware's global UMA table + // stays mapped across closed-VM reclaim without pinning the VM's ASID or pools. + let mut fw = fw_factory.fw_objects(); + let descriptor = alloc(&mut fw, uma_manager::SIZE, Class::Fw, None, true)?; + let submitted = alloc(&mut fw, 0x40, Class::Fw, None, true)?; + let uma_lease = FwLease::new(fw)?; let auxiliary = alloc( o, 0x4000, @@ -181,7 +193,6 @@ impl Allocator { nc(client::render_list(local_idx)), true, )?; - let submitted = alloc(o, 0x40, Class::Fw, None, true)?; let heap = heap.clone(); super::slots::init_uma_pool(&state, &list, gva(&pool)?)?; descriptor.write( @@ -202,10 +213,15 @@ impl Allocator { list, submitted, heap, + uma_lease, published: AtomicBool::new(false), id: hw_slot, }) } + /// Firmware-only lease retaining this allocator's UMA descriptor and submitted counter. + pub(crate) fn uma_lease(&self) -> Arc { + self.uma_lease.clone() + } /// Device-wide hardware PB/UMA slot (`parameter_id`) owned by this allocator unit. pub(crate) fn id(&self) -> u32 { self.id @@ -302,13 +318,14 @@ pub(crate) fn alloc_pb_heap_chunk( } impl PoolSet { - pub(crate) fn new(o: &mut Objects) -> Result { - Self::new_with_slots(o, [0, 1]) + pub(crate) fn new(o: &mut Objects, fw_factory: &Factory) -> Result { + Self::new_with_slots(o, fw_factory, [0, 1]) } /// Base render allocator units mapped at per-VM local VA indices `0..BASE_PB_SLOTS` and /// bound to device-wide physical PB/UMA slots `slots`. pub(crate) fn new_with_slots( o: &mut Objects, + fw_factory: &Factory, slots: [usize; sizes::BASE_PB_SLOTS], ) -> Result { // The firmware copes with a full PB without the host (its overflow counters move and @@ -324,7 +341,7 @@ impl PoolSet { let mut units = KVec::with_capacity(sizes::BASE_PB_SLOTS, GFP_KERNEL)?; for (local, &hw_slot) in slots.iter().enumerate() { units.push( - Allocator::new_at(o, local as u64, hw_slot as u32, &heap)?, + Allocator::new_at(o, fw_factory, local as u64, hw_slot as u32, &heap)?, GFP_KERNEL, )?; } @@ -400,12 +417,21 @@ pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, owners: [Option>; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each `parameter_id`'s `pb_manager` + `counter` page mapped + /// for firmware's global `pb_mgr_table[parameter_id]` across closed-VM reclaim until a newer + /// `InitBM` retires on that exact slot. + retained_pb: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] owner_vms: [Option>; sizes::PB_SLOTS], #[allow(dead_code)] owner_arenas: [Option; sizes::PB_SLOTS], + /// VM-free firmware leases keeping each render UMA slot's `descriptor` + `submitted` page + /// mapped for firmware's global `uma_mgr_table[RENDER_UMA_SLOT + k]` across closed-VM reclaim + /// until a newer render retires on that exact slot. + retained_uma: [Option>; sizes::PB_SLOTS], pending_vms: [Option>; sizes::PB_SLOTS], pending_arenas: [Option; sizes::PB_SLOTS], + pending_uma: [Option>; sizes::PB_SLOTS], /// Per allocator slot, a binding count, bumped by each fresh epoch (its InitBM rebinds the /// slot) and by a firmware recovery. It identifies a binding without holding the epoch. binds: [u64; sizes::PB_SLOTS], @@ -429,10 +455,13 @@ impl Pools { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], owner_vms: [const { None }; sizes::PB_SLOTS], owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], pending_vms: [const { None }; sizes::PB_SLOTS], pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], binds: [0; sizes::PB_SLOTS], keep: [false; sizes::PB_SLOTS], active: None, @@ -452,10 +481,13 @@ impl Pools { dev: dev.as_ref().as_ref().into(), stats: PbStats::default(), owners: [const { None }; sizes::PB_SLOTS], + retained_pb: [const { None }; sizes::PB_SLOTS], owner_vms: [const { None }; sizes::PB_SLOTS], owner_arenas: [const { None }; sizes::PB_SLOTS], + retained_uma: [const { None }; sizes::PB_SLOTS], pending_vms: [const { None }; sizes::PB_SLOTS], pending_arenas: [const { None }; sizes::PB_SLOTS], + pending_uma: [const { None }; sizes::PB_SLOTS], binds: [0; sizes::PB_SLOTS], keep: [false; sizes::PB_SLOTS], active: None, @@ -748,7 +780,7 @@ impl Pools { pub(crate) fn exhausted_for(&self, vm: &Arc) -> bool { self.exhausted_for_within(vm, sizes::PB_SLOTS) } - /// Retains the candidate VM and owning render/recovery arena (holding the UMA descriptors) + /// Retains the candidate VM, owning render/recovery arena, and firmware UMA descriptor lease /// before publication visibility. #[allow(dead_code)] pub(crate) fn hold_alloc( @@ -756,12 +788,14 @@ impl Pools { k: usize, vm: &Arc, arena: Option, + uma_lease: Option>, ) -> Result { if k >= sizes::PB_SLOTS || self.quarantined[k] { return Err(EINVAL); } self.pending_vms[k] = Some(vm.clone()); self.pending_arenas[k] = arena; + self.pending_uma[k] = uma_lease; Ok(()) } /// Cancels unpublished candidate retention for allocator slot `k`. @@ -770,6 +804,7 @@ impl Pools { if k < sizes::PB_SLOTS { self.pending_vms[k] = None; self.pending_arenas[k] = None; + self.pending_uma[k] = None; } } /// Records a render reaching firmware visibility on allocator slot `k`. @@ -797,12 +832,16 @@ impl Pools { return Ok(()); } self.owners[k] = Some(epoch.clone()); + self.retained_pb[k] = Some(epoch.records_lease()); if let Some(vm) = self.pending_vms[k].take() { self.owner_vms[k] = Some(vm); } if let Some(arena) = self.pending_arenas[k].take() { self.owner_arenas[k] = Some(arena); } + if let Some(uma) = self.pending_uma[k].take() { + self.retained_uma[k] = Some(uma); + } self.last_clean_retired = Some(k); self.retire_epoch(k, binding, completed); Ok(()) @@ -865,9 +904,47 @@ impl Pools { *keep = false; } } + /// Releases displaced PB/UMA allocator leases owned by closed VMs while preserving active, + /// in-flight, undisplaced, and quarantined slots. Returns `true` if any non-quarantined + /// slot still holds a closed-VM lease awaiting retirement or displacement. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::PB_SLOTS { + if self.quarantined[k] { + continue; + } + let closed = self.owner_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()) + || self.owners[k] + .as_ref() + .is_some_and(|epoch| epoch._vm.vm.is_closed()) + || self.pending_vms[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !closed { + continue; + } + if self.slot_displaced(k) + && self.pending_vms[k].is_none() + && self.pending_arenas[k].is_none() + && self.pending_uma[k].is_none() + { + self.owners[k] = None; + self.owner_vms[k] = None; + self.owner_arenas[k] = None; + self.keep[k] = false; + self.binds[k] = self.binds[k].wrapping_add(1); + } else { + remaining = true; + } + } + remaining + } #[allow(dead_code)] pub(crate) fn retire_binding(&mut self, k: usize, epoch: &Arc) -> Result { *self.owners.get_mut(k).ok_or(EINVAL)? = Some(epoch.clone()); + *self.retained_pb.get_mut(k).ok_or(EINVAL)? = Some(epoch.records_lease()); Ok(()) } pub(crate) fn write_stats(&self, f: &mut impl fmt::Write) -> fmt::Result { @@ -907,6 +984,9 @@ pub(crate) struct PbEpochInner { /// so fresh `InitBM` seeding writes only the active prefix (plus any shrink tail). seeded_blocks: AtomicU32, exposed: AtomicBool, + /// VM-free firmware lease keeping `records` (`manager`, `ring`, `counter`, `misc`, `initbm`) + /// mapped across closed-VM reclaim until a newer `InitBM` overwrites `pb_mgr_table[k]`. + records_lease: Arc, // Unmap private records before releasing the VM's aliases and ASID. _objects: Objects, _vm: Arc, @@ -919,8 +999,10 @@ impl PbEpoch { vm: &Arc, permit: super::budget::Permit, ) -> Result> { + let mut fw = factory.fw_objects(); + let records = alloc(&mut fw, 0x500, Class::Fw, None, true)?; + let records_lease = FwLease::new(fw)?; let mut o = factory.objects(&vm.vm); - let records = alloc(&mut o, 0x500, Class::Fw, None, true)?; let mut inner = PbEpochInner { manager: FwObject::view(&records, 0, 0xc0)?, pages: o.alloc_dynamic_client(buffer::PAGE_LIST_SIZE)?, @@ -933,6 +1015,7 @@ impl PbEpoch { heap_blocks: AtomicU32::new(0), seeded_blocks: AtomicU32::new(0), exposed: AtomicBool::new(false), + records_lease, _objects: o, _vm: vm.clone(), _permit: permit, @@ -944,6 +1027,11 @@ impl PbEpoch { )?) } + /// Firmware-only lease retaining this epoch's `pb_manager` + `counter` page. + pub(crate) fn records_lease(&self) -> Arc { + self.records_lease.clone() + } + /// Seed only unpublished storage. A retry may choose another physical slot; after /// exposure neither the manager nor any of its firmware-mutated lists is reset. pub(crate) fn prepare(&self, k: usize, heap: u64, heap_blocks: u32) -> Result { diff --git a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs index 869e716b2b7e8..15e77396fcf7a 100644 --- a/drivers/gpu/drm/asahi/g16/pools/lifetime.rs +++ b/drivers/gpu/drm/asahi/g16/pools/lifetime.rs @@ -122,6 +122,12 @@ impl Lifetime { pub(crate) fn any_quarantined_within(&self, n: usize) -> bool { (0..n.min(N)).any(|k| self.units[k].state == State::Quarantined) } + /// Whether owner `k` is permanently quarantined. + pub(crate) fn is_quarantined(&self, k: usize) -> bool { + self.units + .get(k) + .is_some_and(|u| u.state == State::Quarantined) + } pub(crate) fn claim(&mut self, k: usize) -> bool { if !self.available(k) { return false; diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index aad844d07e73e..271b3867da424 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -64,7 +64,10 @@ impl ComputeArena { let mut objects = factory.objects(vm); let mut compute = KVec::with_capacity(units.len(), GFP_KERNEL)?; for k in units { - compute.push(ComputeSlot::new(&mut objects, k as u64)?, GFP_KERNEL)?; + compute.push( + ComputeSlot::new(&mut objects, factory, k as u64)?, + GFP_KERNEL, + )?; } objects.finish_private()?; Ok(Arc::new( @@ -301,7 +304,7 @@ impl RenderArena { for k in 0..BASE_RENDER_SLOTS { passes.push(PassSlot::new(&mut objects, k as u64, 1)?, GFP_KERNEL)?; } - let pools = PoolSet::new_with_slots(&mut objects, base_pb_slots)?; + let pools = PoolSet::new_with_slots(&mut objects, factory, base_pb_slots)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(RenderInner { @@ -425,8 +428,13 @@ impl PoolExtArena { heap: &Arc, ) -> Result> { let mut objects = factory.objects(vm); - let allocator = - super::pools::Allocator::new_at(&mut objects, local_idx as u64, hw_slot as u32, heap)?; + let allocator = super::pools::Allocator::new_at( + &mut objects, + factory, + local_idx as u64, + hw_slot as u32, + heap, + )?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(PoolExtInner { @@ -1196,6 +1204,13 @@ impl Prepared { .map(|ext| PbOwnerArena::Ext(base.clone(), ext.clone(), heap_ext)) } } + /// VM-free firmware lease keeping PB/UMA allocator slot `k`'s `descriptor` + `submitted` + /// pages mapped in context-0 UAT across closed-VM reclaim. + pub(crate) fn pb_uma_lease(&self, k: usize) -> Option> { + self.pb_allocator(k) + .ok() + .map(super::pools::Allocator::uma_lease) + } fn render_ext_for(&self, k: usize) -> Option<(&Arc, usize)> { for tier in self.render_ext.iter().take_while(|t| t.is_some()).flatten() { if let Some(idx) = k.checked_sub(tier.start) { diff --git a/drivers/gpu/drm/asahi/g16/slots.rs b/drivers/gpu/drm/asahi/g16/slots.rs index 900d25b725e0d..aa3d445a12bd8 100644 --- a/drivers/gpu/drm/asahi/g16/slots.rs +++ b/drivers/gpu/drm/asahi/g16/slots.rs @@ -15,7 +15,7 @@ use super::encode::{Geometry, PassRefs}; use super::fw::work::{barrier, fs, ta}; use super::graph::{alloc, alloc_work, cmd_fw, Client}; use super::hw::{client, sizes}; -use super::object::{Class, FwObject, Objects}; +use super::object::{Class, Factory, FwLease, FwObject, Objects}; use super::pools::lifetime::Lifetime; /// One immutable allocation set. Mutable firmware pool cursors survive successful reuse. @@ -32,6 +32,10 @@ pub(crate) struct ComputeSlot { pub(crate) counter: Arc, pub(crate) context_store: Arc, pub(crate) aux: Arc, + /// VM-free firmware lease keeping `work` (containing the compute UMA manager at `+0xe00`) + /// and `counter` mapped in context-0 UAT until a later compute retirement overwrites + /// firmware `uma_mgr_table[1 + k]`. + uma_lease: Arc, } /// Initializes the private pool exactly once, before it is exposed. Never called on reuse. @@ -54,8 +58,12 @@ pub(crate) fn init_uma_pool(state: &FwObject, list: &FwObject, pool: u64) -> Res } impl ComputeSlot { - pub(crate) fn new(o: &mut Objects, k: u64) -> Result { + pub(crate) fn new(o: &mut Objects, fw_factory: &Factory, k: u64) -> Result { let sh = Class::Shared; + let mut fw = fw_factory.fw_objects(); + let work = alloc_work(&mut fw, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?; + let counter = alloc(&mut fw, 0x80, sh, None, 0, false)?; + let uma_lease = FwLease::new(fw)?; let unit = Self { its: alloc(o, 16, sh, None, 0, false)?, preempt: alloc( @@ -66,7 +74,7 @@ impl ComputeSlot { 0, false, )?, - work: alloc_work(o, 0x2000, client::WORK_PAGE + k * client::CWORK_STRIDE, 0)?, + work, seq: alloc(o, 0x300, cmd_fw(), None, 0, false)?, // Holds fs2c (+0x00) and cross-pipe c2c (+0x40) barriers within one page. barrier: alloc( @@ -95,7 +103,7 @@ impl ComputeSlot { false, )?, page_list: alloc(o, 0x4000, sh, Client::nc(client::compute_list(k)), 0, false)?, - counter: alloc(o, 0x80, sh, None, 0, false)?, + counter, context_store: alloc( o, 0x40000, @@ -105,6 +113,7 @@ impl ComputeSlot { false, )?, aux: alloc(o, 0x4000, sh, Client::nc(client::compute_aux(k)), 0, false)?, + uma_lease, }; init_uma_pool( &unit.pool_state, @@ -113,6 +122,10 @@ impl ComputeSlot { )?; Ok(unit) } + /// VM-free firmware lease keeping this unit's `work` and `counter` mapped in context-0 UAT. + pub(crate) fn uma_lease(&self) -> Arc { + self.uma_lease.clone() + } /// Resets command-local state before reuse. Pool/list/counter/descriptor state is preserved. /// /// Clean same-VM reuse only zeroes the 16-byte internal timestamp pair so retirement @@ -461,6 +474,11 @@ pub(crate) struct ComputeOwners { /// descriptor when a later owner displaces it, after its VM's client closed. arena: [Option>; sizes::COMPUTE_UNITS], pending_arena: [Option>; sizes::COMPUTE_UNITS], + /// VM-free firmware leases keeping each hardware slot's `work` + `counter` mapped in + /// context-0 UAT across closed-VM reclaim until a later compute retirement overwrites + /// firmware `uma_mgr_table[1 + k]`. + retained_uma: [Option>; sizes::COMPUTE_UNITS], + pending_uma: [Option>; sizes::COMPUTE_UNITS], /// Force a full scrub on next claim (first use, cancel, error, or firmware recovery). scrub_full: [bool; sizes::COMPUTE_UNITS], /// Whether the most recent claim of each compute unit required a full scrub/work write. @@ -737,6 +755,8 @@ impl Slots { pending_owner: [const { None }; sizes::COMPUTE_UNITS], arena: [const { None }; sizes::COMPUTE_UNITS], pending_arena: [const { None }; sizes::COMPUTE_UNITS], + retained_uma: [const { None }; sizes::COMPUTE_UNITS], + pending_uma: [const { None }; sizes::COMPUTE_UNITS], scrub_full: [true; sizes::COMPUTE_UNITS], last_full: [true; sizes::COMPUTE_UNITS], }), @@ -893,6 +913,9 @@ impl Slots { || self.render.scrub_full[k] || self.scrub.is_scrubbing(k) || self.scrub.is_clean(k) + || self.render.owner[k] + .as_ref() + .is_none_or(|vm| vm.vm.is_closed()) { continue; } @@ -932,6 +955,78 @@ impl Slots { } self.take_staged_scrubs() } + /// Releases displaced compute-unit and render-pass leases owned by closed VMs while + /// preserving active, in-flight, undisplaced, scrubbing, and quarantined slots. + /// + /// Returns `true` if any non-quarantined slot still holds a closed-VM lease awaiting + /// retirement, displacement, or an in-progress off-lock pass scrub. + pub(crate) fn reclaim_closed(&mut self) -> bool { + let mut remaining = false; + for k in 0..sizes::COMPUTE_UNITS { + if self.compute.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.compute.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.compute.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + if owner_closed + && self.compute.lifetime.available(k) + && self.compute.pending_owner[k].is_none() + && self.compute.pending_arena[k].is_none() + && self.compute.pending_uma[k].is_none() + { + self.compute.owner[k] = None; + self.compute.arena[k] = None; + self.compute.scrub_full[k] = true; + self.compute.last_full[k] = true; + } else { + remaining = true; + } + } + for k in 0..sizes::RENDER_SLOTS { + if self.render.lifetime.is_quarantined(k) { + continue; + } + let owner_closed = self.render.owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + let pending_closed = self.render.pending_owner[k] + .as_ref() + .is_some_and(|vm| vm.vm.is_closed()); + if !owner_closed && !pending_closed { + continue; + } + let bit = 1u64 << k; + if owner_closed + && self.pass_busy & bit == 0 + && self.render.lifetime.available(k) + && self.render.pending_owner[k].is_none() + && self.render.pending_arena[k].is_none() + { + if self.scrub.is_scrubbing(k) { + self.scrub.waiter.store(true, Ordering::SeqCst); + } + if !self.scrub.is_scrubbing(k) { + self.render.owner[k] = None; + self.render.arena[k] = None; + self.render.scrub_full[k] = true; + self.render.last_full[k] = true; + self.scrub.clear_clean(k); + } else { + remaining = true; + } + } else { + remaining = true; + } + } + remaining + } /// Compute units published and not yet retired. pub(crate) fn compute_published(&self) -> u32 { self.compute.lifetime.published() @@ -1436,6 +1531,7 @@ impl Slots { .and_then(|old| Self::vm_retarget(k, old, vm)); self.compute.pending_owner[k] = Some(vm.clone()); self.compute.pending_arena[k] = resources.compute_arena(k); + self.compute.pending_uma[k] = resources.compute_unit(k).ok().map(ComputeSlot::uma_lease); Ok(()) } @@ -1557,6 +1653,12 @@ impl Slots { if let Some(cell) = self.compute.pending_arena.get_mut(k as usize) { *cell = resources.compute_arena(k as usize); } + if let Some(cell) = self.compute.pending_uma.get_mut(k as usize) { + *cell = resources + .compute_unit(k as usize) + .ok() + .map(ComputeSlot::uma_lease); + } } let mut mask = f.pass_mask & PASS_MASK; while mask != 0 { @@ -1635,6 +1737,9 @@ impl Slots { for &k in &f.slot[..f.slot_count as usize] { self.compute.owner[k as usize] = self.compute.pending_owner[k as usize].take(); self.compute.arena[k as usize] = self.compute.pending_arena[k as usize].take(); + if let Some(lease) = self.compute.pending_uma[k as usize].take() { + self.compute.retained_uma[k as usize] = Some(lease); + } if clean_scrub { self.compute.scrub_full[k as usize] = false; } @@ -1686,6 +1791,7 @@ impl Slots { self.compute.pending_retarget[k as usize] = None; self.compute.pending_owner[k as usize] = None; self.compute.pending_arena[k as usize] = None; + self.compute.pending_uma[k as usize] = None; self.compute.scrub_full[k as usize] = true; } let mut mask = f.pass_mask & PASS_MASK; 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 5a7a7b3e5ba36..03099634f7b6c 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 @@ -213,6 +213,7 @@ def item(declaration, text=source): sleeping: AtomicBool, evented: AtomicBool, publish_wake: AtomicBool, + closed_vm_reclaim: AtomicBool, rearmed: Cell, idle_power_polls: Cell, rearm_soon: Cell, @@ -224,6 +225,7 @@ def item(declaration, text=source): sleeping: AtomicBool::new(false), evented: AtomicBool::new(false), publish_wake: AtomicBool::new(false), + closed_vm_reclaim: AtomicBool::new(false), rearmed: Cell::new(0), idle_power_polls: Cell::new(0), rearm_soon: Cell::new(0), @@ -262,14 +264,32 @@ def item(declaration, text=source): } } +#[derive(Default)] +struct Pools { + reclaim_calls: u32, + reclaim_remaining: bool, +} +impl Pools { + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } +} + #[derive(Default)] struct Slots { scrub_woke: AtomicBool, + reclaim_calls: u32, + reclaim_remaining: bool, } impl Slots { fn take_scrub_woke(&self) -> bool { self.scrub_woke.swap(false, Ordering::AcqRel) } + fn reclaim_closed(&mut self) -> bool { + self.reclaim_calls += 1; + self.reclaim_remaining + } } struct Firmware { @@ -280,6 +300,7 @@ def item(declaration, text=source): events: Events, recovery: Recovery, power: Power, + pools: Pools, slots: Slots, last_housekeeping_ns: u64, last_aux_drain_ns: u64, @@ -333,6 +354,7 @@ def item(declaration, text=source): events: Events::default(), recovery: Recovery::default(), power: Power::default(), + pools: Pools::default(), slots: Slots::default(), last_housekeeping_ns: 0, last_aux_drain_ns: 0, @@ -410,12 +432,57 @@ def item(declaration, text=source): self.ta_pending } + __RECLAIM_CLOSED_VM_SLOTS__ __POLL_STEP__ __OLDEST_TERMINAL_EVENTS__ __TA_WAVE_READY__ __OLDEST_STAMP_REACHED__ } +#[test] +fn idle_poll_step_reclaims_closed_vm_slots_and_rearms_while_remaining() { + CLOCK.with(|c| c.set(1_000_000)); + let shared = Shared::new(); + let mut fw = Firmware::new(); + fw.engine.shared = Some(shared.clone()); + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared.publish_wake.store(true, Ordering::Release); + fw.pools.reclaim_remaining = true; + + let (mut retry_tail, mut hk_deferred, mut done) = (false, false, vec![]); + let busy = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert!(!busy); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (1, 1)); + assert!(!shared.publish_wake.load(Ordering::Acquire)); + assert!( + shared.closed_vm_reclaim.load(Ordering::Acquire), + "remaining undisplaced closed VM keeps reclaim armed" + ); + + // Once remaining clears, idle poll clears closed_vm_reclaim and later polls skip scans. + fw.pools.reclaim_remaining = false; + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); + + let _ = fw + .poll_step(false, 0, &mut retry_tail, &mut hk_deferred, &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (2, 2)); + + // Idle submit_locked also reclaims before publish_checked when armed. + shared.closed_vm_reclaim.store(true, Ordering::Release); + shared + .submit_locked(&mut fw, Arc::new(Job { id: 9 }), &mut done) + .unwrap(); + assert_eq!((fw.pools.reclaim_calls, fw.slots.reclaim_calls), (3, 3)); + assert!(!shared.closed_vm_reclaim.load(Ordering::Acquire)); +} + #[test] fn submit_locked_retires_inline_on_reached_stamp_without_full_housekeeping() { CLOCK.with(|c| c.set(100_000)); @@ -1501,6 +1568,7 @@ def item(declaration, text=source): for token, decl in { '__SUBMIT_LOCKED__': 'fn submit_locked(', + '__RECLAIM_CLOSED_VM_SLOTS__': 'pub(crate) fn reclaim_closed_vm_slots(', '__POLL_STEP__': 'pub(crate) fn poll_step(', '__RUN_HOUSEKEEPING__': 'pub(crate) fn run_housekeeping(', '__OLDEST_TERMINAL_EVENTS__': 'fn oldest_terminal_events(', @@ -1537,7 +1605,7 @@ def item(declaration, text=source): json.dumps( { 'passed': True, - 'tests': 21, + 'tests': 22, 'cpu_only': True, 'hardware_execution': False, 'scope': 'Verbatim production submit_locked inline retirement and poll_step TA-only non-spin logic.', 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 860e6f89d8240..efbe9e2b7a2f3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -107,15 +107,26 @@ def module(text, name): pub fn r32(&self,o:usize)->Result{let d=self.data.lock().unwrap();Ok(u32::from_le_bytes(d[self.offset+o..self.offset+o+4].try_into().unwrap()))} pub fn snapshot(&self)->Vec{self.data.lock().unwrap().clone()} } + pub struct FwLease(pub crate::cleanup::Deferred); + impl FwLease { + pub fn new(mut objects: Objects) -> Result> { + objects.finish_private()?; + Arc::new(Self(crate::cleanup::Deferred::new(objects)?), 0) + } + } pub struct Factory; - impl Factory{pub fn objects(&self,_:&())->Objects{Objects::new()}} + impl Factory{ + pub fn objects(&self,_:&super::vm::MockVm)->Objects{Objects::new()} + pub fn fw_objects(&self)->Objects{Objects::new()} + } + pub static NEXT_VA: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0xfffffc2001000000); std::thread_local!{pub static ALL_OBJECTS:std::cell::RefCell>>=const{std::cell::RefCell::new(Vec::new())};} - pub struct Objects{pub objects:Vec>,next:u64} + pub struct Objects{pub objects:Vec>} impl Objects{ - pub fn new()->Self{Self{objects:vec![],next:0xfffffc2001000000}} + pub fn new()->Self{Self{objects:vec![]}} pub fn finish_private(&mut self)->Result{Ok(())} pub fn alloc_dynamic_client(&mut self,size:usize)->Result>{self.alloc(Request{size,class:Class::Shared,placement:Placement::Anywhere,offset:0,client:Some((0x7040000000,super::hw::pte::LEAF_NC)),lower:None,cpu:true})} - pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=self.next;self.next+=bytes as u64+0x4000;let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} + pub fn alloc(&mut self,r:Request)->Result>{let bytes=(r.size+r.offset+0x3fff)&!0x3fff;let va=NEXT_VA.fetch_add(bytes as u64+0x4000,std::sync::atomic::Ordering::Relaxed);let x=Arc::new(FwObject{class:r.class,client_leaf:r.client.map(|c|c.1),va:va+r.offset as u64,gva:r.client.map(|c|c.0+r.offset as u64),lower_gva:r.lower.map(|g|g+r.offset as u64),lower_leaf:r.lower.map(|_|super::hw::pte::LOWER),size:r.size,mapped:bytes,offset:r.offset,data:std::sync::Arc::new(std::sync::Mutex::new(if r.cpu{vec![0;bytes]}else{vec![]})),fills:std::sync::Mutex::new(Vec::new()),fail_fill:std::sync::atomic::AtomicBool::new(false),write_bytes:std::sync::atomic::AtomicUsize::new(0)},0)?;self.objects.push(x.clone());ALL_OBJECTS.with(|a|a.borrow_mut().push(x.clone()));Ok(x)} } } pub mod graph { @@ -140,8 +151,15 @@ def module(text, name): pub struct PassRefs{pub ta_work:u64,pub ta_work_gva:u64,pub fs_work:u64,pub fs_work_gva:u64,pub ta_seq:u64,pub fs_seq:u64,pub scene:u64,pub tpc_gva:u64,pub tilemap_gva:u64,pub heap_gva:u64,pub scene_user_gva:u64,pub scene_list:u64,pub pre_gva:[u64;3],pub fs_scratch_gva:u64,pub aux_gva:u64,pub its:u64,pub ta_scratch:u64,pub tpc_fw:u64,pub scratch_fw:u64} } pub mod vm { - use crate::{mmu,sync::Arc};use core::sync::atomic::Ordering; - pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:()} + use crate::{mmu,sync::Arc}; + use core::sync::atomic::{AtomicBool,Ordering}; + pub struct MockVm(AtomicBool); + impl MockVm{ + pub fn new()->Self{Self(AtomicBool::new(false))} + pub fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)} + pub fn close(&self){self.0.store(true,Ordering::Release);} + } + pub struct VmState{pub id:u64,pub slot:u32,pub generation:u8,pub vm:MockVm} struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ @@ -171,10 +189,17 @@ def module(text, name): match self{Self::Base(a)=>Some((a.passes.get(k)?,PassDirty{tpc:a.tpc_dirty.get(k)?,tilemap:a.tilemap_dirty.get(k)?,tilemap_last:a.tilemap_last.get(k)?,tilemap_clean:a.tilemap_clean.get(k)?,heap:a.heap_dirty.get(k)?}))} } } + std::thread_local!{ + pub static COMPUTE_OWNER_ARENA:std::cell::RefCell< + Option>, + >=const{std::cell::RefCell::new(None)}; + } impl ComputeArena{ pub fn compute_units(&self)->Result{Ok(self.compute.len())} pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{self.compute.get(k).ok_or(EINVAL)} - pub fn compute_arena(&self,_k:usize)->Option>{None} + pub fn compute_arena(&self,_k:usize)->Option>{ + COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone()) + } pub fn render_arena(&self)->Option>{self.render.clone()} pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} pub fn render_pass(&self,k:usize)->Result<&super::slots::PassSlot>{self.render.as_deref().and_then(|r|r.passes.get(k)).ok_or(EINVAL)} @@ -218,9 +243,13 @@ def module(text, name): heap_dirty:[const{std::sync::atomic::AtomicU64::new(0)};g16::hw::sizes::RENDER_SLOTS], } } + fn find_va(va:u64)->sync::Arc{ + g16::object::ALL_OBJECTS.with(|a|a.borrow().iter().find(|obj|obj.va==va).unwrap().clone()) + } fn arenas(o:&mut Objects)->Arenas{ let mut compute=KVec::new();let mut passes=KVec::new(); - for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} + let f=g16::object::Factory; + for k in 0..2{compute.push(g16::slots::ComputeSlot::new(o,&f,k).unwrap(),0).unwrap();passes.push(g16::slots::PassSlot::new(o,k,1).unwrap(),0).unwrap();} Arenas{compute:g16::resources::ComputeArena{compute,render:None},render:render_arena(passes)} } fn retire_render(s:&mut Slots,k:usize){let mut c=Claims::new();c.pass[0]=k as u32;c.pass_mask=1<=0x7000000000);assert!(base+a.mapped as u64<=0x7100000000);aliases.push((base,base+a.mapped as u64));}} aliases.push((0x1000000000,0x1000010000)); // Per-VM context store. @@ -315,11 +344,11 @@ def module(text, name): } } #[test]fn allocator_metadata_is_firmware_only_and_shared_state_keeps_real_backing(){ - let mut o=Objects::new();let pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let read64=|obj:&g16::object::FwObject,at:usize|->u64{obj.r32(at).unwrap()as u64|((obj.r32(at+4).unwrap()as u64)<<32)}; for k in 0..2 { let refs=pools.allocator_refs_for(k).unwrap(); - let descriptor=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let descriptor=find_va(refs.uma_mgr[0]); let auxiliary=o.objects.iter().find(|obj|obj.va+0x100==refs.uma_aux[0]).unwrap(); assert_eq!(descriptor.class,g16::object::Class::Fw); assert_eq!(descriptor.gva,None);assert_eq!(descriptor.client_leaf,None); @@ -342,8 +371,8 @@ def module(text, name): } assert_eq!(metadata,descriptor.snapshot()); // Freelist and pool-table pointers still select writable client mappings. - let state_va=read64(descriptor,g16::fw::graph::manager::FREELIST); - let list_va=read64(descriptor,g16::fw::graph::manager::POOL_TABLE); + let state_va=read64(&descriptor,g16::fw::graph::manager::FREELIST); + let list_va=read64(&descriptor,g16::fw::graph::manager::POOL_TABLE); for va in [list_va,state_va] { let shared=o.objects.iter().find(|obj|obj.gva==Some(va)).unwrap(); assert_eq!(shared.class,g16::object::Class::Shared); @@ -369,11 +398,11 @@ def module(text, name): s.publish(&mut c).unwrap();s.quarantine(&mut c);assert!(s.compute_exhausted()); } #[test]fn production_render_descriptors_preserve_firmware_bytes_and_exact_counter(){ - let mut o=Objects::new();let mut pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let mut pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let a=pools.prepare(0,1).unwrap();assert!(a.init_buffer);assert_eq!(a.uma_submitted,2); assert!(!pools.retired(0).unwrap());pools.publish_batch(0,2,1).unwrap(); assert!(pools.publish_batch(0,2,1).is_err());assert!(pools.prepare(0,2).is_err()); - let d=o.objects.iter().find(|o|o.va==a.uma_mgr[0]).unwrap(); + let d=find_va(a.uma_mgr[0]); d.w64(0x54,2).unwrap();d.w64(0x60,0x5a5aa5a5).unwrap(); let original=d.snapshot();assert!(pools.retired(0).unwrap()); let next=pools.prepare(0,2).unwrap();assert!(next.init_buffer);assert_eq!(next.uma_submitted,4); @@ -382,9 +411,15 @@ def module(text, name): #[test]fn cross_vm_evidence_counts_only_noted_publication(){ let mut o=Objects::new();let mut s=Slots::new().unwrap();let arena=arenas(&mut o); - let a=sync::Arc::new(g16::vm::VmState{id:100,slot:1,generation:1,vm:()},0).unwrap(); - let b=sync::Arc::new(g16::vm::VmState{id:101,slot:2,generation:1,vm:()},0).unwrap(); - let c=sync::Arc::new(g16::vm::VmState{id:102,slot:3,generation:9,vm:()},0).unwrap(); + let a=sync::Arc::new( + g16::vm::VmState{id:100,slot:1,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let b=sync::Arc::new( + g16::vm::VmState{id:101,slot:2,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap(); + let c=sync::Arc::new( + g16::vm::VmState{id:102,slot:3,generation:9,vm:g16::vm::MockVm::new()},0, + ).unwrap(); let mut claims=Claims::new(); for vm in [&a,&b]{s.claim_compute(&arena.compute,&mut claims,0).unwrap().unwrap();s.hold_vm(&claims,vm).unwrap();s.publish(&mut claims).unwrap();s.note_published(&claims);s.retire(&mut claims).unwrap();} assert_eq!(s.stats.cross_vm_retargets,[0,0]); @@ -401,7 +436,11 @@ def module(text, name): s.release(&mut claims);s.note_published(&claims);assert_eq!(s.stats.cross_vm_retargets,[1,0]); } - fn vm(id:u64)->sync::Arc{sync::Arc::new(g16::vm::VmState{id,slot:id as u32,generation:1,vm:()},0).unwrap()} + fn vm(id:u64)->sync::Arc{ + sync::Arc::new( + g16::vm::VmState{id,slot:id as u32,generation:1,vm:g16::vm::MockVm::new()},0, + ).unwrap() + } #[test]fn previous_vm_lease_survives_replacement_publication_until_full_retirement(){ let mut o=Objects::new();let arena=arenas(&mut o);let mut s=Slots::new().unwrap(); let a=vm(1);let b=vm(2);let c=vm(3);let mut claims=Claims::new(); @@ -605,15 +644,15 @@ def module(text, name): assert_eq!(g16::hw::sizes::RENDER_SLOTS, 48); assert_eq!(g16::hw::sizes::COMPUTE_UNITS, 24); let mut o=Objects::new(); - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); for idx in 0..g16::hw::sizes::EXT_PB_SLOTS { let local=(g16::hw::sizes::BASE_PB_SLOTS+idx) as u64; let hw_slot=(g16::hw::sizes::WARM_PB_SLOTS+idx) as u32; - let ext=g16::pools::Allocator::new_at(&mut o,local,hw_slot,pools.heap()).unwrap(); + let ext=g16::pools::Allocator::new_at(&mut o,&g16::object::Factory,local,hw_slot,pools.heap()).unwrap(); 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,k).unwrap(); + g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(); } let mut scene_lists=Vec::new(); let count_client=|objs:&Objects|objs.objects.iter().filter(|a|a.gva.is_some()).count(); @@ -655,7 +694,7 @@ def module(text, name): } #[test]fn decoupled_pb_allocator_supports_same_vm_pipelining_cross_vm_displacement_and_abort(){ - let mut o=Objects::new();let pools=PoolSet::new(&mut o).unwrap(); + let mut o=Objects::new();let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); let vm1=vm(1);let vm2=vm(2);let factory=g16::object::Factory;let budget=g16::budget::Budget::new().unwrap(); let e1=g16::pools::PbEpoch::new(&factory,&vm1,g16::budget::Budget::reserve(&budget,1).unwrap().take().unwrap()).unwrap(); e1.prepare(0,0x70c0000000,2048).unwrap();e1.check_assignment(0).unwrap();e1.expose(); @@ -668,7 +707,7 @@ def module(text, name): let a1=pools.prepare_in_flight(0,1,false).unwrap(); assert_eq!(a1.uma_submitted,2); pools.publish_batch(0,2,1).unwrap();p.publish_flight(0); - let d0=o.objects.iter().find(|obj|obj.va==a1.uma_mgr[0]).unwrap(); + let d0=find_va(a1.uma_mgr[0]); d0.w64(0x54,2).unwrap(); p.retire_flight(0,&e1,b1,true).unwrap(); // Same-VM pipelining: 3 concurrent renders share slot 0 with cumulative uma_submitted (4, 6, 8). @@ -705,12 +744,14 @@ def module(text, name): #[test]fn render_allocators_use_distinct_uma_slots_within_firmware_window(){ let mut o=Objects::new(); - let pools=PoolSet::new_with_slots(&mut o,[7,8]).unwrap(); + let f=g16::object::Factory; + let pools=PoolSet::new_with_slots(&mut o,&f,[7,8]).unwrap(); assert_eq!(pools.unit(0).unwrap().id(),7); assert_eq!(pools.unit(1).unwrap().id(),8); assert_eq!( g16::pools::Allocator::new_at( &mut o, + &f, g16::hw::sizes::MAX_VM_PB_SLOTS as u64, 0, pools.heap() @@ -720,6 +761,7 @@ def module(text, name): assert_eq!( g16::pools::Allocator::new_at( &mut o, + &f, 0, g16::hw::sizes::PB_SLOTS as u32, pools.heap() @@ -729,10 +771,10 @@ def module(text, name): let mut uma_slots=Vec::new(); for k in 0..g16::hw::sizes::PB_SLOTS { let local=(k % g16::hw::sizes::MAX_VM_PB_SLOTS) as u64; - let alloc=g16::pools::Allocator::new_at(&mut o,local,k as u32,pools.heap()).unwrap(); + let alloc=g16::pools::Allocator::new_at(&mut o,&f,local,k as u32,pools.heap()).unwrap(); let refs=alloc.prepare_in_flight(1,false).unwrap(); assert_eq!(refs.parameter_id,k as u32); - let desc=o.objects.iter().find(|obj|obj.va==refs.uma_mgr[0]).unwrap(); + let desc=find_va(refs.uma_mgr[0]); let slot_id=desc.r32(8).unwrap(); let expected=g16::hw::engine::RENDER_UMA_SLOT+k as u32; assert_eq!(slot_id,expected); @@ -1151,10 +1193,12 @@ def module(text, name): let mut o=Objects::new(); let mut units=KVec::new(); for k in 0..hw::sizes::COMPUTE_UNITS { - units.push(ComputeSlot::new(&mut o,k as u64).unwrap(),0).unwrap(); + units.push(ComputeSlot::new(&mut o,&g16::object::Factory,k as u64).unwrap(),0).unwrap(); } let prep=ComputeArena{compute:units,render:None}; - let a=Arc::new(vm::VmState{id:1,slot:1,generation:1,vm:()},0).unwrap(); + let a=Arc::new( + vm::VmState{id:1,slot:1,generation:1,vm:vm::MockVm::new()},0, + ).unwrap(); let mut s=Slots::new().unwrap(); assert_eq!(s.free_compute_in(hw::sizes::COMPUTE_UNITS),hw::sizes::COMPUTE_UNITS as u32); // Claim 4 units into one Claims for a compute horizon, publish, and retire in order. @@ -1237,7 +1281,7 @@ def module(text, name): s.release(&mut cancel2); // PoolSet::publish_batch advances submitted by 2 * renders and rejects invalid deltas. - let pools=PoolSet::new(&mut o).unwrap(); + let pools=PoolSet::new(&mut o,&g16::object::Factory).unwrap(); assert_eq!(pools.publish_batch(0,0,0),Err(EINVAL)); assert_eq!(pools.publish_batch(0,4,3),Err(EINVAL)); assert_eq!(pools.publish_batch(0,6,3),Ok(())); @@ -1417,7 +1461,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut units=KVec::new(); for k in 0..4u64 { - units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep_full=g16::resources::ComputeArena{compute:units,render:None}; let a=vm(1);let b=vm(2); @@ -1444,7 +1488,7 @@ def module(text, name): // A base-only (2-unit) VM can now claim displaced base unit 0 again. let mut base_units=KVec::new(); for k in 0..2u64 { - base_units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; assert_eq!(s.claim_compute_for(&prep_base,&mut c,Some(b.id)).unwrap(),Some(0)); @@ -1455,7 +1499,7 @@ def module(text, name): let mut o=Objects::new();let mut s=Slots::new().unwrap(); let mut units=KVec::new(); for k in 0..4u64 { - units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep=g16::resources::ComputeArena{compute:units,render:None}; let a=vm(1);let b=vm(2); @@ -1492,7 +1536,7 @@ def module(text, name): // reclaims displaced extension unit 2 on the 4-unit VM without touching base units 0..2. let mut base_units=KVec::new(); for k in 0..2u64 { - base_units.push(g16::slots::ComputeSlot::new(&mut o,k).unwrap(),0).unwrap(); + base_units.push(g16::slots::ComputeSlot::new(&mut o,&g16::object::Factory,k).unwrap(),0).unwrap(); } let prep_base=g16::resources::ComputeArena{compute:base_units,render:None}; let mut c0c=Claims::new(); @@ -1788,7 +1832,7 @@ def module(text, name): let mut s = Slots::new().unwrap(); let mut units = KVec::new(); for k in 0..g16::hw::sizes::COMPUTE_UNITS as u64 { - units.push(g16::slots::ComputeSlot::new(&mut o, k).unwrap(), 0).unwrap(); + units.push(g16::slots::ComputeSlot::new(&mut o, &g16::object::Factory, k).unwrap(), 0).unwrap(); } let prep = g16::resources::ComputeArena { compute: units, render: None }; let vms = [vm(1), vm(2), vm(3), vm(4)]; @@ -2021,6 +2065,370 @@ def module(text, name): assert_eq!(page_obj.r32(1023 * 4 * 4).unwrap(), 0); assert_eq!(block_obj.r32(1023 * 8).unwrap(), 0); } + + #[test]fn closed_vms_reclaim_displaced_pb_render_and_compute_slots(){ + use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; + use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; + use g16::slots::{ComputeSlot, PassSlot}; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); + } + let mut passes = KVec::new(); + for k in 0..18 { + passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let shared_prep_compute = ComputeArena { compute: compute_slots, render: None }; + let geo = g16::encode::Geometry { tpc_bytes: 0x1000, tilemap_bytes: 0x2000 }; + + let mut vms = Vec::new(); + let mut epochs = Vec::new(); + let mut pb_arenas = Vec::new(); + let mut pass_arenas = Vec::new(); + let mut comp_arenas = Vec::new(); + + // Bind and retire 16 VMs across warm PB slots, render passes, and compute units. + for i in 0..WARM_PB_SLOTS { + let v = vm(400 + i as u64); + let pb_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let mut r_passes = KVec::new(); + for k in 0..18 { + r_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let r_arena = sync::Arc::new(render_arena(r_passes), 0).unwrap(); + let r_prep = ComputeArena { compute: KVec::new(), render: Some(r_arena.clone()) }; + let c_arena = sync::Arc::new( + ComputeArena { compute: KVec::new(), render: None }, 0, + ).unwrap(); + + // 1) PB slot i + let pb_slot = i; + let e = g16::pools::PbEpoch::new( + &factory, + &v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(pb_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(pb_slot, false); + p.hold_alloc(pb_slot, &v, Some(PbOwnerArena::Base(pb_arena.clone())), None).unwrap(); + p.publish_flight(pb_slot); + p.retire_flight(pb_slot, &e, b, true).unwrap(); + + // 2) Render pass slot i + let pk = s.pick_pass_in_for(&r_prep, &geo, 0, Some(v.id)).unwrap(); + s.claim_pass_in(&r_prep, pk, Some(v.id), geo.tilemap_bytes).unwrap(); + let mut rc = Claims::new(); + rc.pass[0] = pk as u32; + rc.pass_count = 1; + rc.pass_mask = 1u64 << pk; + s.hold_render_pass(pk, &v, &r_prep).unwrap(); + s.publish(&mut rc).unwrap(); + s.retire(&mut rc).unwrap(); + + // 3) Compute unit i + let mut cc = Claims::new(); + let ck = s + .claim_compute_for(&shared_prep_compute, &mut cc, Some(v.id)) + .unwrap() + .unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena.clone())); + s.hold_compute_slot(ck, &v, &shared_prep_compute).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc).unwrap(); + s.retire(&mut cc).unwrap(); + + vms.push(v); + epochs.push(e); + pb_arenas.push(pb_arena); + pass_arenas.push(r_arena); + comp_arenas.push(c_arena); + } + + // Live VMs stay pinned and reusable across reclaim_closed(). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + for i in 0..WARM_PB_SLOTS { + assert!(sync::Arc::strong_count(&pb_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&pass_arenas[i]) > 1); + assert!(sync::Arc::strong_count(&comp_arenas[i]) > 1); + assert!(p.reusable(i, &vms[i]).is_some()); + } + + // Close all VMs: displaced slots 0..15 reclaim immediately; last (15) stays undisplaced. + for v in &vms { + v.vm.close(); + } + assert!(p.reclaim_closed(), "undisplaced last PB slot remains"); + assert!(s.reclaim_closed(), "undisplaced last render/compute slot remain"); + // Displaced pass scrubs must skip closed VMs. + s.stage_displaced_pass_scrubs(); + assert!(!s.scrubbing_active()); + + let last = WARM_PB_SLOTS - 1; + for i in 0..last { + assert_eq!(sync::Arc::strong_count(&pb_arenas[i]), 1, "PB arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "PB epoch {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&pass_arenas[i]), 1, "pass arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&comp_arenas[i]), 1, "compute arena {i} reclaimed"); + assert_eq!(sync::Arc::strong_count(&vms[i]), 2); + } + // Final undisplaced slot stays protected until displaced. + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 2); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 2); + + // Live VM runs 1 render + 1 compute, displacing slot 15 everywhere. + let live = vm(500); + let live_r_arena = sync::Arc::new(render_arena(passes), 0).unwrap(); + let live_r_prep = ComputeArena { compute: KVec::new(), render: Some(live_r_arena.clone()) }; + let live_slot = p.pick_slot_in_mask_blocks(&live, false, 0b11, 0, 512).unwrap(); + assert_eq!(live_slot, 0); + let live_e = g16::pools::PbEpoch::new( + &factory, + &live, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + live_e.prepare(live_slot, g16::hw::client::pb_heap(0), 512).unwrap(); + live_e.expose(); + let lb = p.bind(live_slot, false); + p.hold_alloc(live_slot, &live, Some(PbOwnerArena::Base(live_r_arena.clone())), None).unwrap(); + p.publish_flight(live_slot); + p.retire_flight(live_slot, &live_e, lb, true).unwrap(); + + let lpk = s.pick_pass_in_for(&live_r_prep, &geo, 0, Some(live.id)).unwrap(); + s.claim_pass_in(&live_r_prep, lpk, Some(live.id), geo.tilemap_bytes).unwrap(); + let mut lrc = Claims::new(); + lrc.pass[0] = lpk as u32; + lrc.pass_count = 1; + lrc.pass_mask = 1u64 << lpk; + s.hold_render_pass(lpk, &live, &live_r_prep).unwrap(); + s.publish(&mut lrc).unwrap(); + s.retire(&mut lrc).unwrap(); + + let mut lcc = Claims::new(); + let lck = s + .claim_compute_for(&shared_prep_compute, &mut lcc, Some(live.id)) + .unwrap() + .unwrap(); + s.hold_compute_slot(lck, &live, &shared_prep_compute).unwrap(); + s.publish(&mut lcc).unwrap(); + s.retire(&mut lcc).unwrap(); + + // Now slot 15 is displaced -> reclaim_closed() evicts it and returns false (0 remaining). + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&epochs[last]), 1); + assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 1); + assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 1); + drop(epochs); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released"); + } + + // Active off-lock scrub on a closed VM's displaced pass slot waits for scrub completion. + let mut s2 = Slots::new().unwrap(); + let mut sc_passes = KVec::new(); + for k in 0..2 { + sc_passes.push(PassSlot::new(&mut o, k as u64, 1).unwrap(), 0).unwrap(); + } + let sc_arena = sync::Arc::new(render_arena(sc_passes), 0).unwrap(); + let sc_prep = ComputeArena { compute: KVec::new(), render: Some(sc_arena.clone()) }; + let va = vm(600); + let vb = vm(601); + for (k, owner) in [(0usize, &va), (1usize, &vb)] { + s2.claim_pass_in(&sc_prep, k, Some(owner.id), 0x2000).unwrap(); + sc_prep.set_pass_dirty(k, 0x1000, 0x2000, 0x200).unwrap(); + let mut c = Claims::new(); + c.pass[0] = k as u32; + c.pass_count = 1; + c.pass_mask = 1u64 << k; + s2.hold_render_pass(k, owner, &sc_prep).unwrap(); + s2.publish(&mut c).unwrap(); + s2.retire(&mut c).unwrap(); + } + // Stage off-lock scrub on displaced slot 0 while va is still open, then close va. + s2.stage_displaced_pass_scrubs(); + assert!(s2.scrubbing_active()); + let batch = s2.take_staged_scrubs(); + va.vm.close(); + assert!(s2.reclaim_closed(), "must not evict slot 0 mid-scrub"); + assert_eq!(sync::Arc::strong_count(&va), 2); + // Running the scrub wakes the reclaim waiter, then reclaim_closed() evicts slot 0. + assert!(drain_scrubs(batch)); + assert!(s2.take_scrub_woke()); + assert!(!s2.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&va), 1); + + // Quarantined closed-VM slots stay pinned forever AND do not keep reclaim_closed() armed. + let vq = vm(700); + let mut pq = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let eq = g16::pools::PbEpoch::new( + &factory, + &vq, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + pq.hold_alloc(0, &vq, Some(PbOwnerArena::Base(sc_arena.clone())), None).unwrap(); + pq.publish_flight(0); + pq.quarantine_flight(0, Some(eq.clone())); + let mut cq = Claims::new(); + let qk = s2.claim_compute_for(&shared_prep_compute, &mut cq, Some(vq.id)).unwrap().unwrap(); + s2.hold_compute_slot(qk, &vq, &shared_prep_compute).unwrap(); + s2.publish(&mut cq).unwrap(); + s2.quarantine(&mut cq); + vq.vm.close(); + assert!(!pq.reclaim_closed(), "quarantined PB slot must not spin reclaim"); + assert!(!s2.reclaim_closed(), "quarantined compute slot must not spin reclaim"); + assert!(sync::Arc::strong_count(&vq) > 1, "quarantined leases stay retained"); + } + #[test]fn closed_vm_reclaim_retains_firmware_pb_and_uma_leases_until_overwritten(){ + use g16::hw::sizes::{COMPUTE_UNITS, WARM_PB_SLOTS}; + use g16::resources::{COMPUTE_OWNER_ARENA, ComputeArena, PbOwnerArena}; + use g16::slots::ComputeSlot; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let mut s = Slots::new().unwrap(); + let mut o = Objects::new(); + + // VM1 primes PB/UMA slot 0 and compute unit 0; VM2 displaces both via slot 1 / unit 1. + let vm1 = vm(1001); + let vm2 = vm(1002); + let vm3 = vm(1003); + + let pools1 = PoolSet::new_with_slots(&mut o, &factory, [0, 1]).unwrap(); + let uma1 = pools1.unit(0).unwrap().uma_lease(); + let r_arena1 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e1 = g16::pools::PbEpoch::new( + &factory, + &vm1, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease1 = e1.records_lease(); + e1.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e1.expose(); + let b1 = p.bind(0, false); + p.hold_alloc(0, &vm1, Some(PbOwnerArena::Base(r_arena1.clone())), Some(uma1.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e1, b1, true).unwrap(); + + let pools2 = PoolSet::new_with_slots(&mut o, &factory, [1, 2]).unwrap(); + let uma2 = pools2.unit(0).unwrap().uma_lease(); + let r_arena2 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let e2 = g16::pools::PbEpoch::new( + &factory, + &vm2, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e2.prepare(1, g16::hw::client::pb_heap(0), 512).unwrap(); + e2.expose(); + let b2 = p.bind(1, false); + p.hold_alloc(1, &vm2, Some(PbOwnerArena::Base(r_arena2.clone())), Some(uma2.clone())).unwrap(); + p.publish_flight(1); + p.retire_flight(1, &e2, b2, true).unwrap(); + + // Compute unit 0 owned by VM1, displaced by VM2 on unit 1. + let mut units1 = KVec::new(); + for k in 0..COMPUTE_UNITS { + units1.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); + } + let c_uma1 = units1[0].uma_lease(); + let prep1 = ComputeArena { compute: units1, render: None }; + let c_arena1 = sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(); + let mut cc1 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep1, &mut cc1, Some(vm1.id)).unwrap(), Some(0)); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = Some(c_arena1.clone())); + s.hold_compute_slot(0, &vm1, &prep1).unwrap(); + COMPUTE_OWNER_ARENA.with(|a| *a.borrow_mut() = None); + s.publish(&mut cc1).unwrap(); + s.retire(&mut cc1).unwrap(); + + let mut units2 = KVec::new(); + for k in 0..COMPUTE_UNITS { + units2.push(ComputeSlot::new(&mut o, &factory, k as u64).unwrap(), 0).unwrap(); + } + let prep2 = ComputeArena { compute: units2, render: None }; + let mut cc2 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep2, &mut cc2, Some(vm2.id)).unwrap(), Some(1)); + s.hold_compute_slot(1, &vm2, &prep2).unwrap(); + s.publish(&mut cc2).unwrap(); + s.retire(&mut cc2).unwrap(); + + let mut units3 = KVec::new(); + units3.push(ComputeSlot::new(&mut o, &factory, 0).unwrap(), 0).unwrap(); + let c_uma3 = units3[0].uma_lease(); + let prep3 = ComputeArena { compute: units3, render: None }; + + // Drop local arena/epoch/pool handles for VM1 and close VM1. + drop(e1); + drop(pools1); + drop(prep1); + vm1.vm.close(); + + // Reclaim evicts VM1's VmState, RenderArena, PbEpoch, and ComputeArena immediately, + // WHILE retaining its tiny VM-free firmware PB & UMA leases until overwritten! + assert!(!p.reclaim_closed()); + assert!(!s.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&vm1), 1, "VM1 VmState/TTBAT must release immediately"); + assert_eq!(sync::Arc::strong_count(&r_arena1), 1, "VM1 RenderArena/PB heap must release"); + assert_eq!(sync::Arc::strong_count(&c_arena1), 1, "VM1 ComputeArena/32MiB pool must release"); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 2, "pb_mgr_table[0] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&uma1), 2, "render uma_mgr_table[33] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2, "compute uma_mgr_table[1] lease must stay mapped"); + + // Cancelling an unpublished replacement on slot 0 / unit 0 must NOT release VM1's leases. + let pools3 = PoolSet::new_with_slots(&mut o, &factory, [0, 2]).unwrap(); + let uma3 = pools3.unit(0).unwrap().uma_lease(); + let r_arena3 = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3.clone())), Some(uma3.clone())).unwrap(); + p.cancel_alloc(0); + assert_eq!(sync::Arc::strong_count(&uma1), 2); + assert_eq!(sync::Arc::strong_count(&uma3), 2); + + let mut cc3_cancel = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3_cancel, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.release(&mut cc3_cancel); + assert_eq!(sync::Arc::strong_count(&c_uma1), 2); + + // Once VM3 retires on exact hardware slot 0 / unit 0, firmware tables are overwritten and + // VM1's old FwLeases drop cleanly while VM3's leases become retained. + let e3 = g16::pools::PbEpoch::new( + &factory, + &vm3, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + let pb_lease3 = e3.records_lease(); + e3.prepare(0, g16::hw::client::pb_heap(0), 512).unwrap(); + e3.expose(); + let b3 = p.bind(0, false); + p.hold_alloc(0, &vm3, Some(PbOwnerArena::Base(r_arena3)), Some(uma3.clone())).unwrap(); + p.publish_flight(0); + p.retire_flight(0, &e3, b3, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 1, "overwritten pb_mgr_table[0] lease dropped"); + assert_eq!(sync::Arc::strong_count(&uma1), 1, "overwritten render uma_mgr_table[33] lease dropped"); + assert_eq!(sync::Arc::strong_count(&pb_lease3), 3, "new PB lease held by epoch + retained_pb"); + assert_eq!(sync::Arc::strong_count(&uma3), 3, "new render UMA lease held by pool + retained_uma"); + + let mut cc3 = Claims::new(); + assert_eq!(s.claim_compute_for(&prep3, &mut cc3, Some(vm3.id)).unwrap(), Some(0)); + s.hold_compute_slot(0, &vm3, &prep3).unwrap(); + s.publish(&mut cc3).unwrap(); + s.retire(&mut cc3).unwrap(); + assert_eq!(sync::Arc::strong_count(&c_uma1), 1, "overwritten compute uma_mgr_table[1] lease dropped"); + assert_eq!(sync::Arc::strong_count(&c_uma3), 3, "new compute UMA lease held by unit + retained_uma"); + let _ = WARM_PB_SLOTS; + } + } ''' poll_source = (production/'poll.rs').read_text() @@ -2031,6 +2439,9 @@ def module(text, name): assert 'self.enqueue_scrubs(scrubs)' in poll_source, 'poll.rs must enqueue scrubs asynchronously' assert 'OwnedQueue::new_unbound_reclaim(c_str!("aurora_g16_scrub"), false)' in mod_source assert 'self.scrub_wq.drain();' in sleep_source, 'sleep.rs::join_workers must drain scrub_wq' +assert 'closed_vm_reclaim' in mod_source +assert 'self.shared.closed_vm_reclaim.store(true, Ordering::Release);' in mod_source +assert 'reclaim_closed_vm_slots' in poll_source lifetime_source = (production.parent / 'mmu' / 'lifetime.rs').read_text() is_closed_fn = item(lifetime_source, 'pub(crate) fn is_closed(') assert '.lock()' not in is_closed_fn, 'Vm::is_closed() must be lock-free' @@ -2107,7 +2518,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 38, + 'result': 'pass', 'tests': 40, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 6bd4317e47e0d9b71b05bd13860b5cc88ce00bdd Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 12:59:21 -0500 Subject: [PATCH 07/10] drm/asahi/g16: split compute arenas per unit to bound closed-VM pins With two independent CDM pipes (COMPUTE_PIPES = 2), multi-process compute leaves one undisplaced last-retired compute unit on pipe 0 and one on pipe 1 (22 of 24 units reusable). Because firmware may still reference each pipe's last-retired unit until a later retired publication on that same pipe displaces it, those two owner leases must remain pinned. Previously, Ready::compute_ext backed all 22 extension compute units (2..24) inside a single monolithic Arc (~713 MiB). Holding a lease on one undisplaced extension unit pinned all 22 units of its closed VM; across two CDM pipes that retained ~1.40 GiB (+1,464 MiB Unevictable) instead of 2 x ~32.4 MiB (~65 MiB). Split compute unit backing so each ComputeArena owns a single self-contained ComputeSlot and introduce ComputeUnitSet (a KVec of per-unit Arc) for Ready::{compute, compute_ext} and Prepared::{compute, compute_ext}: - Prepared::compute_arena(k) returns only unit k's Arc, keeping zero-alloc Cache::prepare() cloning intact. - When a VM closes, Cache::close() and Slots::reclaim_closed() drop every unused or displaced unit immediately while each pipe's undisplaced (or quarantined) slot pins only its own ~32.4 MiB unit (~22x reduction). - Add dual-pipe per-unit closed-VM reclamation coverage in test-resources.py. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/resources.rs | 89 ++++++++++++----- .../drivers/gpu/asahi-m4/test-resources.py | 99 ++++++++++++++++++- 2 files changed, 158 insertions(+), 30 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/resources.rs b/drivers/gpu/drm/asahi/g16/resources.rs index 271b3867da424..c3b5d0acfed90 100644 --- a/drivers/gpu/drm/asahi/g16/resources.rs +++ b/drivers/gpu/drm/asahi/g16/resources.rs @@ -27,6 +27,8 @@ use kernel::{ /// avoids allocating and mapping fresh epochs whenever submission depth rises. const SPARE_EPOCHS: usize = 32; +/// Backing for one physical compute unit (`k`) of a VM, deferred-dropped independently so an +/// undisplaced last-retired owner lease on one CDM pipe never pins the VM's other compute units. pub(crate) struct ComputeArena(crate::cleanup::Deferred); impl core::ops::Deref for ComputeArena { type Target = ComputeInner; @@ -35,7 +37,7 @@ impl core::ops::Deref for ComputeArena { } } pub(crate) struct ComputeInner { - pub(crate) compute: KVec, + pub(crate) unit: ComputeSlot, _objects: Objects, // Mappings must disappear while their root still owns its ASID. _bind: mmu::VmBind, @@ -53,26 +55,21 @@ const BURST_GAP_NS: u64 = 2_000_000; const BURST_COMMANDS: usize = 3; impl ComputeArena { - /// Units `units` (their index fixes their client addresses and hardware UMA slot). + /// Allocates one self-contained compute unit `k` (its index fixes its client addresses and + /// hardware UMA slot). fn new( factory: &Factory, bind: &mmu::VmBind, vm: &mmu::Vm, live: &Arc, - units: core::ops::Range, + k: usize, ) -> Result> { let mut objects = factory.objects(vm); - let mut compute = KVec::with_capacity(units.len(), GFP_KERNEL)?; - for k in units { - compute.push( - ComputeSlot::new(&mut objects, factory, k as u64)?, - GFP_KERNEL, - )?; - } + let unit = ComputeSlot::new(&mut objects, factory, k as u64)?; objects.finish_private()?; Ok(Arc::new( Self(crate::cleanup::Deferred::new(ComputeInner { - compute, + unit, _objects: objects, _bind: bind.clone(), _live: live.clone(), @@ -82,6 +79,43 @@ impl ComputeArena { } } +/// Contiguous range of independently reference-counted [`ComputeArena`] units owned by a VM. +/// +/// Each unit `k` owns its own `Arc` so `Cache::close()` and +/// `Slots::reclaim_closed()` release all unused or displaced units immediately even while a +/// CDM pipe retains one undisplaced last-retired unit until displacement. +pub(crate) struct ComputeUnitSet { + units: KVec>, +} +impl ComputeUnitSet { + /// Units `range` (each index fixes its client addresses and hardware UMA slot). + fn new( + factory: &Factory, + bind: &mmu::VmBind, + vm: &mmu::Vm, + live: &Arc, + range: core::ops::Range, + ) -> Result> { + let mut units = KVec::with_capacity(range.len(), GFP_KERNEL)?; + for k in range { + units.push( + ComputeArena::new(factory, bind, vm, live, k)?, + GFP_KERNEL, + )?; + } + Ok(Arc::new(Self { units }, GFP_KERNEL)?) + } + fn len(&self) -> usize { + self.units.len() + } + fn unit(&self, idx: usize) -> Option<&ComputeSlot> { + self.units.get(idx).map(|arena| &arena.unit) + } + fn arena(&self, idx: usize) -> Option> { + self.units.get(idx).cloned() + } +} + /// Render pass slots every VM gets with its first render command; extension slots /// (`BASE_RENDER_SLOTS..hw::sizes::RENDER_SLOTS`) are grown lazily in bounded tiers once the VM /// pipelines renders or submits multi-pass/burst frames. @@ -546,9 +580,9 @@ impl PassOwnerArena { #[derive(Default)] struct Ready { - compute: Option>, + compute: Option>, /// Units from [`BASE_COMPUTE_UNITS`] on, for a VM that keeps compute queued. - compute_ext: Option>, + compute_ext: Option>, render: Option>, /// Demand-grown extension render pass tiers (`EXT_RENDER_TIERS`). render_ext: [Option>; EXT_RENDER_TIERS.len()], @@ -778,7 +812,7 @@ impl Cache { return Err(EIO); } if compute && ready.compute.is_none() { - ready.compute = Some(ComputeArena::new( + ready.compute = Some(ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, @@ -800,7 +834,7 @@ impl Cache { hints.expand_compute_ext, ) { // Best effort: without them the VM keeps the base compute units. - state.compute_ext = ComputeArena::new( + state.compute_ext = ComputeUnitSet::new( &self.factory, &self.bind, &vm.vm, @@ -1081,9 +1115,9 @@ impl Cache { /// Immutable references carried by an accepted job. No fallible lazy work in the engine. pub(crate) struct Prepared { - pub(crate) compute: Option>, + pub(crate) compute: Option>, /// The VM's extension compute units when the job was prepared. - pub(crate) compute_ext: Option>, + pub(crate) compute_ext: Option>, pub(crate) render: Option>, /// The VM's demand-grown extension render pass tiers when the job was prepared. pub(crate) render_ext: [Option>; EXT_RENDER_TIERS.len()], @@ -1113,21 +1147,22 @@ impl Drop for Prepared { } } impl Prepared { - pub(crate) fn compute(&self) -> Result<&ComputeArena> { + pub(crate) fn compute(&self) -> Result<&ComputeUnitSet> { self.compute.as_deref().ok_or(EINVAL) } /// Compute units this job can use. pub(crate) fn compute_units(&self) -> Result { - Ok(self.compute()?.compute.len() - + self.compute_ext.as_deref().map_or(0, |e| e.compute.len())) + Ok(self.compute()?.len() + self.compute_ext.as_deref().map_or(0, ComputeUnitSet::len)) } - /// The arena holding compute unit `k`. + /// The per-unit arena holding compute unit `k`. pub(crate) fn compute_arena(&self, k: usize) -> Option> { let base = self.compute.as_ref()?; - if k < base.compute.len() { - Some(base.clone()) + if k < base.len() { + base.arena(k) } else { - self.compute_ext.clone() + self.compute_ext + .as_ref() + .and_then(|ext| ext.arena(k - base.len())) } } /// Physical PB/UMA allocator slot bitmask and preferred home slot this job can use. @@ -1294,13 +1329,13 @@ impl Prepared { } /// Compute unit `k`: the VM's base units, then its extension units. pub(crate) fn compute_unit(&self, k: usize) -> Result<&ComputeSlot> { - let base = &self.compute()?.compute; - match base.get(k) { + let base = self.compute()?; + match base.unit(k) { Some(unit) => Ok(unit), None => self .compute_ext .as_deref() - .and_then(|e| e.compute.get(k - base.len())) + .and_then(|e| e.unit(k - base.len())) .ok_or(EINVAL), } } 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 efbe9e2b7a2f3..458a57a99a8dc 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -193,12 +193,17 @@ def module(text, name): pub static COMPUTE_OWNER_ARENA:std::cell::RefCell< Option>, >=const{std::cell::RefCell::new(None)}; + pub static COMPUTE_OWNER_ARENAS:std::cell::RefCell< + Option>>, + >=const{std::cell::RefCell::new(None)}; } impl ComputeArena{ pub fn compute_units(&self)->Result{Ok(self.compute.len())} pub fn compute_unit(&self,k:usize)->Result<&super::slots::ComputeSlot>{self.compute.get(k).ok_or(EINVAL)} - pub fn compute_arena(&self,_k:usize)->Option>{ - COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone()) + pub fn compute_arena(&self,k:usize)->Option>{ + COMPUTE_OWNER_ARENAS + .with(|a|a.borrow().as_ref().and_then(|v|v.get(k).cloned())) + .or_else(||COMPUTE_OWNER_ARENA.with(|a|a.borrow().clone())) } pub fn render_arena(&self)->Option>{self.render.clone()} pub fn render_passes(&self)->Result{self.render.as_deref().map(|r|r.passes.len()).ok_or(EINVAL)} @@ -2429,6 +2434,90 @@ def module(text, name): let _ = WARM_PB_SLOTS; } + #[test]fn dual_pipe_closed_compute_vms_pin_only_one_unit_per_pipe(){ + use g16::hw::sizes::COMPUTE_UNITS; + use g16::resources::{COMPUTE_OWNER_ARENAS, ComputeArena}; + use g16::slots::ComputeSlot; + + let mut o = Objects::new(); + let mut s = Slots::new().unwrap(); + let mut compute_slots = KVec::new(); + for k in 0..COMPUTE_UNITS { + compute_slots.push(ComputeSlot::new(&mut o, &g16::object::Factory, k as u64).unwrap(), 0).unwrap(); + } + let prep = ComputeArena { compute: compute_slots, render: None }; + + // Simulate 8 compute VMs, each owning 24 independent per-unit ComputeArenas + // (matching production ComputeUnitSet), running across BOTH CDM pipes (0 and 1). + let mut vms = Vec::new(); + let mut vm_unit_arenas: Vec>> = Vec::new(); + for i in 0..8usize { + let v = vm(800 + i as u64); + let mut per_unit = Vec::with_capacity(COMPUTE_UNITS); + for _ in 0..COMPUTE_UNITS { + per_unit.push( + sync::Arc::new(ComputeArena { compute: KVec::new(), render: None }, 0).unwrap(), + ); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = Some(per_unit.clone())); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(v.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &v, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + COMPUTE_OWNER_ARENAS.with(|a| *a.borrow_mut() = None); + vms.push(v); + vm_unit_arenas.push(per_unit); + } + + // Close all 8 VMs and reclaim displaced leases: + // - Pipe 0 and pipe 1 each retain 1 undisplaced last-retired unit -> reusable == 22. + // - Out of 8 * 24 = 192 per-unit arenas, ONLY those 2 undisplaced units remain pinned + // (strong_count == 2); all 190 other units (including the other 23 units of each + // last-retired VM) drop immediately (strong_count == 1). + for v in &vms { + v.vm.close(); + } + assert!(s.reclaim_closed(), "two undisplaced dual-pipe units remain"); + assert_eq!(s.lifetime_counts()[0].reusable, (COMPUTE_UNITS - 2) as u32); + let pinned_units: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_units, 2, "must pin exactly 1 unit per CDM pipe, never a whole VM set"); + for (i, units) in vm_unit_arenas.iter().enumerate() { + let vm_pinned = units.iter().filter(|a| sync::Arc::strong_count(a) > 1).count(); + if i == 7 { + assert_eq!(vm_pinned, 2, "last VM holds only its 2 undisplaced units"); + } else { + assert_eq!(vm_pinned, 0, "displaced closed VM {i} holds 0 units"); + assert_eq!(sync::Arc::strong_count(&vms[i]), 1, "closed VM {i} fully released"); + } + } + + // Displace pipe 0 and pipe 1 with a live VM -> all 8 closed VMs and 192 units release. + let live = vm(900); + for pipe in [0usize, 1usize] { + let mut c = Claims::new(); + let k = s.claim_compute_for_pipe(&prep, &mut c, Some(live.id), pipe).unwrap().unwrap(); + s.hold_compute_slot(k, &live, &prep).unwrap(); + s.publish(&mut c).unwrap(); + s.retire(&mut c).unwrap(); + } + assert!(!s.reclaim_closed(), "both dual-pipe closed leases displaced and reclaimed"); + let pinned_after: usize = vm_unit_arenas + .iter() + .flat_map(|units| units.iter()) + .filter(|arena| sync::Arc::strong_count(arena) > 1) + .count(); + assert_eq!(pinned_after, 0); + for (i, v) in vms.iter().enumerate() { + assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); + } + } } ''' poll_source = (production/'poll.rs').read_text() @@ -2474,6 +2563,10 @@ def module(text, name): source=source.replace('__BUDGET__',budget.replace('//!','//')) source = source.replace('__LIVE_TOKEN__' ,item((production/'vm.rs').read_text(),'pub(crate) struct LiveToken')).replace('__LIVE_DROP__',item((production/'vm.rs').read_text(),'impl Drop for LiveToken')) resources_source = (production/'resources.rs').read_text() +assert 'pub(crate) struct ComputeUnitSet {' in resources_source, 'resources.rs must split compute units into per-unit ComputeArenas' +assert 'ComputeArena::new(factory, bind, vm, live, k)?' in resources_source, 'ComputeUnitSet::new must allocate one ComputeArena per unit' +assert 'compute_ext: Option>' in resources_source, 'compute_ext must use ComputeUnitSet so undisplaced slots pin only one unit' +assert 'base.arena(k)' in resources_source and 'ext.arena(k - base.len())' in resources_source, 'Prepared::compute_arena must return the per-unit ComputeArena' ext_tiers_start = resources_source.index('pub(crate) const EXT_RENDER_TIERS:') ext_tiers_end = resources_source.index('];\n', ext_tiers_start) + 3 render_burst_lines = ( @@ -2518,7 +2611,7 @@ def module(text, name): raise SystemExit(result.returncode) files = ['graph.rs', 'slots.rs', 'pools.rs', 'pools/lifetime.rs', 'fw/buffer.rs', 'fw/graph.rs', 'fw/work.rs', 'hw.rs', 'resources.rs', 'budget.rs'] (out/'resource-host.json').write_text(json.dumps({ - 'result': 'pass', 'tests': 40, + 'result': 'pass', 'tests': 41, 'scope': 'Actual production allocation, initialization and lifetime code against a CPU-only backing recorder; no hardware qualification.', 'private_rw_pte': hex(private_rw), 'private_rw_reference': 'Qualified J713 NC read/write leaf attributes', From 047b934ce47ad72d4c9954c0cf07eec7ee20fef8 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Tue, 24 Nov 2026 00:27:05 -0500 Subject: [PATCH 08/10] drm/asahi: g16: keep closed VMs' PB epochs until their slot is replaced Commit c12278d5c9aa ("drm/asahi/g16: reclaim displaced closed-VM slot leases and retain firmware PB/UMA records") lets Pools::reclaim_closed() drop the owner epoch of a closed VM's PB slot as soon as a render retires on any other slot while keeping the manager record mapped. That epoch maps the page list of its manager in the VM's DYNAMIC client window and its block list, and it holds the VM's TTBAT slot. Because the firmware keeps pb_mgr_table[k] naming the manager across work on other slots, dropping the epoch releases the page and block lists and the VM's ASID while the firmware can still reference that manager. A light render workload run repeatedly with sixteen concurrent client processes faulted with no compute or ray-query work active: fault bank 1: status 0x8b81ddc021 va 0x704000cb40 (write unmapped level 0 unit 0xe0 ctx 46) attribution: busy=0 ctx=46 flight_matches=1 live_vm=Some(110) event=0xffffffff flights=1 Unit 0xe0 is gPM_SP(0), the parameter manager. Only PB page lists are placed in the DYNAMIC window: 0x704000cb40 is entry 720 of a VM's second page list. No TA, FS or compute slot was running for ctx 46, so the firmware attributed the fault to no stage. The parameter manager wrote a PB page list that ctx 46 did not map. Reclaim releases exactly such a list, together with the VM context, while pb_mgr_table[k] still names its manager. Keep the owner epoch until a newer epoch retires on the same slot, as before reclaim existed; retire_flight() already replaces it then. Reclaim still releases the closed VM's render arena, PB heap and the slot's VM references. A closed VM then keeps only its two 32 KiB lists, its records and its context until its slot is reused, and each PB slot pins at most one such VM. A slot holding nothing but that epoch no longer keeps reclaim armed. Add a host regression test for this sequence and update the two reclaim tests, which expected the epoch and the VM's TTBAT slot to be released at reclaim. Fixes: c12278d5c9aa ("drm/asahi/g16: reclaim displaced closed-VM slot leases and retain firmware PB/UMA records") Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/pools.rs | 25 +++-- .../drivers/gpu/asahi-m4/test-resources.py | 103 +++++++++++++++++- 2 files changed, 114 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/pools.rs b/drivers/gpu/drm/asahi/g16/pools.rs index 78c93869d57dc..8c801b7940461 100644 --- a/drivers/gpu/drm/asahi/g16/pools.rs +++ b/drivers/gpu/drm/asahi/g16/pools.rs @@ -416,6 +416,9 @@ impl PoolSet { pub(crate) struct Pools { pub(crate) dev: ARef, pub(crate) stats: PbStats, + /// The epoch whose manager `pb_mgr_table[k]` names, kept until a newer epoch retires on + /// slot `k`, also after its VM closed: it maps the manager's page and block lists and keeps + /// the VM's TTBAT slot bound, the context through which those lists are written. owners: [Option>; sizes::PB_SLOTS], /// VM-free firmware leases keeping each `parameter_id`'s `pb_manager` + `counter` page mapped /// for firmware's global `pb_mgr_table[parameter_id]` across closed-VM reclaim until a newer @@ -904,15 +907,26 @@ impl Pools { *keep = false; } } - /// Releases displaced PB/UMA allocator leases owned by closed VMs while preserving active, + /// Releases the displaced render arenas and PB heaps of closed VMs while preserving active, /// in-flight, undisplaced, and quarantined slots. Returns `true` if any non-quarantined - /// slot still holds a closed-VM lease awaiting retirement or displacement. + /// slot still holds such a closed-VM lease awaiting retirement or displacement. + /// + /// The owner epoch itself stays until a newer epoch retires on its slot + /// ([`Self::retire_flight`]): `pb_mgr_table[k]` keeps naming its manager, and the parameter + /// manager can still write that manager's page list through the context of the epoch's VM. pub(crate) fn reclaim_closed(&mut self) -> bool { let mut remaining = false; for k in 0..sizes::PB_SLOTS { if self.quarantined[k] { continue; } + let pending = self.pending_vms[k].is_some() + || self.pending_arenas[k].is_some() + || self.pending_uma[k].is_some(); + // Only the owner epoch is left; the next epoch to retire on the slot releases it. + if !pending && self.owner_vms[k].is_none() && self.owner_arenas[k].is_none() { + continue; + } let closed = self.owner_vms[k] .as_ref() .is_some_and(|vm| vm.vm.is_closed()) @@ -925,12 +939,7 @@ impl Pools { if !closed { continue; } - if self.slot_displaced(k) - && self.pending_vms[k].is_none() - && self.pending_arenas[k].is_none() - && self.pending_uma[k].is_none() - { - self.owners[k] = None; + if self.slot_displaced(k) && !pending { self.owner_vms[k] = None; self.owner_arenas[k] = None; self.keep[k] = false; 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 458a57a99a8dc..69138f4dd1135 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -2180,7 +2180,8 @@ def module(text, name): let last = WARM_PB_SLOTS - 1; for i in 0..last { assert_eq!(sync::Arc::strong_count(&pb_arenas[i]), 1, "PB arena {i} reclaimed"); - assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "PB epoch {i} reclaimed"); + // pb_mgr_table[i] still names this epoch's manager: it stays until replaced. + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); assert_eq!(sync::Arc::strong_count(&pass_arenas[i]), 1, "pass arena {i} reclaimed"); assert_eq!(sync::Arc::strong_count(&comp_arenas[i]), 1, "compute arena {i} reclaimed"); assert_eq!(sync::Arc::strong_count(&vms[i]), 2); @@ -2231,9 +2232,30 @@ def module(text, name): assert!(!p.reclaim_closed()); assert!(!s.reclaim_closed()); assert_eq!(sync::Arc::strong_count(&pb_arenas[last]), 1); - assert_eq!(sync::Arc::strong_count(&epochs[last]), 1); assert_eq!(sync::Arc::strong_count(&pass_arenas[last]), 1); assert_eq!(sync::Arc::strong_count(&comp_arenas[last]), 1); + // VM 17's epoch replaced slot 0's; the other slots keep their closed owners' epochs. + assert_eq!(sync::Arc::strong_count(&epochs[0]), 1, "replaced PB epoch 0 released"); + for i in 1..WARM_PB_SLOTS { + assert_eq!(sync::Arc::strong_count(&epochs[i]), 2, "PB epoch {i} still bound"); + } + // Each epoch is released once a newer epoch retires on its own slot. + for i in 1..WARM_PB_SLOTS { + let next = vm(520 + i as u64); + let e = g16::pools::PbEpoch::new( + &factory, + &next, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(i, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + let b = p.bind(i, false); + p.hold_alloc(i, &next, None, None).unwrap(); + p.publish_flight(i); + p.retire_flight(i, &e, b, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&epochs[i]), 1, "replaced PB epoch {i} released"); + } + assert!(!p.reclaim_closed()); drop(epochs); for (i, v) in vms.iter().enumerate() { assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released"); @@ -2379,14 +2401,15 @@ def module(text, name): drop(prep1); vm1.vm.close(); - // Reclaim evicts VM1's VmState, RenderArena, PbEpoch, and ComputeArena immediately, - // WHILE retaining its tiny VM-free firmware PB & UMA leases until overwritten! + // Reclaim evicts VM1's RenderArena and ComputeArena immediately and retains its + // firmware PB & UMA leases until overwritten. PB slot 0's epoch keeps VM1's VmState + // (TTBAT slot) and page list until a newer epoch retires on slot 0. assert!(!p.reclaim_closed()); assert!(!s.reclaim_closed()); - assert_eq!(sync::Arc::strong_count(&vm1), 1, "VM1 VmState/TTBAT must release immediately"); + assert_eq!(sync::Arc::strong_count(&vm1), 2, "VM1 TTBAT slot stays with its PB epoch"); assert_eq!(sync::Arc::strong_count(&r_arena1), 1, "VM1 RenderArena/PB heap must release"); assert_eq!(sync::Arc::strong_count(&c_arena1), 1, "VM1 ComputeArena/32MiB pool must release"); - assert_eq!(sync::Arc::strong_count(&pb_lease1), 2, "pb_mgr_table[0] lease must stay mapped"); + assert_eq!(sync::Arc::strong_count(&pb_lease1), 3, "pb_mgr_table[0] lease held by epoch + retained_pb"); assert_eq!(sync::Arc::strong_count(&uma1), 2, "render uma_mgr_table[33] lease must stay mapped"); assert_eq!(sync::Arc::strong_count(&c_uma1), 2, "compute uma_mgr_table[1] lease must stay mapped"); @@ -2398,6 +2421,7 @@ def module(text, name): p.cancel_alloc(0); assert_eq!(sync::Arc::strong_count(&uma1), 2); assert_eq!(sync::Arc::strong_count(&uma3), 2); + assert_eq!(sync::Arc::strong_count(&vm1), 2); let mut cc3_cancel = Claims::new(); assert_eq!(s.claim_compute_for(&prep3, &mut cc3_cancel, Some(vm3.id)).unwrap(), Some(0)); @@ -2420,6 +2444,7 @@ def module(text, name): p.publish_flight(0); p.retire_flight(0, &e3, b3, true).unwrap(); assert_eq!(sync::Arc::strong_count(&pb_lease1), 1, "overwritten pb_mgr_table[0] lease dropped"); + assert_eq!(sync::Arc::strong_count(&vm1), 1, "replaced PB epoch releases VM1's TTBAT slot"); assert_eq!(sync::Arc::strong_count(&uma1), 1, "overwritten render uma_mgr_table[33] lease dropped"); assert_eq!(sync::Arc::strong_count(&pb_lease3), 3, "new PB lease held by epoch + retained_pb"); assert_eq!(sync::Arc::strong_count(&uma3), 3, "new render UMA lease held by pool + retained_uma"); @@ -2518,6 +2543,72 @@ def module(text, name): assert_eq!(sync::Arc::strong_count(v), 1, "closed VM {i} fully released after displacement"); } } + + // A closed VM's PB slot 3 is displaced by slot 4 and reclaimed. pb_mgr_table[3] still names + // its epoch's manager; gPM_SP(0) wrote that manager's page list (DYNAMIC, 0x704000cb40) + // through ctx 46 after the epoch was gone: "write unmapped level 0 unit 0xe0 ctx 46". + #[test]fn closed_vm_pb_epoch_keeps_page_list_and_context_until_slot_replacement_retires(){ + use g16::resources::PbOwnerArena; + + let factory = g16::object::Factory; + let budget = g16::budget::Budget::new().unwrap(); + let mut p = g16::pools::Pools::new(&driver::AsahiDrmDevice(device::Device)); + let epoch = |v: &sync::Arc, k: usize| { + let e = g16::pools::PbEpoch::new( + &factory, + v, + g16::budget::Budget::reserve(&budget, 1).unwrap().take().unwrap(), + ).unwrap(); + e.prepare(k, g16::hw::client::pb_heap(0), 512).unwrap(); + e.expose(); + e + }; + + // VM X (ctx 46) runs and retires on PB slot 3; VM Y then retires on slot 4. + let x = vm(46); + let x_arena = sync::Arc::new(render_arena(KVec::new()), 0).unwrap(); + let ex = epoch(&x, 3); + let x_records = ex.records_lease(); + let bx = p.bind(3, false); + p.hold_alloc(3, &x, Some(PbOwnerArena::Base(x_arena.clone())), None).unwrap(); + p.publish_flight(3); + p.retire_flight(3, &ex, bx, true).unwrap(); + let y = vm(47); + let ey = epoch(&y, 4); + let by = p.bind(4, false); + p.hold_alloc(4, &y, None, None).unwrap(); + p.publish_flight(4); + p.retire_flight(4, &ey, by, true).unwrap(); + + // X closes. Its arena and PB heap go, but not the epoch firmware still names. + x.vm.close(); + assert!(!p.reclaim_closed(), "a retained owner epoch alone must not keep reclaim armed"); + assert!(!p.reclaim_closed()); + assert_eq!(sync::Arc::strong_count(&x_arena), 1, "closed VM's render arena reclaimed"); + assert_eq!(sync::Arc::strong_count(&ex), 2, "slot 3 epoch (page list) reclaimed early"); + assert_eq!(sync::Arc::strong_count(&x), 2, "ctx 46 released while its lists are named"); + assert!(sync::Arc::strong_count(&x_records) >= 2); + assert!(p.reusable(3, &x).is_none()); + + // A new VM's InitBM epoch rebinds slot 3. The old binding stays intact while that + // render is in flight and goes only with its full retirement. + let z = vm(48); + assert_eq!(p.pick_slot_in_mask_blocks(&z, false, 0b11000, 3, 512), Some(3)); + let ez = epoch(&z, 3); + let bz = p.bind(3, false); + p.hold_alloc(3, &z, None, None).unwrap(); + p.publish_flight(3); + assert!(p.reclaim_closed(), "rebinding render still in flight"); + assert_eq!(sync::Arc::strong_count(&ex), 2); + assert_eq!(sync::Arc::strong_count(&x), 2); + p.retire_flight(3, &ez, bz, true).unwrap(); + assert_eq!(sync::Arc::strong_count(&ex), 1, "replaced epoch released"); + drop(ex); + assert_eq!(sync::Arc::strong_count(&x), 1, "closed VM released after replacement"); + assert_eq!(sync::Arc::strong_count(&x_records), 1); + assert!(!p.reclaim_closed()); + } + } ''' poll_source = (production/'poll.rs').read_text() From 2cd448a3c82834fd9cdf8a61bf76a20228011459 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 17:17:23 -0500 Subject: [PATCH 09/10] drm/asahi: g16: say which side stalled when M4 recovery times out When a firmware recovery does not finish within its 1000 ms budget, recover() only logs "M4 GPU recovery exceeded 1000 ms" and fail-stops. On a live M4 recovery timeout after a type-4 event and its statistics record, the log could not tell whether the firmware never halted in phase 1 or the host acknowledged phase 1 and phase 3 never came. It also could not tell whether tiling or fragment work was left behind; the stats showed seven render owners still published. Keep the last phase the host read and name the stall from it and from whether the host had answered (recovery::logic::Stall). Also print the observed TA and FS stamps next to the newest published ones, and the number of flights retained. The message keeps its prefix, so existing log matching still works. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/recovery.rs | 16 ++++++- drivers/gpu/drm/asahi/g16/recovery/logic.rs | 48 +++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 8e9b9a61e3bab..6ed3120b70b57 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -425,16 +425,30 @@ impl Firmware { let deadline = start.saturating_add(logic::RECOVERY_BUDGET_NS); let mut answered = false; let mut generation = 0; + let mut last_phase = 0; loop { if let Some(error) = self.transport_error() { return Err(error); } let now = now_ns(); if logic::expired(now, deadline) { - dev_err!(self.dev(), "M4 GPU recovery exceeded 1000 ms\n"); + // Which side stalled, and whether tiling or fragment work was left behind. + let stage = self.recovery_snapshot().unwrap_or_default(); + dev_err!( + self.dev(), + "M4 GPU recovery exceeded 1000 ms: {} (phase {}, TA {:#x}/{:#x}, FS {:#x}/{:#x}, {} flights)\n", + logic::Stall::of(last_phase, answered).describe(), + last_phase, + stage[0], + self.engine.ta_target, + stage[1], + self.engine.fs_target, + self.engine.flights.len() + ); return Err(ETIMEDOUT); } let phase = self.firmware_r32(self.init.firmware_data().phase)?; + last_phase = phase; let current_generation = if phase == 1 || phase == 3 { self.firmware_generation()? } else { diff --git a/drivers/gpu/drm/asahi/g16/recovery/logic.rs b/drivers/gpu/drm/asahi/g16/recovery/logic.rs index f93b2cd35f4ff..a0b9641e51c19 100644 --- a/drivers/gpu/drm/asahi/g16/recovery/logic.rs +++ b/drivers/gpu/drm/asahi/g16/recovery/logic.rs @@ -102,6 +102,36 @@ pub(crate) fn action(phase: u32, answered: bool, generation_matches: bool) -> Re } } +/// Where a recovery that ran past [`RECOVERY_BUDGET_NS`] stopped, from the last phase the host +/// read and whether the host had acknowledged phase 1 ([`action`]'s inputs). +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum Stall { + /// The firmware announced a recovery but never published phase 1. + NotHalted, + /// The firmware published phase 1 and the host had not acknowledged it. + NotAcknowledged, + /// The host acknowledged phase 1 and the firmware never published phase 3. + NotResumed, +} + +impl Stall { + pub(crate) const fn of(phase: u32, answered: bool) -> Self { + match (phase, answered) { + (_, true) => Self::NotResumed, + (1, false) => Self::NotAcknowledged, + _ => Self::NotHalted, + } + } + + pub(crate) const fn describe(self) -> &'static str { + match self { + Self::NotHalted => "firmware never halted in phase 1", + Self::NotAcknowledged => "phase 1 not acknowledged", + Self::NotResumed => "firmware never published phase 3", + } + } +} + /// One valid-prefix entry of the firmware's snapshot. Invalid entries terminate it. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub(crate) struct SnapshotEntry { @@ -249,6 +279,24 @@ mod tests { assert_eq!(action(3, true, false), RecoveryAction::ProtocolError); } + #[test] + fn budget_overrun_names_the_phase_that_never_arrived() { + // dcp103b: a type-4 event and its statistics arrived, then 1000 ms passed. Which side + // stalled follows from the last phase read and whether the host had answered. + assert_eq!(Stall::of(0, false), Stall::NotHalted); + assert_eq!(Stall::of(1, false), Stall::NotAcknowledged); + assert_eq!(Stall::of(2, true), Stall::NotResumed); + for phase in [3, 4, u32::MAX] { + assert_eq!(Stall::of(phase, false), Stall::NotHalted); + } + let all = [Stall::NotHalted, Stall::NotAcknowledged, Stall::NotResumed]; + for (i, a) in all.iter().enumerate() { + for b in &all[i + 1..] { + assert_ne!(a.describe(), b.describe()); + } + } + } + #[test] fn affected_job_failure_does_not_erase_a_full_owner_receipt() { assert!(!Retirement::Pending.complete()); From a1450a23e65d0c68a6b5c9a18d3c5fd265d2b63f Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Mon, 23 Nov 2026 17:59:09 -0500 Subject: [PATCH 10/10] drm/asahi: g16: log fault_scan() records and firmware log entries during recovery When firmware announces a recovery with no attributed stage ([4, gen, 0, ffffffff]), recover() already runs fault_scan() while the firmware is halted in phase 1, but discards the fault status, VA, bank and unit without calling the existing log_fault() decoder, and silently drains the nine firmware log rings without printing their payload lines. Extend Regs::fault_scan() to snapshot all eight fault banks (restoring the saved selector), decode every non-zero bank through log_fault() with busy/ASID flight and live-VM attribution, and explicitly log when all eight banks read zero. Keep LOG_DATA attached to Channels and, whenever recovery is pending or running, print up to the last 32 drained firmware log payload entries before advancing the consumer (leaving the normal non-recovery drain path untouched). Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g16/boot.rs | 6 +- drivers/gpu/drm/asahi/g16/channel.rs | 136 +++++++++++++++++++++++--- drivers/gpu/drm/asahi/g16/hw.rs | 3 + drivers/gpu/drm/asahi/g16/initdata.rs | 1 + drivers/gpu/drm/asahi/g16/poll.rs | 3 +- drivers/gpu/drm/asahi/g16/recovery.rs | 71 +++++++++++++- drivers/gpu/drm/asahi/g16/regs.rs | 60 ++++++++---- drivers/gpu/drm/asahi/g16/vm.rs | 9 ++ 8 files changed, 249 insertions(+), 40 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/boot.rs b/drivers/gpu/drm/asahi/g16/boot.rs index 353c576b247d1..73b3445ffe2b9 100644 --- a/drivers/gpu/drm/asahi/g16/boot.rs +++ b/drivers/gpu/drm/asahi/g16/boot.rs @@ -533,9 +533,9 @@ impl Session { self.while_powered(regs::Regs::engine_state) } - /// The first engine fault bank holding a fault, for a firmware halted for recovery, or - /// `None` while the GPU is powered down. - pub(crate) fn fault_scan(&self) -> Result> { + /// All eight engine fault banks, for a firmware halted for recovery, or `None` while the GPU + /// is powered down. + pub(crate) fn fault_scan(&self) -> Result> { self.while_powered(regs::Regs::fault_scan) } diff --git a/drivers/gpu/drm/asahi/g16/channel.rs b/drivers/gpu/drm/asahi/g16/channel.rs index 17b5aef14c617..9e958a99a5ae9 100644 --- a/drivers/gpu/drm/asahi/g16/channel.rs +++ b/drivers/gpu/drm/asahi/g16/channel.rs @@ -55,6 +55,9 @@ impl Ring { } } +/// Maximum firmware log entries printed per recovery before suppressing excess entries. +pub(crate) const RECOVERY_FWLOG_CAP: usize = 32; + /// The channels and rings. pub(crate) struct Channels { /// The 12 submit channels (TA, FS and compute are used). @@ -63,6 +66,8 @@ pub(crate) struct Channels { pub(crate) event: Ring, /// The nine log sub-rings share one state object (9 x 0x30) and one ring object. pub(crate) log: Ring, + /// Backing payload buffer (`LOG_DATA`, 9 x 256 x 0xd8) indexed by firmware log records. + log_data: Arc, pub(crate) trace: Ring, pub(crate) stats: Ring, /// Allocated for the firmware; the host never uses it. @@ -93,6 +98,7 @@ impl Channels { devctl: Ring, event: Ring, log: Ring, + log_data: Arc, trace: Ring, stats: Ring, fwctl: Ring, @@ -112,6 +118,7 @@ impl Channels { devctl, event, log, + log_data, trace, stats, _fwctl: fwctl, @@ -222,17 +229,92 @@ impl Channels { ); } - /// Consumes a receive ring to its firmware producer. - fn drain_one(ring: &Ring, offset: usize, capacity: u32) -> Result { - let producer = ring.state.r32(offset + STATE_WRITE)?; - let consumer = ring.state.r32(offset + STATE_READ)?; - if producer >= capacity || consumer >= capacity { + /// Drains one firmware log sub-ring. Outside recovery (`budget` is `None`), advances the + /// consumer directly without touching the payload pages. During recovery (`Some(remaining)`), + /// prints up to the last `*remaining` entries and counts any older/excess entries suppressed. + #[inline(never)] + fn drain_log_ring( + &self, + dev: &kernel::device::Device, + thread: usize, + budget: Option<&mut usize>, + suppressed: &mut usize, + ) -> Result { + let offset = thread * 0x30; + let producer = self.log.state.r32(offset + STATE_WRITE)?; + let mut consumer = self.log.state.r32(offset + STATE_READ)?; + if producer >= RING_SLOTS || consumer >= RING_SLOTS { return Err(super::boot::eproto()); } - if consumer != producer { - ring.state.w32(offset + STATE_READ, producer)?; - wmb(); + if consumer == producer { + return Ok(()); } + if let Some(remaining) = budget { + rmb(); + let pending = producer.wrapping_sub(consumer) % RING_SLOTS; + if (pending as usize) > *remaining { + let skip = pending as usize - *remaining; + *suppressed = suppressed.saturating_add(skip); + consumer = (consumer + skip as u32) % RING_SLOTS; + } + while consumer != producer { + let entry_off = + (thread * RING_SLOTS as usize + consumer as usize) * rings::EVENT_RECORD; + let kind = self.log.ring.r32(entry_off)?; + let slot = self.log.ring.r32(entry_off + 8)?; + let payload_idx = thread * RING_SLOTS as usize + (slot & 255) as usize; + let payload_off = payload_idx * rings::LOG_PAYLOAD_SIZE; + let ptype = self.log_data.r32(payload_off)?; + let seq = self.log_data.r32(payload_off + 4)?; + let mut text = [0u8; rings::LOG_PAYLOAD_TEXT_SIZE]; + self.log_data + .read(payload_off + rings::LOG_PAYLOAD_TEXT_OFFSET, &mut text)?; + let len = text.iter().position(|&b| b == 0).unwrap_or(text.len()); + let line = core::str::from_utf8(&text[..len]) + .ok() + .map(|s| s.trim_end_matches(['\r', '\n'])); + match line { + Some(msg) if !msg.is_empty() && kind == 2 && ptype == 3 => { + dev_warn!( + dev, + "G16: fwlog[{}] seq={} slot={}: {}\n", + thread, + seq, + slot, + msg + ); + } + Some(msg) if !msg.is_empty() => { + dev_warn!( + dev, + "G16: fwlog[{}] kind={} ptype={} seq={} slot={}: {}\n", + thread, + kind, + ptype, + seq, + slot, + msg + ); + } + _ => { + dev_warn!( + dev, + "G16: fwlog[{}] kind={} ptype={} seq={} slot={} (non-text len={})\n", + thread, + kind, + ptype, + seq, + slot, + len + ); + } + } + *remaining = remaining.saturating_sub(1); + consumer = (consumer + 1) % RING_SLOTS; + } + } + self.log.state.w32(offset + STATE_READ, producer)?; + wmb(); Ok(()) } @@ -252,21 +334,39 @@ impl Channels { result } - /// Drains the nine log sub-rings and the ktrace receive ring. - pub(crate) fn drain_auxiliary_rings(&self, dev: &kernel::device::Device) -> Result { + /// Drains the nine log sub-rings and the ktrace receive ring. When `fwlog_budget` is `Some`, + /// prints drained firmware log records up to the remaining budget. + pub(crate) fn drain_auxiliary_rings_with_log( + &self, + dev: &kernel::device::Device, + mut fwlog_budget: Option<&mut usize>, + ) -> Result { let mut result = Ok(()); + let mut suppressed = 0usize; let mut keep = |r: Result| { if result.is_ok() { result = r; } }; for i in 0..rings::LOG_RINGS { - keep(Self::drain_one(&self.log, i * 0x30, 256)); + keep(self.drain_log_ring(dev, i, fwlog_budget.as_deref_mut(), &mut suppressed)); + } + if suppressed != 0 { + dev_warn!( + dev, + "G16: fwlog: suppressed {} additional entries during recovery\n", + suppressed + ); } keep(self.drain_trace(dev)); result } + /// Drains the nine log sub-rings and the ktrace receive ring silently. + pub(crate) fn drain_auxiliary_rings(&self, dev: &kernel::device::Device) -> Result { + self.drain_auxiliary_rings_with_log(dev, None) + } + /// Drains every receive ring: events (decoded into `events`), the nine log sub-rings, trace /// and stats, whatever another ring reported. The firmware waits while its event ring is /// full, so one bad record must never leave a ring undrained. The first error is returned @@ -410,7 +510,12 @@ impl Firmware { /// Drains the receive rings and decodes events. Called on full housekeeping and idle passes. pub(crate) fn drain_rings(&mut self) -> Result { let dev = self.session.dev.clone(); - self.channels.drain_rings(&dev, &mut self.events) + let mut result = self.channels.drain_events_and_stats(&dev, &mut self.events); + let aux = self.drain_auxiliary_rings(); + if result.is_ok() { + result = aux; + } + result } /// Drains only the event and statistics rings on the hot retirement path. @@ -419,9 +524,12 @@ impl Firmware { self.channels.drain_events_and_stats(&dev, &mut self.events) } - /// Drains the auxiliary log and trace rings on periodic housekeeping passes. + /// Drains the auxiliary log and trace rings on periodic housekeeping passes. Prints firmware + /// log records (bounded per recovery) whenever a firmware recovery is pending or running. pub(crate) fn drain_auxiliary_rings(&mut self) -> Result { let dev = self.session.dev.clone(); - self.channels.drain_auxiliary_rings(&dev) + let log_fwlog = self.recovery.receipt_fault || self.recovery_pending().unwrap_or(false); + let budget = log_fwlog.then_some(&mut self.recovery.fwlog_remaining); + self.channels.drain_auxiliary_rings_with_log(&dev, budget) } } diff --git a/drivers/gpu/drm/asahi/g16/hw.rs b/drivers/gpu/drm/asahi/g16/hw.rs index 155c8f528abb2..55fcb9f05c950 100644 --- a/drivers/gpu/drm/asahi/g16/hw.rs +++ b/drivers/gpu/drm/asahi/g16/hw.rs @@ -542,6 +542,9 @@ pub(crate) mod rings { pub(crate) const LOG_RINGS: usize = 9; pub(crate) const LOG_STATE_SIZE: usize = 0x1b0; pub(crate) const LOG_RING_SIZE: usize = 0x28800; + pub(crate) const LOG_PAYLOAD_SIZE: usize = 0xd8; + pub(crate) const LOG_PAYLOAD_TEXT_OFFSET: usize = 0x10; + pub(crate) const LOG_PAYLOAD_TEXT_SIZE: usize = 0xc8; pub(crate) const TRACE_RING_SIZE: usize = 0x9000; pub(crate) const STATS_RING_SIZE: usize = 0x4800; pub(crate) const FWCTL_RING_SIZE: usize = 0x4000; diff --git a/drivers/gpu/drm/asahi/g16/initdata.rs b/drivers/gpu/drm/asahi/g16/initdata.rs index e4898529be5c7..6d8f3bb7836e7 100644 --- a/drivers/gpu/drm/asahi/g16/initdata.rs +++ b/drivers/gpu/drm/asahi/g16/initdata.rs @@ -150,6 +150,7 @@ pub(crate) fn build( pair(&graph, id::DEVCTRL_STATE, id::DEVCTRL_RING), pair(&graph, id::EVENT_STATE, id::EVENT_DATA), pair(&graph, id::LOG_STATE, id::LOG_ENTRIES), + graph[id::LOG_DATA].clone(), pair(&graph, id::KTRACE_STATE, id::KTRACE_DATA), pair(&graph, id::STATISTICS_STATE, id::STATISTICS_DATA), // FWCTL state and ring share one allocation (ring starts at+0x40). diff --git a/drivers/gpu/drm/asahi/g16/poll.rs b/drivers/gpu/drm/asahi/g16/poll.rs index e3252e36b2799..0685f2688827d 100644 --- a/drivers/gpu/drm/asahi/g16/poll.rs +++ b/drivers/gpu/drm/asahi/g16/poll.rs @@ -1347,7 +1347,6 @@ impl Firmware { } /// Logs the fault bank of `state` when it holds a fault. - #[allow(dead_code)] pub(crate) fn log_fault(&self, state: &EngineState) { let (bank, f, va) = (state.bank, state.status, state.address); if f != 0 { @@ -1357,7 +1356,7 @@ impl Firmware { } else { "unmapped" }; - dev_info!( + dev_warn!( self.graph.dev.as_ref(), "G16: fault bank {}: status {:#x} va {:#x} ({} {} level {} unit {:#x} ctx {})\n", bank, diff --git a/drivers/gpu/drm/asahi/g16/recovery.rs b/drivers/gpu/drm/asahi/g16/recovery.rs index 6ed3120b70b57..ce51e5249f518 100644 --- a/drivers/gpu/drm/asahi/g16/recovery.rs +++ b/drivers/gpu/drm/asahi/g16/recovery.rs @@ -74,6 +74,7 @@ pub(crate) struct Recovery { window_ns: u64, window_count: u32, running: bool, + pub(crate) fwlog_remaining: usize, } impl Recovery { @@ -97,6 +98,7 @@ impl Recovery { window_ns: 0, window_count: 0, running: false, + fwlog_remaining: super::channel::RECOVERY_FWLOG_CAP, } } @@ -402,6 +404,59 @@ impl Firmware { self.recovery_prepare_suspects(stage, event, asid) } + /// Decodes and logs every non-zero fault bank captured while firmware is halted in phase 1, + /// together with whether the faulting context matches any in-flight flight or open VM. + #[inline(never)] + fn log_recovery_faults(&self, scan: Option<&super::regs::FaultScan>, event: u32) { + let Some(scan) = scan else { + dev_warn!( + self.dev(), + "G16: fault_scan: GPU powered down (event={:#x}, flights={})\n", + event, + self.engine.flights.len() + ); + return; + }; + let mut nonzero = 0usize; + for entry in &scan.banks { + if entry.status == 0 { + continue; + } + nonzero += 1; + self.log_fault(entry); + let ctx = ((entry.status >> 17) & 0x3f) as u32; + let flight_matches = self + .engine + .flights + .iter() + .filter(|f| f.job.vm.slot == ctx) + .count(); + let live_vm = self.vms.find_by_slot(ctx); + dev_warn!( + self.dev(), + "G16: fault bank {} attribution: busy={} saved_bank={} ctx={} flight_matches={} live_vm={:?} event={:#x} flights={}\n", + entry.bank, + scan.busy, + scan.saved_bank, + ctx, + flight_matches, + live_vm, + event, + self.engine.flights.len() + ); + } + if nonzero == 0 { + dev_warn!( + self.dev(), + "G16: fault_scan: all 8 banks zero (busy={}, saved_bank={}, event={:#x}, flights={})\n", + scan.busy, + scan.saved_bank, + event, + self.engine.flights.len() + ); + } + } + fn recover(&mut self) -> Result { struct RecoveringGuard(Option>); impl Drop for RecoveringGuard { @@ -432,6 +487,7 @@ impl Firmware { } let now = now_ns(); if logic::expired(now, deadline) { + let _ = self.drain_auxiliary_rings(); // Which side stalled, and whether tiling or fragment work was left behind. let stage = self.recovery_snapshot().unwrap_or_default(); dev_err!( @@ -493,10 +549,13 @@ impl Firmware { self.events.grow.clear(); let stage = self.recovery_snapshot()?; // Powered down, the GPU holds no fault to read. - let fault = self.session.fault_scan()?.unwrap_or_default(); - let asid = Some(fault.status) - .filter(|status| status & 1 != 0) - .map(|status| ((status >> 17) & 0x3f) as u32) + let scan = self.session.fault_scan()?; + self.log_recovery_faults(scan.as_ref(), event); + let _ = self.drain_auxiliary_rings(); + let asid = scan + .as_ref() + .and_then(super::regs::FaultScan::first_latched) + .map(|fault| ((fault.status >> 17) & 0x3f) as u32) .filter(|asid| *asid >= 1); self.mark_recovery(stage, event, asid)?; // Snapshot reads and all TPC repairs precede acknowledgement. @@ -506,6 +565,7 @@ impl Firmware { answered = true; } RecoveryAction::Resume => { + let _ = self.drain_auxiliary_rings(); barrier(); self.firmware_w32(self.init.firmware_data().phase, 0)?; barrier(); @@ -514,6 +574,7 @@ impl Firmware { self.recovery.statistics_seen = self.events.recovery_statistics; self.events.recovery_started_ns = None; self.recovery.running = false; + self.recovery.fwlog_remaining = super::channel::RECOVERY_FWLOG_CAP; self.engine.frozen = false; self.renew_deadlines(); dev_warn!( @@ -539,10 +600,12 @@ impl Firmware { self.engine.flights.is_empty(), now.saturating_sub(start), ) { + let _ = self.drain_auxiliary_rings(); self.recovery.errors_seen = self.events.errors; self.recovery.statistics_seen = self.events.recovery_statistics; self.events.recovery_started_ns = None; self.recovery.running = false; + self.recovery.fwlog_remaining = super::channel::RECOVERY_FWLOG_CAP; self.engine.frozen = false; dev_warn!( self.dev(), diff --git a/drivers/gpu/drm/asahi/g16/regs.rs b/drivers/gpu/drm/asahi/g16/regs.rs index 74b8fd7a43417..225a0ed5d32d4 100644 --- a/drivers/gpu/drm/asahi/g16/regs.rs +++ b/drivers/gpu/drm/asahi/g16/regs.rs @@ -153,7 +153,7 @@ pub(crate) struct Identity { } /// Fault-bank selector values (`+0xd800`) that name a fault bank. -const FAULT_BANKS: u64 = 8; +pub(crate) const FAULT_BANKS: usize = 8; /// Engine receipts: busy bit and one fault bank. #[derive(Copy, Clone, Default)] @@ -177,6 +177,24 @@ impl EngineState { } } +/// Full eight-bank fault-register snapshot taken while firmware is halted for recovery. +#[derive(Copy, Clone, Default)] +pub(crate) struct FaultScan { + /// Bit 0 of `+0xc020 | +0xc120`. + pub(crate) busy: u64, + /// Selector (`+0xd800`) observed before scanning banks 0..7 and restored afterwards. + pub(crate) saved_bank: u64, + /// Raw status (`+0xd8c0`) and address (`+0xd8c8 << 6`) of each fault bank 0..7. + pub(crate) banks: [EngineState; FAULT_BANKS], +} + +impl FaultScan { + /// First bank whose latched fault bit (bit 0) is set. + pub(crate) fn first_latched(&self) -> Option<&EngineState> { + self.banks.iter().find(|entry| entry.status & 1 != 0) + } +} + /// G16 register access. pub(crate) struct Regs { /// The shared SGX mapping. @@ -313,29 +331,37 @@ impl Regs { }) } - /// Engine receipts for a firmware halted for recovery and waiting on the host: the first - /// fault bank, selectors 0 to 7 in order, whose status has bit 0 set, with the saved - /// selector restored. Without a fault, the status is zero and the bank the saved selector. - pub(crate) fn fault_scan(&self) -> Result { + /// Engine receipts for a firmware halted for recovery and waiting on the host: reads all + /// eight fault banks (selectors 0 to 7 in order), capturing status and address for every + /// non-zero bank, and restores the saved selector. + #[inline(never)] + pub(crate) fn fault_scan(&self) -> Result { let r = self.status.io(); let saved = r.try_read64(0x1800)?; - let mut state = EngineState { - busy: (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1, - bank: saved, - ..Default::default() + let busy = (r.try_read64(0x20)? | r.try_read64(0x120)?) & 1; + let mut scan = FaultScan { + busy, + saved_bank: saved, + banks: [EngineState::default(); FAULT_BANKS], }; - for bank in 0..FAULT_BANKS { + for (idx, entry) in scan.banks.iter_mut().enumerate() { + let bank = idx as u64; r.try_write64(bank, 0x1800)?; let status = r.try_read64(0x18c0)?; - if status & 1 != 0 { - state.bank = bank; - state.status = status; - state.address = r.try_read64(0x18c8)? << 6; - break; - } + let address = if status != 0 { + r.try_read64(0x18c8)? << 6 + } else { + 0 + }; + *entry = EngineState { + busy, + bank, + status, + address, + }; } r.try_write64(saved, 0x1800)?; - Ok(state) + Ok(scan) } } diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 0367a4421554c..7db8f5d799e12 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -341,6 +341,15 @@ impl Registry { .ok_or(ENOENT) } + /// The VM id of a live VM currently bound to TTBAT `slot`, if any. + pub(crate) fn find_by_slot(&self, slot: u32) -> Option { + self.vms + .lock() + .iter() + .find(|state| state.slot == slot) + .map(|state| state.id) + } + /// 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) {