From 6d406e1f54075ef702174c3cc3f00117bc0be383 Mon Sep 17 00:00:00 2001 From: Diljit Singh Date: Sat, 14 Nov 2026 11:19:22 -0500 Subject: [PATCH] drm/asahi: g17: grow a busy render pair's tiler heap ahead of the render The host grows a render pair's tiler heap ahead of a render only when the render is submitted to an idle pair: host_growth_target() returns early while the pair has work in flight, and leaves growth to the firmware. A pair that is never idle, because renders are queued back to back, keeps the heap its first render left. The next tiling pass then waits for the previous scene's pages to be freed instead of growing, so tiling and the previous fragment pass run one after the other. One drain of the pair is enough to size the heap for two scenes, after which they overlap. Grow a busy pair's heap ahead of the render as well, through the path a firmware grow request already takes while work is in flight: - the target is the layout's blocks (with the mesh floor), or the automatic target from the page high-water (three times the high-water once twice it no longer fits), capped at the heap's capacity. The high-water is read without requesting its reset, so the idle growth check and the shrink period keep their samples; - prepare_growth() without a descriptor snapshot, then commit_growth(): new blocks are appended to the inventory ring after the committed cursor and published by advancing it. The firmware-owned page list, PB state and PB descriptor are left alone and existing blocks never move. The firmware takes the new blocks without a grow reply; - the growth is skipped while the device's GPU memory, or the client's, would come within an eighth of its limit. A growth that cannot be prepared or committed keeps the heap and publishes the render as before. Either case retries a shrink period later; - the idle shrink may give busy growth back down to the size the heap had before it. That growth only serves renders in flight together. This applies to every heap of the block geometry the A18 Pro and the M4 Pro and Max share. M5 heaps have their own geometry and are never shrunk, so they keep growing on idle submissions only. Report every tiler heap size change through the asahi_g17_message tracepoint as kind 3: source << 56 | changed << 48 | blocks before << 24 | blocks after, with source 1 an idle host growth, 2 a busy host growth (changed 0: refused or failed), 3 a granted firmware request, 4 a refused or capped one and 5 a shrink. On the A18 Pro, rt.scene raster at queue depth 2 ran about 18 % faster in the first measurement of this change: the heap grows within the first frames instead of waiting for a drain. The light and medium presets were unchanged. Signed-off-by: Diljit Singh --- drivers/gpu/drm/asahi/g17/buffer.rs | 93 ++++++++++++++++++- drivers/gpu/drm/asahi/g17/queue/render.rs | 35 +++++-- .../gpu/drm/asahi/g17/runtime/render/grow.rs | 82 +++++++++++----- .../drm/asahi/g17/runtime/render/prepare.rs | 51 ++++++---- drivers/gpu/drm/asahi/g17/trace.rs | 19 +++- 5 files changed, 228 insertions(+), 52 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/buffer.rs b/drivers/gpu/drm/asahi/g17/buffer.rs index 2a3eadaafef40..2e2c79ae15123 100644 --- a/drivers/gpu/drm/asahi/g17/buffer.rs +++ b/drivers/gpu/drm/asahi/g17/buffer.rs @@ -336,6 +336,23 @@ fn automatic_target_for(used_pages: usize, current: usize, pages: usize, maximum ) } +/// Whether `bytes` more kernel memory keeps the device's GPU memory more than an +/// eighth below the device limit, and `client`'s committed memory more than an +/// eighth below the per-client limit (`memacct`). A busy pair's growth is only +/// ahead of need, so it never takes the device or a client close to a limit; +/// firmware grow requests still serve the pair. +fn busy_growth_admitted(bytes: u64, client: Option<&Arc>) -> bool { + let ledger = &crate::memacct::LEDGER; + let within = |used: u64, limit: u64| limit == 0 || used.saturating_add(bytes) <= limit - limit / 8; + within( + ledger.user_committed.load(Ordering::Relaxed) + .saturating_add(ledger.kernel_resident.load(Ordering::Relaxed)), + ledger.limit.load(Ordering::Relaxed), + ) && client.is_none_or(|client| { + within(client.committed(), ledger.client_limit.load(Ordering::Relaxed)) + }) +} + use super::object::{CpuMap, KernelObject}; use crate::{driver::AsahiDrmDevice, mmu}; use core::ops::Range; @@ -745,6 +762,14 @@ struct Shrink { window: [u32; SHRINK_WINDOW], window_next: usize, busy_peak: u32, + /// Blocks before the first growth the host made while the pair was busy, + /// since the last idle growth or the shrink that gave it back (0: none). + /// An idle shrink may return to this size: that growth only serves + /// renders overlapping in flight. + busy_base: usize, + /// Host ns before which a busy pair is not grown again after a growth + /// was refused or failed. + busy_retry: u64, } pub(crate) struct Submitted<'a> { @@ -964,6 +989,51 @@ impl Manager { Ok(automatic_target_for(pages as usize, self.blocks(), self.tvb.geometry.pages(), self.layout.normal_blocks)) } + /// The growth of a pair with work in flight ahead of a render that needs + /// `required` blocks at `now`: the layout's blocks, or the automatic target + /// from the page high-water since the last sample, which is read without + /// requesting its reset (the idle growth check and the shrink period own the + /// samples). None keeps the heap: the growth is not needed, waits for a + /// retry after a refusal, or would take the device or `client` within an + /// eighth of a memory limit (it is then retried a shrink period later). + pub(crate) fn busy_target( + &mut self, + required: usize, + now: u64, + client: Option<&Arc>, + ) -> Result> { + // Every heap of the block geometry the A18 Pro and the M4 Pro and Max share takes + // appended blocks while the firmware uses it, the path its grow requests take. M5 + // heaps have their own geometry and are never shrunk (`shrinkable`), so growth made + // for renders in flight together would never be given back. + if self.tvb.geometry != BlockGeometry::NEO || now < self.shrink.busy_retry { + return Ok(None); + } + let max_pages = self + .graph + .word(self.layout.control + core::mem::offset_of!(fw::Control, max_pages))?; + fence(Ordering::Acquire); + let pages = max_pages.load(Ordering::Relaxed) as usize; + let current = self.blocks(); + let feedback = automatic_target_for(pages, current, self.tvb.geometry.pages(), + self.layout.normal_blocks).unwrap_or(0); + let target = required.max(feedback).min(self.max_blocks()); + if target <= current { + return Ok(None); + } + let bytes = Tvb::backing_bytes(self.tvb.geometry, target - current)? as u64; + if !busy_growth_admitted(bytes, client) { + self.defer_busy_growth(now); + super::trace::heap(super::trace::HEAP_HOST_BUSY, false, current, current); + return Ok(None); + } + Ok(Some(target)) + } + /// A busy pair's growth was refused or failed at `now`: retry a shrink + /// period later. + pub(crate) fn defer_busy_growth(&mut self, now: u64) { + self.shrink.busy_retry = now.saturating_add(SHRINK_PERIOD_NS); + } /// Records the blocks a pass layout requires, the floor of any shrink. /// A pass is being prepared at `now`; the heap counts as busy. pub(crate) fn note_required(&mut self, blocks: usize, now: u64) { @@ -977,7 +1047,22 @@ impl Manager { let recent = (self.shrink.busy_peak as usize) .saturating_mul(2) .div_ceil(cfg::TVB_PAGES_PER_BLOCK); - self.tvb.primary_blocks().max(self.shrink.required).max(recent) + let minimum = self.tvb.primary_blocks().max(self.shrink.required); + // Growth made while the pair was busy goes back down to the size it had + // before, also below the recent peak, which counts renders in flight + // together. + let busy = if self.shrink.busy_base != 0 { + minimum.max(self.shrink.busy_base) + } else { + usize::MAX + }; + minimum.max(recent).min(busy) + } + /// The host grew this heap from `previous` blocks while the pair was busy. + pub(crate) fn note_busy_growth(&mut self, previous: usize) { + if self.shrink.busy_base == 0 { + self.shrink.busy_base = previous; + } } /// Whether the heap holds growth beyond its primary backing. /// M5 heaps are never shrunk. @@ -1220,6 +1305,8 @@ impl Manager { write(at + 4, 0); } if descriptor.is_some() { + // An idle growth sizes the heap for the recent load, busy growth included. + self.shrink.busy_base = 0; for (entry, value) in rebuilt.into_iter().enumerate() { write(self.layout.pages + entry * 4, value); } @@ -1335,6 +1422,10 @@ impl Manager { } } self.shrink.credit = self.shrink.credit.saturating_sub(blocks - kept); + if kept <= self.shrink.busy_base { + self.shrink.busy_base = 0; + } + super::trace::heap(super::trace::HEAP_SHRINK, true, blocks, kept); Ok(Some(( fw::reload_descriptor(descriptor, self.page_list_client, pages), release, diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index b59a9301044c9..64d3f50a5df9d 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -186,6 +186,16 @@ pub(crate) enum Registration { M5(crate::g17::fw::m5::queue::HardwareSubmission), } +/// A tiler heap growth the host makes before publishing a render, to this many blocks. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub(crate) enum HostGrowth { + /// The pair is idle: the page list and the PB descriptor are rebuilt. + Idle(usize), + /// The pair has work in flight: blocks are only appended to the inventory, + /// as for a firmware grow request. + Busy(usize), +} + /// Installed kick backing remains owned even when this pair has no logical /// owner. Commands retain their exact descriptor and allocation generations. pub(crate) struct Pair { @@ -1793,9 +1803,11 @@ impl Pair { pub(crate) fn oldest_packet(&self) -> Option> { self.active.front().map(|active| active.packet.clone()) } - /// Sample PM feedback only after this pair's exact retirement. Busy pairs - /// keep their current capacity and let firmware request growth as needed. - pub(crate) fn host_growth_target(&mut self, packet: &Packet) -> Result> { + /// Sample PM feedback only after this pair's exact retirement. A busy pair + /// grows ahead of the render only by appending blocks to its inventory, as a + /// firmware grow request does (`buffer::Manager::busy_target`), and otherwise + /// keeps its current capacity and lets firmware request growth as needed. + pub(crate) fn host_growth_target(&mut self, packet: &Packet) -> Result> { let mut required = m5_render_submission::layout(&packet.command, self.clusters, self.variant.programs)? .tvb_blocks; @@ -1810,11 +1822,18 @@ impl Pair { required = required.max(floor); } } - self.memory - .manager - .note_required(required, crate::g17::now_ns()); + let now = crate::g17::now_ns(); + self.memory.manager.note_required(required, now); if self.in_flight() { - return Ok(None); + if self.quarantined { + return Ok(None); + } + let client = self.memory.context.vm().memory_client().cloned(); + return Ok(self + .memory + .manager + .busy_target(required, now, client.as_ref())? + .map(HostGrowth::Busy)); } if !self.idle_for_context(self.context())? { return Err(EBUSY); @@ -1830,7 +1849,7 @@ impl Pair { // ERANGE: a 16384x16384 no-attachment render after smaller ones lost the device // (dEQP-GLES31.functional.fbo.no_attachments.maximums.*). let required = required.max(feedback).min(self.memory.manager.max_blocks()); - Ok((required > self.memory.manager.blocks()).then_some(required)) + Ok((required > self.memory.manager.blocks()).then_some(HostGrowth::Idle(required))) } /// A quarantined pair, or a closed owner's pair that holds only groups whose stamps are diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs b/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs index 62d7afada3e4b..c096970ded545 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/grow.rs @@ -293,10 +293,15 @@ impl crate::g17::Firmware { } impl crate::g17::Firmware { + /// Commits a host growth prepared for the pair in `slot`. A `busy` pair's + /// growth only appends blocks to the inventory, as a firmware grow request's + /// does; if it cannot be committed the pair keeps its heap and the render + /// is published as it would have been without it. pub(super) fn commit_render_growth( &mut self, slot: u8, prepared: &mut Option, + busy: bool, ) -> Result { if prepared.is_none() { return Ok(()); @@ -308,28 +313,45 @@ impl crate::g17::Firmware { .pair .as_mut() .ok_or(EIO)?; - let vm = pair.context().vm().clone(); - let pool = pair.pool_id(); - let buffer_id = pair.buffer_id(); - // Preflight every destination before the graph starts publishing. - let table = self.init.pb_descriptor_table()?; - let offset = usize::from(buffer_id) * 16; - let words = [ - table.word(offset)?, - table.word(offset + 4)?, - table.word(offset + 8)?, - table.word(offset + 12)?, - ]; - let descriptor = pair - .manager() - .commit_growth(prepared, |previous, blocks, mappings| { - vm.append_render_pool_mappings_prepared(slot, pool, previous, blocks, mappings) - })?; - if let Some(descriptor) = descriptor { - for (word, value) in words.into_iter().zip(descriptor) { - word.store(value, Ordering::Relaxed); + let previous = pair.manager().blocks(); + let source = if busy { + crate::g17::trace::HEAP_HOST_BUSY + } else { + crate::g17::trace::HEAP_HOST_IDLE + }; + let committed: Result = (|| { + let vm = pair.context().vm().clone(); + let pool = pair.pool_id(); + let buffer_id = pair.buffer_id(); + // Preflight every destination before the graph starts publishing. + let table = self.init.pb_descriptor_table()?; + let offset = usize::from(buffer_id) * 16; + let words = [ + table.word(offset)?, + table.word(offset + 4)?, + table.word(offset + 8)?, + table.word(offset + 12)?, + ]; + let descriptor = pair + .manager() + .commit_growth(prepared, |previous, blocks, mappings| { + vm.append_render_pool_mappings_prepared(slot, pool, previous, blocks, mappings) + })?; + if let Some(descriptor) = descriptor { + for (word, value) in words.into_iter().zip(descriptor) { + word.store(value, Ordering::Relaxed); + } + fence(Ordering::SeqCst); } - fence(Ordering::SeqCst); + Ok(()) + })(); + let manager = pair.manager(); + crate::g17::trace::heap(source, committed.is_ok(), previous, manager.blocks()); + match committed { + Ok(()) if busy => manager.note_busy_growth(previous), + // The prepared growth is dropped by the caller after the device mutex. + Err(_) if busy => manager.defer_busy_growth(crate::g17::now_ns()), + committed => committed?, } Ok(()) } @@ -383,13 +405,13 @@ impl crate::g17::Shared { render.grow.active = Some(request); (request, slot, pair) }; + let before = pair.as_mut().map_or(0, |pair| pair.manager().blocks()); let prepared = match pair.as_mut() { Some(pair) => { let vm = pair.context().vm().clone(); let pool = pair.pool_id(); let slot = pair.slot(); let manager = pair.manager(); - let before = manager.blocks(); if vm.render_pool_tvb_blocks(slot, pool) != Some(before) { Err(EFAULT) } else { @@ -465,6 +487,22 @@ impl crate::g17::Shared { false } }; + // A refused or capped request leaves the tiling pass to partial-render + // within the heap it has. + let after = slot + .and_then(|slot| firmware.queues.render.entries[slot].as_mut()) + .and_then(|entry| entry.pair.as_mut()) + .map_or(before, |pair| pair.manager().blocks()); + crate::g17::trace::heap( + if grew { + crate::g17::trace::HEAP_FIRMWARE_GRANTED + } else { + crate::g17::trace::HEAP_FIRMWARE_REFUSED + }, + grew, + before, + after, + ); firmware.queues.render.grow.reply = Some((request, grew, 0)); if !firmware.flush_tvb_reply()? { return Ok(()); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 71f6e4b5943a2..dc05f1f0ef5ba 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -10,7 +10,7 @@ use crate::g17::{ preparation::Lease, job::Packet, object::{Allocator, KernelObject, Pool}, - queue::render::{Pair, RenderAddresses}, + queue::render::{HostGrowth, Pair, RenderAddresses}, }; use kernel::{prelude::*, sync::Arc}; @@ -898,19 +898,23 @@ impl super::super::Backend { packet.context.mark_published(); let target = pair.host_growth_target(packet)?; let buffer_id = pair.buffer_id(); - let growth_target = if let Some(target) = target { - let table = firmware.init.pb_descriptor_table()?; - let offset = usize::from(buffer_id) * 16; - core::sync::atomic::fence(core::sync::atomic::Ordering::Acquire); - let mut descriptor = [0; 4]; - for (index, word) in descriptor.iter_mut().enumerate() { - *word = table - .word(offset + index * 4)? - .load(core::sync::atomic::Ordering::Relaxed); + let growth_target = match target { + Some(HostGrowth::Idle(target)) => { + let table = firmware.init.pb_descriptor_table()?; + let offset = usize::from(buffer_id) * 16; + core::sync::atomic::fence(core::sync::atomic::Ordering::Acquire); + let mut descriptor = [0; 4]; + for (index, word) in descriptor.iter_mut().enumerate() { + *word = table + .word(offset + index * 4)? + .load(core::sync::atomic::Ordering::Relaxed); + } + Some((target, Some(descriptor))) } - Some((target, descriptor)) - } else { - None + // A busy pair's firmware owns its page list and PB descriptor: + // the growth only appends blocks to the inventory. + Some(HostGrowth::Busy(target)) => Some((target, None)), + None => None, }; let pair = firmware.queues.render.take_pair(slot, self.owner, packet)?; (firmware.uat.clone(), pair, addresses, growth_target) @@ -920,15 +924,22 @@ impl super::super::Backend { uat: &uat, }; let mut growth = None; + let busy = matches!(growth_target, Some((_, None))); let result = (|| { if let Some((target, descriptor)) = growth_target { let vm = pair.context().vm().clone(); - growth = pair.manager().prepare_growth( - &dev, - &vm, - target, - Some(descriptor), - )?; + match pair.manager().prepare_growth(&dev, &vm, target, descriptor) { + Ok(prepared) => growth = prepared, + // A busy pair keeps its heap; firmware grow requests still serve it. + Err(_) if busy => { + let manager = pair.manager(); + manager.defer_busy_growth(crate::g17::now_ns()); + let blocks = manager.blocks(); + crate::g17::trace::heap(crate::g17::trace::HEAP_HOST_BUSY, false, + blocks, blocks); + } + Err(error) => return Err(error), + } } pair.prepare(&alloc, packet, addresses) })(); @@ -967,7 +978,7 @@ impl super::super::Backend { } // Private restaging can fail after preparing a larger inventory. // Finish its descriptor before discarding the command preparation. - firmware.commit_render_growth(slot, &mut growth)?; + firmware.commit_render_growth(slot, &mut growth, busy)?; result?; if packet.cancel_requested() || firmware.queues.render.entry(slot)?.closed { return Err(ECANCELED); diff --git a/drivers/gpu/drm/asahi/g17/trace.rs b/drivers/gpu/drm/asahi/g17/trace.rs index e3f9dfdd1052d..963bbf3470721 100644 --- a/drivers/gpu/drm/asahi/g17/trace.rs +++ b/drivers/gpu/drm/asahi/g17/trace.rs @@ -92,12 +92,29 @@ pub(super) const CONTROL: u8 = 1; pub(super) const EFFORT: u8 = 2; /// A host-to-firmware message: a mailbox message, a device-control record by -/// opcode, or a new performance effort value. +/// opcode, a new performance effort value, or a tiler heap size change. pub(super) fn message(kind: u8, value: u64) { // SAFETY: Plain values only. unsafe { asahi_g17_trace_message(kind, value) }; } +/// `message` kind of a tiler heap size change ([`heap`]). +pub(super) const HEAP: u8 = 3; +pub(super) const HEAP_HOST_IDLE: u8 = 1; +pub(super) const HEAP_HOST_BUSY: u8 = 2; +pub(super) const HEAP_FIRMWARE_GRANTED: u8 = 3; +pub(super) const HEAP_FIRMWARE_REFUSED: u8 = 4; +pub(super) const HEAP_SHRINK: u8 = 5; + +/// A tiler heap growth or shrink of `source` (HEAP_*), as a `message` of kind +/// [`HEAP`]: `source << 56 | grew << 48 | blocks_before << 24 | blocks_after`. +/// `grew` is whether the heap changed (a shrink that applied sets it too). +pub(super) fn heap(source: u8, grew: bool, before: usize, after: usize) { + let blocks = |blocks: usize| (blocks as u64) & 0xff_ffff; + message(HEAP, u64::from(source) << 56 | u64::from(grew) << 48 | blocks(before) << 24 + | blocks(after)); +} + /// Failed-context teardown: 1 compute fault (qid, stamp), 2 unstamped render retire (slot, /// ordinal), 3 kill published (cookie, context, held slots | 1 if it skipped the wait for other /// contexts' compute under memory pressure; slot 0 is never held), 4 kill acknowledged (cookie,