From 7ff8f5a440624d134cbe56854d413d3840cabce0 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 14:48:39 -0300 Subject: [PATCH 01/13] drm/asahi: g17: build a compute queue's objects apart from its QID A fresh G17 compute queue was built for the QID publication reserves: the pool's control header names the QID's pool slot, and the kick ring carries the QID. So its objects could only be allocated once the QID was known, at publication, after SUBMIT accepted the job. Only stores depend on the QID. Split construction in two: - **Allocate:** `compute::Kit::new` allocates the pool's control and state (`freelist::PoolObjects`), the kick ring storage (`kick::ComputeRing`) and the graph's objects (`GraphObjects`), with no QID. The pool pages and the descriptor ring are allocated as before. - **Bind:** `compute::Queue::new_channel(kit, pages, ring, id, ...)` binds them to the QID: `ComputePool::bind` writes the control header, `kick::Queue::compute` keeps the id and `Graph::new` writes the owner's queue record. No device memory is allocated. Publication still calls both, in the same order of effects: the pool's row is installed before the queue is built. A later change allocates in SUBMIT. tools/asahi/g17-compute-reserve-tests.py checks that the bind steps allocate nothing, with two mutations that inject an allocation. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/freelist.rs | 45 +++--- drivers/gpu/drm/asahi/g17/kick.rs | 24 ++- drivers/gpu/drm/asahi/g17/queue/compute.rs | 159 ++++++++++++-------- drivers/gpu/drm/asahi/g17/runtime.rs | 40 ++--- tools/asahi/g17-compute-reserve-tests.py | 99 ++++++++++++ tools/asahi/g17-m5-sibling-compute-tests.py | 6 +- tools/asahi/g17-m5-sibling-rearm-tests.py | 2 +- tools/asahi/run-host-tests.py | 2 + 8 files changed, 266 insertions(+), 111 deletions(-) create mode 100644 tools/asahi/g17-compute-reserve-tests.py diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index 017f6d03b2013..9fcd45ae281b4 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -1043,6 +1043,23 @@ impl Submitted<'_> { /// that VM's work, so a view of it in another VM is refused /// ([`Self::map_client`]). Another VM gets the queue only after the backing /// was given back and fresh, zeroed backing installed ([`Self::rearm`]). +/// The control and state objects of a compute pool, allocated before a QID is reserved for it. +pub(crate) struct PoolObjects { + control: KernelObject, + state: KernelObject, +} +impl PoolObjects { + pub(crate) fn new(alloc: &Allocator<'_>) -> Result { + let object = || alloc.kernel( + CONTROL_SIZE, + mmu::UAT_PGSZ as u64, + mmu::PROT_GPU_FW_SHARED_RW, + CpuMap::WriteCombined, + ); + Ok(Self { control: object()?, state: object()? }) + } +} + pub(crate) struct ComputePool { pages: Option, /// The VM (`mmu::Vm::id`) the backing serves, from its first client view @@ -1059,34 +1076,22 @@ impl ComputePool { self.pages.as_ref().is_some_and(|pages| pages.fits_capacity(required)) } - /// A pool at the admitted capacity, in the capacity's family format. - pub(crate) fn new(alloc: &Allocator<'_>, qid: u8, required: ComputeCapacity, - client: Option<&Arc>) -> Result { + /// Binds `objects` and `pages` to the pool slot of `qid`: stores only. + pub(crate) fn bind(objects: PoolObjects, qid: u8, pages: Pages) -> Result { if qid > super::fw::kick::QID_MAX { return Err(EINVAL); } - let pages = Pages::for_compute(alloc, required, client)?; + let PoolObjects { mut control, state } = objects; + let id = Self::slot(qid); let m5 = pages.is_m5(); - Self::with_pages(alloc, qid, m5, pages) - } - fn with_pages(alloc: &Allocator<'_>, qid: u8, m5: bool, pages: Pages) -> Result { - let id = u16::from(qid) + 1; - let mut control = alloc.kernel( - CONTROL_SIZE, - mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_FW_SHARED_RW, - CpuMap::WriteCombined, - )?; - let state = alloc.kernel( - CONTROL_SIZE, - mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_FW_SHARED_RW, - CpuMap::WriteCombined, - )?; Self::initialize_control(&mut control, &pages, id, state.gpu_va(), [0; 8])?; fence(Ordering::SeqCst); Ok(Self { pages: Some(pages), client_vm: 0, control, state, id, m5 }) } + /// The pool slot (buffer slot) of `qid`'s pool. + pub(crate) fn slot(qid: u8) -> u16 { + u16::from(qid) + 1 + } fn initialize_control(control: &mut KernelObject, pages: &Pages, id: u16, submitted: u64, completed: [u8; 8]) -> Result { match pages.layout { diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 43e1115f221f0..8915bd9fef3fa 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -622,11 +622,14 @@ impl PreparedKick<'_> { } } -impl Queue { - pub(crate) fn compute(alloc: &Allocator<'_>, id: Id) -> Result { - if id.engine != DataMaster::Compute { - return Err(EINVAL); - } +/// Storage of a compute queue's kick ring, allocated before a QID is reserved for it. +pub(crate) struct ComputeRing { + high: mmu::KernelMapping, + low: KernelObject, +} + +impl ComputeRing { + pub(crate) fn new(alloc: &Allocator<'_>) -> Result { let low = alloc.lower( KICK_RING_SIZE, mmu::UAT_PGSZ as u64, @@ -641,6 +644,17 @@ impl Queue { mmu::PROT_FW_SHARED_RW, )?; fence(Ordering::SeqCst); + Ok(Self { high, low }) + } +} + +impl Queue { + /// Binds `ring` to the QID of `id`: stores only. + pub(crate) fn compute(ring: ComputeRing, id: Id) -> Result { + if id.engine != DataMaster::Compute { + return Err(EINVAL); + } + let ComputeRing { high, low } = ring; Ok(Self { backing: Backing::Compute { high, low }, id, diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 968ca6a9bf012..c266b62c73870 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -168,22 +168,31 @@ struct Graph { mcache: bool, } -impl Graph { +/// The firmware-shared objects of one compute QID but its descriptor ring, allocated before a +/// QID is reserved for them. None names an owner yet. +pub(crate) struct GraphObjects { + preempt: KernelObject, + usage: KernelObject, + operand: KernelObject, + support: KernelObject, + m5_timestamps: Option>, + graph: KernelObject, + context_low: Option, + context_high: Option, + records: KernelObject, + cached_records: PooledObject, +} + +impl GraphObjects { fn new( alloc: &Allocator<'_>, objects: &Arc, - context: &Context, - pointers: PointerLayout, operand_state: &'static OperandState, - board: Option<&'static Board>, - program: ComputeProgram, m5: bool, - mcache: bool, ) -> Result { let page = mmu::UAT_PGSZ as u64; let prot = mmu::PROT_GPU_FW_SHARED_RW; let cpu = CpuMap::WriteCombined; - let ring = DescriptorRing::new(alloc, objects)?; let preempt = alloc.kernel(0x4000, page, prot, cpu)?; let usage = alloc.kernel(mmu::UAT_PGSZ, page, prot, cpu)?; let operand = alloc.lower(operand_state.size, page, prot, cpu)?; @@ -204,7 +213,47 @@ impl Graph { // so dirty firmware lines would revert host updates. An installed // compute graph lives until firmware stop and does not need the reuse // pool. - let mut graph = alloc.kernel(GRAPH_SIZE + mmu::UAT_PGSZ, page, prot, cpu)?; + let graph = alloc.kernel(GRAPH_SIZE + mmu::UAT_PGSZ, page, prot, cpu)?; + let (context_low, context_high) = if m5 { (None, None) } else { + (Some(alloc.lower(CONTEXT_SIZE, page, prot, cpu)?), + Some(alloc.kernel(CONTEXT_SIZE, page, prot, cpu)?)) + }; + let records = alloc.kernel(RECORD_SLOTS * RECORD_STRIDE, page, prot, cpu)?; + let m5_timestamps = if m5 { + Some(Arc::new(alloc.kernel(RECORD_SLOTS * 16, page, prot, cpu)?, GFP_KERNEL)?) + } else { None }; + let cached_records = objects.allocate( + alloc, + Family::QueueConfig, + RECORD_SLOTS * CACHED_RECORD_STRIDE, + RECORD_SLOTS * CACHED_RECORD_STRIDE, + prot, + cpu, + )?; + Ok(Self { + preempt, usage, operand, support, m5_timestamps, graph, context_low, context_high, + records, cached_records, + }) + } +} + +impl Graph { + /// Writes `context`'s queue record into `objects`: stores only. + fn new( + objects: GraphObjects, + ring: DescriptorRing, + context: &Context, + pointers: PointerLayout, + operand_state: &'static OperandState, + board: Option<&'static Board>, + program: ComputeProgram, + m5: bool, + mcache: bool, + ) -> Result { + let GraphObjects { + preempt, usage, operand, support, m5_timestamps, mut graph, context_low, context_high, + records, cached_records, + } = objects; let graph_va = graph.gpu_va(); graph.initialize::(0, |view| { view.pointers = PointerBlock::new(&pointers)?; @@ -230,22 +279,6 @@ impl Graph { } else { graph.write(0, QueueRecord::new(&record))?; } - let (context_low, context_high) = if m5 { (None, None) } else { - (Some(alloc.lower(CONTEXT_SIZE, page, prot, cpu)?), - Some(alloc.kernel(CONTEXT_SIZE, page, prot, cpu)?)) - }; - let records = alloc.kernel(RECORD_SLOTS * RECORD_STRIDE, page, prot, cpu)?; - let m5_timestamps = if m5 { - Some(Arc::new(alloc.kernel(RECORD_SLOTS * 16, page, prot, cpu)?, GFP_KERNEL)?) - } else { None }; - let cached_records = objects.allocate( - alloc, - Family::QueueConfig, - RECORD_SLOTS * CACHED_RECORD_STRIDE, - RECORD_SLOTS * CACHED_RECORD_STRIDE, - prot, - cpu, - )?; Ok(Self { m5, ring: Some(ring), @@ -590,39 +623,34 @@ struct ConfigIdentity { context: u32, } -/// A private physical pool whose descriptor row is installed before allocating its kick ring. -/// The QID remains unpublished throughout construction. -pub(crate) struct PoolBacking { - pool: ComputePool, - id: kick::Id, +/// Everything a fresh compute queue needs but its pool pages and descriptor ring: the pool's +/// control and state, the kick ring and the graph's objects. Allocated before a QID is reserved +/// for it; [`Queue::new_channel`] binds it to one with stores only. Device memory: an installed +/// queue keeps it until processor stop, past its first owner. +pub(crate) struct Kit { + pool: crate::g17::freelist::PoolObjects, + kick: kick::ComputeRing, + graph: GraphObjects, } -impl PoolBacking { - pub(crate) fn new(alloc: &Allocator<'_>, id: kick::Id, required: ComputeCapacity, - client: Option<&Arc>) -> Result { - let pool = ComputePool::new(alloc, id.qid(), required, client)?; - Ok(Self { pool, id }) - } - - /// Fresh page-pool row data, installed once while the QID is still unpublished. - pub(crate) fn pool_descriptor(&self) -> Result { - self.pool.descriptor() +impl Kit { + pub(crate) fn new( + alloc: &Allocator<'_>, + objects: &Arc, + operand_state: &'static OperandState, + m5: bool, + ) -> Result { + Ok(Self { + pool: crate::g17::freelist::PoolObjects::new(alloc)?, + kick: kick::ComputeRing::new(alloc)?, + graph: GraphObjects::new(alloc, objects, operand_state, m5)?, + }) } } -/// A physical pool and kick ring prepared before the device-global compute scheduler and -/// descriptor graph. No logical VM aliases or firmware publication exist at this stage. -pub(crate) struct Backing { - pool: ComputePool, - kick: kick::Queue, -} - -impl Backing { - pub(crate) fn new(alloc: &Allocator<'_>, backing: PoolBacking) -> Result { - let PoolBacking { pool, id } = backing; - let kick = kick::Queue::compute(alloc, id)?; - Ok(Self { pool, kick }) - } +/// The page-pool row of a fresh queue's pool at QID `qid`, installed before the queue is built. +pub(crate) fn pool_descriptor(pages: &crate::g17::freelist::Pages, qid: u8) -> Result { + pages.descriptor(ComputePool::slot(qid)) } /// Installed graph and its exact logical owner. A released idle graph may change owners only @@ -747,9 +775,10 @@ impl Queue { /// The caller reserves a QID first, cancels it on construction failure, and retains every /// successfully installed queue until processor stop. Shared VM apertures precede this call. pub(crate) fn new( - alloc: &Allocator<'_>, - objects: &Arc, - backing: Backing, + kit: Kit, + pages: crate::g17::freelist::Pages, + ring: DescriptorRing, + id: kick::Id, owner: u64, context: Arc, pointers: PointerLayout, @@ -760,9 +789,10 @@ impl Queue { mcache: bool, ) -> Result { Self::new_channel( - alloc, - objects, - backing, + kit, + pages, + ring, + id, owner, context, pointers, @@ -781,9 +811,10 @@ impl Queue { identity." )] pub(crate) fn new_channel( - alloc: &Allocator<'_>, - objects: &Arc, - backing: Backing, + kit: Kit, + pages: crate::g17::freelist::Pages, + ring: DescriptorRing, + id: kick::Id, owner: u64, context: Arc, pointers: PointerLayout, @@ -794,10 +825,12 @@ impl Queue { mcache: bool, channel_index: u8, ) -> Result { - let Backing { mut pool, mut kick } = backing; + let Kit { pool, kick, graph } = kit; + let mut pool = ComputePool::bind(pool, id.qid(), pages)?; + let mut kick = kick::Queue::compute(kick, id)?; let (active, replays) = (Fifo::new()?, Fifo::new()?); let mut graph = - Graph::new(alloc, objects, &context, pointers, operand_state, board, program, m5, mcache)?; + Graph::new(graph, ring, &context, pointers, operand_state, board, program, m5, mcache)?; let kick_alias = kick.map_client(context.vm())?; let pool_alias = Some(pool.map_client(context.vm())?); let binding = graph.bind(context.clone(), kick_alias, pool_alias)?; diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index c11fdbac73040..1f77faebf42a9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2002,8 +2002,11 @@ impl Backend { } }; let built = (|| { - let pool = compute::PoolBacking::new(&alloc, reservation.id, required, + let pages = super::freelist::Pages::for_compute(&alloc, required, self.context.vm().memory_client())?; + let ring = compute::DescriptorRing::new(&alloc, &objects)?; + let kit = compute::Kit::new(&alloc, &objects, self.shared.operand_state, + alloc.uat.is_m5())?; { let mut state = self.shared.state.lock(); admission.check()?; @@ -2013,19 +2016,19 @@ impl Backend { } self.admission_open()?; firmware.queues.reserved(reservation)?; - firmware.init.install_compute_pool(pool.pool_descriptor()?)?; + firmware.init.install_compute_pool( + compute::pool_descriptor(&pages, reservation.id.qid())?)?; } - let backing = compute::Backing::new(&alloc, pool)?; - // The global scheduler is created after pool/kick backing and - // retained even if this queue's later descriptor graph fails. + // The global scheduler is retained even if this queue's graph fails. // It is G17P compute state; M5 has none. if !self.context.is_m5() { self.compute_scheduler(&alloc, &lease, admission)?; } let queue = compute::Queue::new( - &alloc, - &objects, - backing, + kit, + pages, + ring, + reservation.id, self.owner, self.context.clone(), self.shared.variant.pointers, @@ -2184,12 +2187,10 @@ impl Backend { } }; let built = (|| { - let pool = compute::PoolBacking::new( - &alloc, - reservation.id, - required, - self.context.vm().memory_client(), - )?; + let pages = super::freelist::Pages::for_compute(&alloc, required, + self.context.vm().memory_client())?; + let ring = compute::DescriptorRing::new(&alloc, &objects)?; + let kit = compute::Kit::new(&alloc, &objects, self.shared.operand_state, true)?; { let mut state = self.shared.state.lock(); admission.check()?; @@ -2199,13 +2200,14 @@ impl Backend { } self.admission_open()?; firmware.queues.reserved(reservation)?; - firmware.init.install_compute_pool(pool.pool_descriptor()?)?; + firmware.init.install_compute_pool( + compute::pool_descriptor(&pages, reservation.id.qid())?)?; } - let backing = compute::Backing::new(&alloc, pool)?; let queue = compute::Queue::new_channel( - &alloc, - &objects, - backing, + kit, + pages, + ring, + reservation.id, self.owner, self.context.clone(), self.shared.variant.pointers, diff --git a/tools/asahi/g17-compute-reserve-tests.py b/tools/asahi/g17-compute-reserve-tests.py new file mode 100644 index 0000000000000..8309132eb3e08 --- /dev/null +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""A compute queue's objects are allocated apart from the QID they are bound to. + +A fresh G17 compute queue is built for a QID that publication reserves from +firmware state. Its objects (the pool's control and state, the kick ring, the +graph's objects: `compute::Kit`; the pool pages and descriptor ring) are +allocated without one, and binding them to the QID only stores: + +- `ComputePool::bind`, `kick::Queue::compute`, `Graph::new` and + `Queue::new_channel` allocate no device memory; +- `Kit::new` allocates the kit through an Allocator. + +--mutation allocating-bind / allocating-graph inject an allocation into a bind +step and must be caught. +""" +import argparse +import re +import sys +from pathlib import Path + +G17 = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' +# Calls that allocate device memory (or build an Allocator for it). +ALLOCATING = re.compile(r'\balloc\b|Allocator\s*\{|\.allocate\(|KernelObject::|for_compute\(|' + r'DescriptorRing::new\(|Kit::new\(|PoolObjects::new\(|ComputeRing::new\(|' + r'GraphObjects::new\(|ComputeShared::new\(|ComputeScheduler::new\(') + + +def item(text, signature): + start = text.index(signature) + begin = text.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +def code(text): + return '\n'.join(l.split('//')[0] for l in text.split('\n')) + + +def sources(mutation): + files = {name: (G17 / name).read_text() for name in + ['freelist.rs', 'kick.rs', 'queue/compute.rs', 'runtime.rs', 'runtime/backend.rs']} + if mutation == 'allocating-bind': + files['freelist.rs'] = files['freelist.rs'].replace( + ' let PoolObjects { mut control, state } = objects;', + ' let PoolObjects { mut control, state } = objects;\n' + ' let _ = alloc.kernel(CONTROL_SIZE, 0, mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined);', 1) + elif mutation == 'allocating-graph': + files['queue/compute.rs'] = files['queue/compute.rs'].replace( + ' let graph_va = graph.gpu_va();', + ' let ring = DescriptorRing::new(alloc, objects)?;\n let graph_va = graph.gpu_va();', 1) + return files + + +# (file, signature, why it must not allocate) +BINDS = [ + ('freelist.rs', 'pub(crate) fn bind(objects: PoolObjects', 'binding pool objects to a QID'), + ('kick.rs', 'pub(crate) fn compute(ring: ComputeRing', 'binding a kick ring to a QID'), + ('queue/compute.rs', 'impl Graph {\n /// Writes', "writing an owner's queue record"), + ('queue/compute.rs', 'pub(crate) fn new_channel(', 'assembling a fresh queue'), +] + + +def check(files): + failures = [] + for name, signature, why in BINDS: + text = files[name] + if signature not in text: + failures.append(f'FAIL line 0: {name}: {signature!r} is missing') + continue + body = item(text, signature) + if signature.startswith('impl Graph'): + body = item(body, 'fn new(') + for m in ALLOCATING.finditer(code(body)): + line = text.count('\n', 0, text.index(signature)) + code(body).count('\n', 0, m.start()) + 1 + failures.append(f'FAIL line {line}: {name}: {why} allocates ({m.group(0)})') + kit = files['queue/compute.rs'] + if 'impl Kit {' not in kit or 'GraphObjects::new(alloc' not in item(kit, 'impl Kit {'): + failures.append('FAIL line 0: queue/compute.rs: Kit::new does not allocate the graph objects') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['allocating-bind', 'allocating-graph']) + args = parser.parse_args() + failures = check(sources(args.mutation)) + for f in failures: + print(f) + if failures: + sys.exit(1) + print('ok: compute queue objects are allocated apart from their QID, and binding only stores') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py index 5348ee32380c5..f0bd1bc986cc1 100755 --- a/tools/asahi/g17-m5-sibling-compute-tests.py +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -13,7 +13,7 @@ 2. Dedicated per-sibling `ComputePool` (no `PoolBorrow`, no shared `0x7c/0x80` pool control contention): a warm reusable sibling requires a same-VM populated fitting pool, a vacant or other-VM idle queue is re-armed with - fresh backing, and a fresh sibling allocates its own `PoolBacking::new` + + fresh backing, and a fresh sibling allocates its own `Kit::new` + pool descriptor (g17-m5-sibling-rearm-tests.py runs the re-arm path). 3. Lock-free `ComputeCell` atomic `(configuring, active_len, last_published)` mirror updated via `QueueGuard::drop()`, with primary-first routing in @@ -178,8 +178,8 @@ def build_harness(mutation=None): 'PoolBorrow' not in freelist_src and 'PoolBorrow' not in queue_src and 'shared_pool' not in queue_src - and 'PoolBacking::new(' in try_add_sib_fn - and 'install_compute_pool(pool.pool_descriptor()?)' in try_add_sib_fn + and 'compute::Kit::new(' in try_add_sib_fn + and 'compute::pool_descriptor(&pages, reservation.id.qid())?' in try_add_sib_fn and ordered_ok(source_fn, 'if queue.pool_vacant() {', '} else if queue.pool_serves(vm) {', '!queue.pool_fits(required)', '&mut warm') and 'let Some(SiblingSource::Warm(qid)) = self.sibling_source(owner, context, required) else' in bind_sib_fn diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index f690f4473cd17..079c206368a34 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -218,7 +218,7 @@ def build(mutation=None): 'Some(SiblingSource::Fresh) =>', 'reserve_compute_channel(self.owner, self.compute_channels)', 'Err(qid) => {', 'self.rearm_vacant(\n qid,\n channel_index,\n required,', 'if !bound {', 'firmware.queues.release_rearm(qid, self.owner);', 'admission.check()?;', - 'return Ok(bound);', 'compute::PoolBacking::new('), + 'return Ok(bound);', 'compute::Kit::new('), 'a re-arm binds the channel it was reserved for, through the primary path': ordered_ok( rearm_vacant, 'crate::g17::freelist::Pages::for_compute(', 'compute::DescriptorRing::new(', 'let mut state = self.shared.state.lock();', 'if !lease.is_current()', 'self.admission_open()', diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index da9196faf2e54..12097e0ee799d 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -318,6 +318,8 @@ def mutations(flag, names, base, expect=KILL): 'g17-chunk-work-guard-tests.py': [([], PASS)] + mutations('--mutation', ('no-guard', 'no-finish-enqueue'), []), 'g17-compute-constructor-tests.py': [([], PASS)], + 'g17-compute-reserve-tests.py': [([], PASS)] + mutations( + '--mutation', ['allocating-bind', 'allocating-graph'], []), 'g17-compute-owed-stamp-tests.py': [([], PASS)] + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', From 837cbbb7ad1d4b3133c7b25aed824a683e490a11 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 14:53:05 -0300 Subject: [PATCH 02/13] drm/asahi: g17: allocate the shared compute objects in SUBMIT G17P's device-wide compute aperture (ComputeShared, 22 blocks of 1 MiB plus its lists) and compute scheduler were built by the first compute publication that needed them, on the scheduler's kworker, after SUBMIT had accepted the job. A refused allocation there failed the job, and the client lost its device. A compute SUBMIT now allocates them while they are neither installed nor prepared (`Backend::provision_compute`, from `ensure_compute`). A refusal is that SUBMIT's error. The publication that needs them takes the prepared object and installs it, as before; it allocates nothing, so its builder flags, the waits for another builder and the condition variable they waited on go. Installation keeps its timing: the aperture with the first publication's lease, the scheduler with the first fresh queue's pool row. Both stay device memory: they serve every client until processor stop. Allocated in a client's ioctl, their pages would be charged to that client's memory cgroup, so `memacct::device_memory` charges them to the root cgroup, as when the kworker allocated them. M5 has neither and allocates nothing. Tests: - g17-compute-constructor-tests now runs the production SUBMIT and publication halves (prepared once, a refusal fails the SUBMIT and prepares nothing, publication never builds and keeps the prepared object on cancel, a stale lease or a crash) with three mutations. - g17-admission-order-tests checks that every valid compute SUBMIT provisions and that a refusal fails it. - g17-m5-render-fast-done-tests checks that note_changed wakes render waiters only. - KUnit asahi_memacct: device_memory_is_charged_to_the_root_cgroup. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/mod.rs | 43 +--- drivers/gpu/drm/asahi/g17/runtime.rs | 201 +++++++------------ drivers/gpu/drm/asahi/g17/runtime/backend.rs | 3 +- drivers/gpu/drm/asahi/memacct.rs | 36 ++++ drivers/gpu/drm/asahi/memcg_scope.c | 13 ++ drivers/gpu/drm/asahi/memcg_scope.h | 1 + tools/asahi/g17-admission-order-tests.py | 21 +- tools/asahi/g17-compute-constructor-tests.py | 159 +++++++++------ tools/asahi/g17-m5-render-fast-done-tests.py | 24 +-- tools/asahi/run-host-tests.py | 1 - 10 files changed, 244 insertions(+), 258 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 37c6e84473b0f..5b35177f2331a 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -91,14 +91,13 @@ use kernel::{ IoSysMap, Region, // }, - new_condvar, new_delayed_work, new_mutex, new_work, platform, + new_delayed_work, new_mutex, new_work, platform, prelude::*, soc::apple::rtkit, sync::{ aref::ARef, Arc, ArcBorrow, - CondVar, Mutex, // }, time::{ @@ -1250,39 +1249,6 @@ const GOVERNOR_WORK: u64 = 6; /// `HOUSEKEEPING_NS`. const HOUSEKEEPING_WORK: u64 = 7; -/// `CondVar` wrapper that tracks active waiters so `notify_all()` skips the waitqueue lock -/// in the common zero-waiter steady state. -#[pin_data] -struct TrackedCondVar { - #[pin] - condvar: CondVar, - waiters: AtomicU32, -} - -impl TrackedCondVar { - fn wait_timeout( - &self, - guard: &mut kernel::sync::MutexGuard<'_, T>, - timeout: kernel::time::Jiffies, - ) -> kernel::sync::CondVarTimeoutResult { - struct Waiter<'a>(&'a AtomicU32); - impl Drop for Waiter<'_> { - fn drop(&mut self) { - self.0.fetch_sub(1, Ordering::Release); - } - } - self.waiters.fetch_add(1, Ordering::SeqCst); - let _waiter = Waiter(&self.waiters); - self.condvar.wait_timeout(guard, timeout) - } - - fn notify_all(&self) { - if self.waiters.load(Ordering::SeqCst) != 0 { - self.condvar.notify_all(); - } - } -} - /// Device state shared with the coprocessor callbacks and the event worker. #[pin_data] struct Shared { @@ -1416,8 +1382,6 @@ struct Shared { /// fan boost. Never taken with `state` held. #[pin] actuators: Mutex, - #[pin] - changed: TrackedCondVar, /// The port of the session in `state`; null before boot and once detachment begins. port: core::sync::atomic::AtomicPtr, } @@ -1740,7 +1704,6 @@ impl Shared { /// Wakes the waiters for a returned pair, binding or capacity change. fn note_changed(&self) { - self.changed.notify_all(); self.renders.notify(); } @@ -2243,10 +2206,6 @@ impl Gpu { stop <- new_mutex!((), "g17::Shared::stop"), state <- new_mutex!(None, "g17::Shared::state"), actuators <- new_mutex!(thermal::Actuators::new(), "g17::Shared::actuators"), - changed <- pin_init!(TrackedCondVar { - condvar <- new_condvar!("g17::Shared::changed"), - waiters: AtomicU32::new(0), - }), port: core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()), }), GFP_KERNEL, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 1f77faebf42a9..e490142ff88e3 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -264,8 +264,11 @@ pub(super) struct Registry { render: render::RenderState, identities: queue::Identities, compute: KVec>, - pub(super) compute_building: bool, - compute_scheduler_building: bool, + /// G17P's device-wide compute aperture and scheduler, allocated by a compute SUBMIT while + /// not installed ([`Backend::provision_compute`]) and installed by the first publication that + /// needs them: a publication never allocates them. + prepared_shared: Option, + prepared_scheduler: Option, replay_outer_wait: Option, /// A compute replay waits for its owner's renders to park or idle (compute_replay). replay_consumer_wait: Option, @@ -317,8 +320,8 @@ impl Registry { } compute }, - compute_building: false, - compute_scheduler_building: false, + prepared_shared: None, + prepared_scheduler: None, replay_outer_wait: None, replay_consumer_wait: None, observations: compute::retirement::Batch::new()?, @@ -1583,137 +1586,31 @@ impl Backend { Ok(PublicationBatch { batch, spare: &self.spare_batch }) } - /// The shared aperture has exactly one builder. Other queues sleep without - /// holding the device mutex; recovery joins its lease before closing roots. + /// Installs the shared aperture this owner's SUBMIT prepared, if no publication did yet, and + /// maps it into the owner's VM. Recovery joins the lease before closing roots. fn shared_compute(&self, admission: &Admission<'_>) -> Result { // The shared aperture is G17P compute state. M5 compute queues need only // their own pools, and the objects it would install are not M5's. if self.context.is_m5() { return Ok(()); } - loop { - admission.check()?; - let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; - let uat = { - let mut state = self.shared.state.lock(); - loop { - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if self - .shared - .crashed - .load(core::sync::atomic::Ordering::Acquire) - { - return Err(EIO); - } - if !lease.is_current() { - return Err(EAGAIN); - } - if firmware.init.has_compute_shared() { - return firmware.init.cache_compute_vm(self.context.vm()); - } - if !firmware.queues.compute_building { - firmware.queues.compute_building = true; - break firmware.uat.clone(); - } - let _ = self.shared.changed.wait_timeout( - &mut state, kernel::time::msecs_to_jiffies(admission.slice_ms()?) - ); - } - }; - let alloc = super::object::Allocator { - dev: &dev, - uat: &uat, - client: None, - }; - let mut built = Some(super::initdata::ComputeShared::new(&alloc)); - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() { - Err(EAGAIN) - } else { - built - .take() - .ok_or(EIO)? - .and_then(|built| firmware.init.install_compute_shared(built)) - .and_then(|()| firmware.init.cache_compute_vm(self.context.vm())) - } - }; - drop(built); - { - let mut state = self.shared.state.lock(); - (*state) - .as_deref_mut() - .ok_or(ENODEV)? - .queues - .compute_building = false; - } - self.shared.note_changed(); - drop(lease); - if result != Err(EAGAIN) { - return result; - } + admission.check()?; + let lease = self.shared.preparations.enter_until(admission)?; + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if self.shared.crashed.load(Ordering::Acquire) { + return Err(EIO); } - } - - /// Uses the queue builder's existing lease. Entering another closed epoch - /// here would make recovery wait for the very builder blocked on reopening. - fn compute_scheduler( - &self, - alloc: &super::object::Allocator<'_>, - lease: &super::preparation::Lease, - admission: &Admission<'_>, - ) -> Result { - { - let mut state = self.shared.state.lock(); - loop { - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { - return Err(EAGAIN); - } - if firmware.init.has_compute_scheduler() { - return Ok(()); - } - if !firmware.queues.compute_scheduler_building { - firmware.queues.compute_scheduler_building = true; - break; - } - let _ = self.shared.changed.wait_timeout( - &mut state, kernel::time::msecs_to_jiffies(admission.slice_ms()?) - ); - } + if !lease.is_current() { + return Err(EAGAIN); } - let mut built = Some(super::initdata::ComputeScheduler::new(alloc)); - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() { - Err(EAGAIN) - } else { - built - .take() - .ok_or(EIO)? - .and_then(|built| firmware.init.install_compute_scheduler(built)) - } - }; - drop(built); - { - let mut state = self.shared.state.lock(); - (*state) - .as_deref_mut() - .ok_or(ENODEV)? - .queues - .compute_scheduler_building = false; + if !firmware.init.has_compute_shared() { + // This command's SUBMIT left it prepared; only an install takes it. + let shared = firmware.queues.prepared_shared.take().ok_or(EIO)?; + firmware.init.install_compute_shared(shared)?; } - self.shared.note_changed(); - result + firmware.init.cache_compute_vm(self.context.vm()) } /// The caller keeps its preparation lease through this two-phase rollback. @@ -2018,11 +1915,12 @@ impl Backend { firmware.queues.reserved(reservation)?; firmware.init.install_compute_pool( compute::pool_descriptor(&pages, reservation.id.qid())?)?; - } - // The global scheduler is retained even if this queue's graph fails. - // It is G17P compute state; M5 has none. - if !self.context.is_m5() { - self.compute_scheduler(&alloc, &lease, admission)?; + // The global scheduler is retained even if this queue's graph fails. + // It is G17P compute state; M5 has none. + if !self.context.is_m5() && !firmware.init.has_compute_scheduler() { + let scheduler = firmware.queues.prepared_scheduler.take().ok_or(EIO)?; + firmware.init.install_compute_scheduler(scheduler)?; + } } let queue = compute::Queue::new( kit, @@ -3159,6 +3057,47 @@ impl Backend { .map(ComputeCapacity::Blocks) } + /// In the SUBMIT ioctl of a compute command: allocates what its publication will install + /// and must not allocate, so that a refusal is this ioctl's error (ENOMEM, or ENOSPC for + /// address space): G17P's device-wide compute aperture and scheduler, until installed. + pub(super) fn provision_compute(&self, _required: super::freelist::ComputeCapacity) -> Result { + if self.context.is_m5() { + return Ok(()); + } + let needed = |firmware: &super::Firmware| ( + !firmware.init.has_compute_shared() && firmware.queues.prepared_shared.is_none(), + !firmware.init.has_compute_scheduler() && firmware.queues.prepared_scheduler.is_none(), + ); + let (uat, (shared, scheduler)) = { + let state = self.shared.state.lock(); + let firmware = state.as_deref().ok_or(ENODEV)?; + (firmware.uat.clone(), needed(firmware)) + }; + if !shared && !scheduler { + return Ok(()); + } + let dev = self.shared.drm()?; + // Device memory: installed, they serve every client until processor stop. + let alloc = super::object::Allocator { dev: &dev, uat: &uat, client: None }; + let (mut shared, mut scheduler) = crate::memacct::device_memory(|| -> Result<_> { + Ok((shared.then(|| super::initdata::ComputeShared::new(&alloc)).transpose()?, + scheduler.then(|| super::initdata::ComputeScheduler::new(&alloc)).transpose()?)) + })?; + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + let (want_shared, want_scheduler) = needed(firmware); + if want_shared { + firmware.queues.prepared_shared = shared.take(); + } + if want_scheduler { + firmware.queues.prepared_scheduler = scheduler.take(); + } + drop(state); + // Another SUBMIT prepared them first: these drop off the device mutex. + drop((shared, scheduler)); + Ok(()) + } + fn ensure_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; let mut deferred = DeferredBatch::publication()?; diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 96d8a11b09e67..c72c5c448c19c 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -278,7 +278,8 @@ impl job::Backend for Backend { // A reverse timeline chain must be submitted before the host signal. // Validate here, but do not consume physical capacity behind unsignalled // DRM dependencies. compute_packet admits it when the job can run. - self.compute_capacity(command).map(|_| ()) + // What its publication would allocate is allocated now, so a refusal is this SUBMIT's. + self.compute_capacity(command).and_then(|required| self.provision_compute(required)) } fn fail_vm(&self, error: Error) { diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index e24babe3b3e04..2f13f870d44b6 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -59,6 +59,7 @@ use core::ffi::c_void; unsafe extern "C" { fn asahi_memcg_get() -> *mut c_void; + fn asahi_memcg_root() -> *mut c_void; fn asahi_memcg_put(memcg: *mut c_void); fn asahi_memcg_enter(memcg: *mut c_void) -> *mut c_void; fn asahi_memcg_leave(old: *mut c_void); @@ -360,6 +361,19 @@ impl Drop for Client { } } +/// Runs `f` with the root memory cgroup as the one that pages populated in it are charged to: +/// device memory a client's ioctl allocates (objects that outlive the client and serve others) +/// is charged to no client's cgroup, as when a kernel thread allocates it. +pub(crate) fn device_memory(f: impl FnOnce() -> T) -> T { + // SAFETY: The root memory cgroup is never freed, and the previous cgroup is restored before + // returning. + let old = unsafe { asahi_memcg_enter(asahi_memcg_root()) }; + let result = f(); + // SAFETY: Restores what `asahi_memcg_enter()` replaced. + unsafe { asahi_memcg_leave(old) }; + result +} + impl Client { pub(crate) fn new() -> Result> { Ok(Arc::new( @@ -722,6 +736,28 @@ mod tests { Ok(()) } + #[test] + fn device_memory_is_charged_to_the_root_cgroup() -> Result { + let a = Client::new()?; + // Inside a client's scope too: device memory goes to the root cgroup, and both scopes + // are restored. + let active = a.charging(|| device_memory(|| { + // SAFETY: Reads the active memory cgroup by replacing it and at once restoring it. + let active = unsafe { asahi_memcg_enter(core::ptr::null_mut()) }; + // SAFETY: Restores it. + unsafe { asahi_memcg_leave(active) }; + active + })); + // SAFETY: As above. Without memory cgroups the root, like the active one, is null. + assert_eq!(active, unsafe { asahi_memcg_root() }); + // SAFETY: As above. + let old = unsafe { asahi_memcg_enter(core::ptr::null_mut()) }; + // SAFETY: Restores it. + unsafe { asahi_memcg_leave(old) }; + assert!(old.is_null()); + Ok(()) + } + #[test] fn charging_restores_the_memory_cgroup() -> Result { let a = Client::new()?; diff --git a/drivers/gpu/drm/asahi/memcg_scope.c b/drivers/gpu/drm/asahi/memcg_scope.c index c7af8e96f083e..9e0318506e409 100644 --- a/drivers/gpu/drm/asahi/memcg_scope.c +++ b/drivers/gpu/drm/asahi/memcg_scope.c @@ -18,6 +18,19 @@ struct mem_cgroup *asahi_memcg_get(void) return get_mem_cgroup_from_mm(current->mm); } +/* + * The root memory cgroup, which device-wide objects a client's ioctl allocates are charged to; + * NULL without memory cgroups. + */ +struct mem_cgroup *asahi_memcg_root(void) +{ +#ifdef CONFIG_MEMCG + return root_mem_cgroup; +#else + return NULL; +#endif +} + void asahi_memcg_put(struct mem_cgroup *memcg) { mem_cgroup_put(memcg); diff --git a/drivers/gpu/drm/asahi/memcg_scope.h b/drivers/gpu/drm/asahi/memcg_scope.h index 87434556bfe2e..871624381e7a8 100644 --- a/drivers/gpu/drm/asahi/memcg_scope.h +++ b/drivers/gpu/drm/asahi/memcg_scope.h @@ -6,6 +6,7 @@ struct mem_cgroup; /* Called from memacct.rs. */ struct mem_cgroup *asahi_memcg_get(void); +struct mem_cgroup *asahi_memcg_root(void); void asahi_memcg_put(struct mem_cgroup *memcg); struct mem_cgroup *asahi_memcg_enter(struct mem_cgroup *memcg); void asahi_memcg_leave(struct mem_cgroup *old); diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index b818075ec654e..a0fbb2383ce9f 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -47,7 +47,7 @@ def compute_order(): #![allow(dead_code)] use std::sync::atomic::{AtomicUsize,AtomicBool,Ordering}; type Result = std::result::Result; -const ECANCELED:i32=-125;const EIO:i32=-5;const EFAULT:i32=-14;const EINVAL:i32=-22; +const ECANCELED:i32=-125;const EIO:i32=-5;const EFAULT:i32=-14;const EINVAL:i32=-22;const ENOMEM:i32=-12; mod g17 { pub mod fw { pub mod compute_pool { @@ -72,7 +72,7 @@ def compute_order(): } pub mod runtime { use super::*; - use crate::{Result,ECANCELED,EIO,EFAULT,EINVAL}; + use crate::{Result,ECANCELED,EIO,EFAULT,EINVAL,ENOMEM}; use std::sync::atomic::{AtomicUsize,AtomicBool,Ordering}; pub struct Status(pub i32); impl Status {fn get(&self)->i32{self.0}} @@ -80,9 +80,10 @@ def compute_order(): impl Context {fn status(&self)->&Status{&self.status} fn is_current(&self)->bool{true} fn is_m5(&self)->bool{self.m5}} pub struct Shared {pub compute_blocks:usize,pub active_cores:u32,pub crashed:AtomicBool} pub struct Admission; - pub struct Backend {pub shared:Shared,pub physical:AtomicUsize,pub closed:AtomicBool,pub context:Context} + pub struct Backend {pub shared:Shared,pub physical:AtomicUsize,pub reserved:AtomicUsize,pub refuse:AtomicBool,pub closed:AtomicBool,pub context:Context} impl Backend { pub fn ensure_compute(&self,_:freelist::ComputeCapacity,_:&Admission)->Result {self.physical.fetch_add(1,Ordering::SeqCst);Ok(())} + pub fn provision_compute(&self,_:freelist::ComputeCapacity)->Result {if self.refuse.load(Ordering::SeqCst){return Err(ENOMEM);}self.reserved.fetch_add(1,Ordering::SeqCst);Ok(())} ''' + method('runtime.rs', 'pub(super) fn compute_capacity(').replace('pub(super) ', 'pub ', 1) + '\n' + method('runtime.rs', 'fn admission_open(').replace('fn ', 'pub fn ', 1) + r''' } pub trait Api {fn ensure_compute(&self,command:&command::Validated)->Result;} @@ -94,7 +95,7 @@ def compute_order(): use g17::{command::{ScratchRequest,Validated},freelist::ComputeCapacity,fw::m5::pool::PoolGeometry,render_resources::Plan,runtime::*}; fn compute(pages:u16)->Validated {Validated::Compute{plan:None,scratch:ScratchRequest(pages)}} fn backend(cores:u32,m5:bool)->Backend { - Backend{shared:Shared{compute_blocks:21,active_cores:cores,crashed:AtomicBool::new(false)},physical:AtomicUsize::new(0),closed:AtomicBool::new(false),context:Context{status:Status(0),m5}} + Backend{shared:Shared{compute_blocks:21,active_cores:cores,crashed:AtomicBool::new(false)},physical:AtomicUsize::new(0),reserved:AtomicUsize::new(0),refuse:AtomicBool::new(false),closed:AtomicBool::new(false),context:Context{status:Status(0),m5}} } fn main(){ let backend=backend(10,false); @@ -102,12 +103,18 @@ def compute_order(): // final host signal cannot be submitted if ioctl admission blocks on channels. for _client in 0..4 {for _queue in (0..9).rev() {::ensure_compute(&backend,&compute(0)).unwrap();}} assert_eq!(backend.physical.load(Ordering::SeqCst),0,"unsignalled work must not pin physical capacity"); + assert_eq!(backend.reserved.load(Ordering::SeqCst),36,"each SUBMIT reserves what its publication needs"); + // A reserve SUBMIT cannot fill is that SUBMIT's error. + backend.refuse.store(true,Ordering::SeqCst); + assert_eq!(::ensure_compute(&backend,&compute(0)),Err(ENOMEM),"a refused reserve must fail the SUBMIT"); + backend.refuse.store(false,Ordering::SeqCst); assert_eq!(backend.compute_capacity(&compute(3)),Ok(ComputeCapacity::Blocks(24))); Backend::ensure_compute(&backend,backend.compute_capacity(&compute(0)).unwrap(),&Admission).unwrap(); assert_eq!(backend.physical.load(Ordering::SeqCst),1); let invalid=self::backend(0,false); assert_eq!(::ensure_compute(&invalid,&compute(0)),Err(-22)); assert_eq!(invalid.physical.load(Ordering::SeqCst),0); + assert_eq!(invalid.reserved.load(Ordering::SeqCst),0,"invalid sizing reserves nothing"); assert_eq!(::ensure_compute(&backend,&Validated::Render),Err(EINVAL)); // M5 sizes a compute pool by its plan's geometry; that, too, admits nothing physical. let m5=self::backend(0,true); @@ -123,10 +130,10 @@ def compute_order(): println!("PASS closed builders cannot install after logical close; production ioctl sizing validates 36 reverse-order submissions without physical admission, on G17P and M5; invalid sizing consumes no channel"); } ''' - fixed = 'self.compute_capacity(command).map(|_| ())' + fixed = 'self.compute_capacity(command).and_then(|required| self.provision_compute(required))' assert code.count(fixed) == 1 with tempfile.TemporaryDirectory(prefix='g17-admission-order-') as tmp: - for name, source in [('fixed', code), ('eager-physical-admission', code.replace(fixed, 'self.compute_capacity(command).and_then(|required| Backend::ensure_compute(self, required, &Admission))')), ('ignore-logical-close', code.replace('self.closed.load(Ordering::Acquire)', 'false'))]: + for name, source in [('fixed', code), ('eager-physical-admission', code.replace(fixed, 'self.compute_capacity(command).and_then(|required| Backend::ensure_compute(self, required, &Admission))')), ('skip-reserve', code.replace(fixed, 'self.compute_capacity(command).map(|_| ())')), ('ignore-logical-close', code.replace('self.closed.load(Ordering::Acquire)', 'false'))]: path = Path(tmp) / (name + '.rs') binary = path.with_suffix('') path.write_text(source) @@ -136,7 +143,7 @@ def compute_order(): assert result.returncode == 0, result.stderr print(result.stdout.strip()) else: - assert result.returncode != 0 and ('must not pin physical capacity' if name == 'eager-physical-admission' else 'closed constructor must not install') in result.stderr, result.stderr + assert result.returncode != 0 and {'eager-physical-admission': 'must not pin physical capacity', 'skip-reserve': 'each SUBMIT reserves', 'ignore-logical-close': 'closed constructor must not install'}[name] in result.stderr, result.stderr print('PASS negative control:', name) diff --git a/tools/asahi/g17-compute-constructor-tests.py b/tools/asahi/g17-compute-constructor-tests.py index 4bd2999fc1882..51407cbbdd9a8 100644 --- a/tools/asahi/g17-compute-constructor-tests.py +++ b/tools/asahi/g17-compute-constructor-tests.py @@ -1,9 +1,15 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Execute both production shared-constructor waits and flag cleanup. +"""G17P's device-wide compute objects are allocated in SUBMIT and installed at publication. -Allocations, mappings, device locks and firmware are mocked. Real method bodies -must check the original admission after every wake and after off-lock creation. +Runs the production `Backend::provision_compute` (SUBMIT) and `Backend::shared_compute` +(publication) against mocked firmware state, allocations and leases: + +- SUBMIT allocates the shared aperture and the scheduler while neither is installed nor + prepared, as device memory (the root memory cgroup), and nothing on M5; an allocation + failure is the SUBMIT's error and leaves nothing prepared; +- publication installs the prepared aperture, never allocates, fails with EIO if none was + prepared, and checks the admission, the crash flag and its lease before installing. """ from pathlib import Path import os @@ -25,79 +31,107 @@ def item(text, signature): def fixture(): runtime = (ROOT / 'runtime.rs').read_text() - preparation = (ROOT / 'preparation.rs').read_text() - admission = (item(preparation, "pub(super) struct Admission<'a>") + '\n' + - item(preparation, "impl<'a> Admission<'a>")).replace('pub(super) ', '').replace('super::now_ns()', 'now_ns()').replace('super::timeout::', '') - # The admission's wait kinds and their count, which its struct names. - admission = ('#[derive(Clone,Copy,Debug,PartialEq)]\n' + item(preparation, 'pub(super) enum AdmissionWait').replace('pub(super) ', '') + '\n' - + next(line for line in preparation.splitlines() if 'const ADMISSION_WAITS:' in line).replace('pub(super) ', '') - + '\n' + admission) - methods = '\n'.join(item(runtime, sig) for sig in [' fn shared_compute(', ' fn compute_scheduler(']) - methods = methods.replace('super::object::Allocator', 'Allocator').replace('super::preparation::Lease', 'Lease').replace('super::initdata::', '') + methods = '\n'.join(item(runtime, sig) for sig in [' pub(super) fn provision_compute(', ' fn shared_compute(']) + methods = (methods.replace('super::object::Allocator', 'Allocator').replace('super::initdata::', '') + .replace('super::freelist::ComputeCapacity', 'ComputeCapacity').replace('super::Firmware', 'Firmware') + .replace('crate::memacct::device_memory', 'device_memory').replace('pub(super) ', '')) return r''' #![allow(dead_code)] -use std::cell::Cell; -use std::sync::{Mutex,MutexGuard,atomic::{AtomicBool,AtomicU64,Ordering}}; +use std::sync::{Mutex,MutexGuard,atomic::{AtomicBool,AtomicUsize,Ordering}}; type Result = std::result::Result; -const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const EBUSY:i32=-16;const ECANCELED:i32=-125; -const RECOVERY_WAIT_MS:u32=26_000; -static NOW:AtomicU64=AtomicU64::new(0);static CANCEL:AtomicBool=AtomicBool::new(false);static ALLOCATE:AtomicBool=AtomicBool::new(false); -fn now_ns()->u64{NOW.load(Ordering::SeqCst)} -mod kernel{pub mod time{pub fn msecs_to_jiffies(ms:u32)->u32{ms}}} -''' + admission + r''' +const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const ENOMEM:i32=-12;const ECANCELED:i32=-125; +static ALLOCATED:AtomicUsize=AtomicUsize::new(0);static REFUSE:AtomicBool=AtomicBool::new(false); +static DEVICE_SCOPE:AtomicBool=AtomicBool::new(false);static CANCEL:AtomicBool=AtomicBool::new(false); +static CURRENT:AtomicBool=AtomicBool::new(true); +struct Admission<'a>(std::marker::PhantomData<&'a ()>); +const ADMISSION: Admission<'static> = Admission(std::marker::PhantomData); +impl Admission<'_>{fn check(&self)->Result{if CANCEL.load(Ordering::SeqCst){Err(ECANCELED)}else{Ok(())}}} struct Gate;struct Lease; impl Gate{fn enter_until(&self,a:&Admission<'_>)->Result{a.check()?;Ok(Lease)}} -impl Lease{fn is_current(&self)->bool{true}} +impl Lease{fn is_current(&self)->bool{CURRENT.load(Ordering::SeqCst)}} struct State(Mutex>>); impl State{fn lock(&self)->MutexGuard<'_,Option>>{self.0.lock().unwrap()}} -struct Changed; -impl Changed{ - fn wait_timeout(&self,_:&mut MutexGuard<'_,T>,_:u32){NOW.fetch_add(1_000_000,Ordering::SeqCst);assert!(now_ns()<100_000_000,"constructor wait exceeded original budget");} - fn notify_all(&self){} -} -struct Shared{preparations:Gate,state:State,changed:Changed,crashed:AtomicBool} -impl Shared{fn drm(&self)->Result<()>{Ok(())} fn note_changed(&self){self.changed.notify_all();}} +struct Shared{preparations:Gate,state:State,crashed:AtomicBool} +impl Shared{fn drm(&self)->Result<()>{Ok(())}} struct Context{m5:bool}impl Context{fn vm(&self)->&(){&()} fn is_m5(&self)->bool{self.m5}} struct Backend{shared:Shared,context:Context} +struct ComputeCapacity; struct Allocator<'a>{dev:&'a (),uat:&'a (),client:Option<&'a ()>} -struct ComputeShared;struct ComputeScheduler; -fn allocate(){if ALLOCATE.load(Ordering::SeqCst){NOW.fetch_add(25_000_000,Ordering::SeqCst);}} -impl ComputeShared{fn new(_:&Allocator<'_>)->Result{allocate();Ok(Self)}} -impl ComputeScheduler{fn new(_:&Allocator<'_>)->Result{allocate();Ok(Self)}} -struct Init{shared:bool,scheduler:bool} +fn no_scope(f:impl FnOnce()->T)->T{f()} +fn device_memory(f:impl FnOnce()->T)->T{DEVICE_SCOPE.store(true,Ordering::SeqCst);let r=f();DEVICE_SCOPE.store(false,Ordering::SeqCst);r} +fn allocate()->Result{ + assert!(DEVICE_SCOPE.load(Ordering::SeqCst),"device-wide objects must be device memory"); + if REFUSE.load(Ordering::SeqCst){return Err(ENOMEM);}ALLOCATED.fetch_add(1,Ordering::SeqCst);Ok(()) +} +#[derive(Debug)]struct ComputeShared;#[derive(Debug)]struct ComputeScheduler; +impl ComputeShared{fn new(a:&Allocator<'_>)->Result{assert!(a.client.is_none());allocate()?;Ok(Self)}} +impl ComputeScheduler{fn new(a:&Allocator<'_>)->Result{assert!(a.client.is_none());allocate()?;Ok(Self)}} +struct Init{shared:bool,scheduler:bool,cached:usize} impl Init{ fn has_compute_shared(&self)->bool{self.shared} fn has_compute_scheduler(&self)->bool{self.scheduler} - fn cache_compute_vm(&self,_:&())->Result{Ok(())} + fn cache_compute_vm(&mut self,_:&())->Result{self.cached+=1;Ok(())} fn install_compute_shared(&mut self,_:ComputeShared)->Result{self.shared=true;Ok(())} - fn install_compute_scheduler(&mut self,_:ComputeScheduler)->Result{self.scheduler=true;Ok(())} } -struct Queues{compute_building:bool,compute_scheduler_building:bool} +struct Queues{prepared_shared:Option,prepared_scheduler:Option} struct Firmware{init:Init,uat:(),queues:Queues} impl Backend{ ''' + methods + r''' } +fn backend(m5:bool,shared:bool,scheduler:bool)->Backend{ + Backend{context:Context{m5},shared:Shared{preparations:Gate,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(), + init:Init{shared,scheduler,cached:0},queues:Queues{prepared_shared:None,prepared_scheduler:None}}))))}} +} +fn fw<'a>(b:&'a Backend)->MutexGuard<'a,Option>>{b.shared.state.lock()} fn main(){ - for scheduler in [false,true]{for cancel in [false,true]{for building in [false,true]{ - NOW.store(0,Ordering::SeqCst);CANCEL.store(cancel,Ordering::SeqCst);ALLOCATE.store(!building,Ordering::SeqCst); - let b=Backend{context:Context{m5:false},shared:Shared{preparations:Gate,changed:Changed,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(),init:Init{shared:false,scheduler:false},queues:Queues{compute_building:building,compute_scheduler_building:building}}))))}}; - let check=||{if CANCEL.load(Ordering::SeqCst)&&now_ns()>=10_000_000{Err(ECANCELED)}else{Ok(())}}; - let admission=Admission::new(20_000_000,&check); - let alloc=Allocator{dev:&(),uat:&(),client:None}; - let r=if scheduler{b.compute_scheduler(&alloc,&Lease,&admission)}else{b.shared_compute(&admission)}; - assert_eq!(r,Err(if cancel{ECANCELED}else{EBUSY}),"constructor must propagate deadline/cancel"); - assert_eq!(now_ns(),if building{if cancel{10_000_000}else{20_000_000}}else{25_000_000}); - let state=b.shared.state.lock();let fw=state.as_ref().unwrap(); - assert!(!fw.init.shared&&!fw.init.scheduler,"expired constructor must not install"); - if !building{assert!(!fw.queues.compute_building&&!fw.queues.compute_scheduler_building,"failed constructor must clear builder flag");} - }}} - // M5 compute queues need no shared aperture: nothing waits, builds or installs. - NOW.store(0,Ordering::SeqCst);CANCEL.store(false,Ordering::SeqCst);ALLOCATE.store(true,Ordering::SeqCst); - let b=Backend{context:Context{m5:true},shared:Shared{preparations:Gate,changed:Changed,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(),init:Init{shared:false,scheduler:false},queues:Queues{compute_building:true,compute_scheduler_building:false}}))))}}; - let check=||Ok(()); - assert_eq!(b.shared_compute(&Admission::new(20_000_000,&check)),Ok(())); - assert_eq!(now_ns(),0);assert!(!b.shared.state.lock().as_ref().unwrap().init.shared); - println!("PASS 8 production shared/scheduler constructor waits: expiry, cancellation, off-lock-build expiry, no installation and flag cleanup; M5 skips the G17P shared aperture"); + // SUBMIT: allocates what is neither installed nor prepared, once. + let b=backend(false,false,false); + assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2); + assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_some()&&fw(&b).as_ref().unwrap().queues.prepared_scheduler.is_some()); + assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2,"prepared objects must not be allocated again"); + // Publication installs the prepared aperture and allocates nothing. + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + {let g=fw(&b);let f=g.as_ref().unwrap();assert!(f.init.shared&&f.queues.prepared_shared.is_none()&&f.init.cached==1);} + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + assert_eq!(fw(&b).as_ref().unwrap().init.cached,2); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2,"publication must not allocate"); + // Installed objects are not prepared again. + let b=backend(false,true,true); + assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2); + // A refused allocation is the SUBMIT's error and prepares nothing. + let b=backend(false,false,false); + REFUSE.store(true,Ordering::SeqCst); + assert_eq!(b.provision_compute(ComputeCapacity),Err(ENOMEM),"a refused allocation must fail the SUBMIT"); + REFUSE.store(false,Ordering::SeqCst); + assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_none()); + // Publication without a prepared aperture fails and installs nothing; it never builds one. + assert_eq!(b.shared_compute(&ADMISSION),Err(EIO),"publication must not allocate an aperture SUBMIT did not prepare"); + assert!(!fw(&b).as_ref().unwrap().init.shared); + // A cancelled admission, a stale lease or a crash installs nothing. + assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + CANCEL.store(true,Ordering::SeqCst); + assert_eq!(b.shared_compute(&ADMISSION),Err(ECANCELED)); + CANCEL.store(false,Ordering::SeqCst); + CURRENT.store(false,Ordering::SeqCst); + assert_eq!(b.shared_compute(&ADMISSION),Err(EAGAIN)); + CURRENT.store(true,Ordering::SeqCst); + b.shared.crashed.store(true,Ordering::SeqCst); + assert_eq!(b.shared_compute(&ADMISSION),Err(EIO)); + b.shared.crashed.store(false,Ordering::SeqCst); + assert!(!fw(&b).as_ref().unwrap().init.shared&&fw(&b).as_ref().unwrap().queues.prepared_shared.is_some(),"a refused publication must keep the prepared aperture"); + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + assert!(fw(&b).as_ref().unwrap().init.shared); + // M5 has neither: nothing is allocated or installed. + let before=ALLOCATED.load(Ordering::SeqCst); + let b=backend(true,false,false); + assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before); + assert!(!fw(&b).as_ref().unwrap().init.shared); + println!("PASS G17P compute aperture and scheduler: SUBMIT prepares them once as device memory and fails on a refusal; publication installs the prepared aperture, never allocates, and keeps it on cancel, stale lease or crash; M5 has neither"); } ''' @@ -106,8 +140,15 @@ def main(): source = fixture() mutants = [ ('fixed', source, ''), - ('ignore-constructor-wakes', source.replace(' admission.check()?;\n let firmware', ' let firmware').replace(' admission.check()?;\n let firmware', ' let firmware').replace('admission.slice_ms()?', '10'), 'constructor wait exceeded'), - ('ignore-build-expiry', source.replace('if let Err(error) = admission.check() {', 'if let Err(error) = Ok::<(),i32>(()) {'), 'constructor must propagate'), + ('publication-builds', source.replace( + 'let shared = firmware.queues.prepared_shared.take().ok_or(EIO)?;', + 'let shared = firmware.queues.prepared_shared.take().map_or_else(|| device_memory(|| ComputeShared::new(&Allocator { dev: &(), uat: &(), client: None })), Ok)?;'), + 'publication must not allocate'), + ('charged-to-client', source.replace('= device_memory(|| -> Result<_>', '= no_scope(|| -> Result<_>'), + 'must be device memory'), + ('swallow-refusal', source.replace( + '(&alloc)).transpose()?', '(&alloc)).transpose().unwrap_or(None)'), + 'must fail the SUBMIT'), ] with tempfile.TemporaryDirectory(prefix='g17-compute-constructors-') as tmp: for name, code, expected in mutants: @@ -122,7 +163,7 @@ def main(): assert result.returncode == 0, result.stderr print(result.stdout.strip()) else: - assert result.returncode != 0 and expected in result.stderr, result.stderr + assert result.returncode != 0 and expected in result.stderr, (name, result.stderr) print('PASS negative control:', name) diff --git a/tools/asahi/g17-m5-render-fast-done-tests.py b/tools/asahi/g17-m5-render-fast-done-tests.py index f84dff058ee0d..7d4611eeeb8a4 100755 --- a/tools/asahi/g17-m5-render-fast-done-tests.py +++ b/tools/asahi/g17-m5-render-fast-done-tests.py @@ -21,9 +21,8 @@ multi-slot pending work fall back to `observe_renders()`. - Slow-path `observe_renders()` folds deferred-error drain and rescan checks into `runtime_event_turn()`'s existing `state.lock()` holds. -4. `Shared::note_changed()` (`mod.rs`) gates `self.changed.notify_all()` on - `changed_waiters` and all `changed.wait_timeout` callers in `runtime.rs` - use `wait_changed_timeout()`. +4. `Shared::note_changed()` (`mod.rs`) wakes render waiters only: nothing + waits on a separate condition variable any more. """ import argparse import os @@ -73,7 +72,7 @@ def build_harness(mutation=None): try_fast = item(observe_src, 'fn fast_observe_renders(') observe_fn = item(observe_src, 'pub(in crate::g17) fn observe_renders(') turn = item(events_src, 'fn runtime_event_turn(') - tracked_cv = item(mod_src, 'impl TrackedCondVar') + note_changed = item(mod_src, 'fn note_changed(') avail_wait = item(avail_src, 'pub(crate) fn wait(') avail_advance = item(avail_src, 'fn advance(') @@ -108,12 +107,6 @@ def build_harness(mutation=None): 'true', 1, ) - elif mutation == 'unconditional-changed-notify': - tracked_cv = tracked_cv.replace( - 'if self.waiters.load(Ordering::SeqCst) != 0 {', - 'if true {', - 1, - ) elif mutation == 'skip-generation-bump': avail_advance = avail_advance.replace( 'let previous = self.generation.fetch_add(1, Ordering::SeqCst);\n' @@ -179,11 +172,9 @@ def build_harness(mutation=None): ) changed_waiters_ok = ( - 'changed: TrackedCondVar,' in mod_src - and 'if self.waiters.load(Ordering::SeqCst) != 0 {' in tracked_cv - and 'self.condvar.notify_all();' in tracked_cv - and 'self.waiters.fetch_add(1, Ordering::SeqCst);' in tracked_cv - and 'self.0.fetch_sub(1, Ordering::Release);' in tracked_cv + 'TrackedCondVar' not in mod_src + and 'condvar' not in note_changed + and 'self.renders.notify();' in note_changed ) # Adapt Availability::wait() and advance() for host compilation to test the real Dekker protocol. @@ -346,7 +337,7 @@ def build_harness(mutation=None): assert!({str(doorbell_order_ok).lower()}, "DirectHost::notify_render must drop m5_outer then render before port.notify()"); assert!({str(fast_render_guards_ok).lower()}, "try_fast_observe_render must guard all non-steady states"); assert!({str(turn_order_ok).lower()}, "runtime_event_turn must scope fast_epoch and fold observe_renders locks"); - assert!({str(changed_waiters_ok).lower()}, "Shared::note_changed must gate condvar wake on changed_waiters"); + assert!({str(changed_waiters_ok).lower()}, "Shared::note_changed must wake render waiters only"); test_availability_zero_waiter_and_dekker_race(); test_multi_slot_fast_render(); println!("PASS g17-m5-render-fast-done-tests"); @@ -361,7 +352,6 @@ def main(): 'skip-pending-error-fallback', 'single-slot-bailout', 'skip-epoch-check', - 'unconditional-changed-notify', 'skip-generation-bump']) args = parser.parse_args() src = build_harness(args.mutation) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 12097e0ee799d..55f086d4591a4 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -361,7 +361,6 @@ def mutations(flag, names, base, expect=KILL): 'skip-pending-error-fallback', 'single-slot-bailout', 'skip-epoch-check', - 'unconditional-changed-notify', 'skip-generation-bump'), []), 'g17-m5-cross-qid-direct-tests.py': [([], PASS)] + mutations('--mutation', ('no-chain-dedup', From 2c8dfe7aa8ac039bf111a2da8dc232aa369f3aa2 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 15:18:43 -0300 Subject: [PATCH 03/13] drm/asahi: g17: allocate a queue's compute backing in SUBMIT A G17 compute queue's backing (the pool pages, at least 23 MiB on G17P, and the descriptor ring) and a fresh queue's kit were allocated when a command was published, on the scheduler's kworker, after SUBMIT had accepted it. A refusal there failed the job, and the client lost its device. With the backing charged to the client's memory cgroup, a client at its cgroup limit lost it that way. Each logical queue (owner) now has a reserve of compute backing: - **SUBMIT provisions.** A compute SUBMIT allocates what its publication would lack (`Backend::provision_backing`): pages that fit the command and a ring, unless the owner's spares or the queues holding its backing have them, and a kit while the owner has no queue of its own. Pages and ring are charged to the client through its Allocator; the kit is device memory (`memacct::device_memory`), since an installed queue outlives the owner. A refusal is that SUBMIT's ENOMEM or ENOSPC, before the command is queued. - **Publication takes.** Re-arming a vacant queue, building a fresh one (now in one device-mutex section with its install), growing a pool and adding an M5 sibling take from the owner's spares and allocate no device memory. A sibling that finds none asks the next SUBMIT for a set. - **Backing is the owner's until it closes.** A queue records whose backing it holds. When it gives the backing back (a pool release the firmware consumed, a grown pool's smaller pages, a recycled ring, a never-published queue's rollback), the pages and ring go back to that owner's spares, reset, while the owner has compute commands. Another open owner's backing is never bound: a queue holding it is given back first, as another VM's is. - **Claims.** Each compute command holds a claim on its owner from before its SUBMIT provisions until the command is dropped. An owner without claims is idle: what its queues give back is freed, and the pool pass frees its spares, so idle memory is what it was. Close frees the rest. A publication whose backing is on its way back waits as it waits for a channel today, and the event pass that observes the consumed release returns the backing and wakes it. That release is published by the pool pass and consumed by the firmware, whatever the waiting client does. Tests: - KUnit asahi_g17_compute_reserve: spares move without being freed, the smallest fitting pages are taken, a full owner frees only covered pages, and each spare is freed once. - g17-compute-reserve-tests: publication paths allocate nothing; SUBMIT charges pages and ring and allocates the kit as device memory; the claim precedes it and the command is queued after; every give-back keeps the backing for its owner; the production keep_backing, stock and trim_reserves free every spare exactly once; a queue-less owner always gets a kit. Six more mutations. - g17-queue-object-charge-tests: SUBMIT's compute backing is the second allocator that names the client; two more mutations. - Fixture updates for the changed functions in the g17 compute, growth, sibling and cleanup tests. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context.rs | 26 + drivers/gpu/drm/asahi/g17/freelist.rs | 27 + drivers/gpu/drm/asahi/g17/job.rs | 4 + drivers/gpu/drm/asahi/g17/queue/compute.rs | 143 ++-- .../drm/asahi/g17/queue/compute/reserve.rs | 251 +++++++ drivers/gpu/drm/asahi/g17/queue/mod.rs | 5 + drivers/gpu/drm/asahi/g17/runtime.rs | 688 ++++++++++++------ drivers/gpu/drm/asahi/g17/runtime/backend.rs | 3 + drivers/gpu/drm/asahi/memacct.rs | 14 +- tools/asahi/g17-admission-order-tests.py | 1 + tools/asahi/g17-compute-constructor-tests.py | 16 +- .../g17-compute-growth-deadline-tests.py | 23 +- tools/asahi/g17-compute-reserve-tests.py | 251 ++++++- tools/asahi/g17-compute-retired-tests.py | 18 +- tools/asahi/g17-growth-tests.py | 16 +- tools/asahi/g17-m5-sibling-compute-tests.py | 11 +- tools/asahi/g17-m5-sibling-gate-tests.py | 2 + tools/asahi/g17-m5-sibling-rearm-tests.py | 24 +- tools/asahi/g17-object-fence-tests.py | 2 +- tools/asahi/g17-queue-object-charge-tests.py | 60 +- tools/asahi/g17-uninstalled-cleanup-tests.py | 36 +- tools/asahi/run-host-tests.py | 7 +- 22 files changed, 1284 insertions(+), 344 deletions(-) create mode 100644 drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index cebeb73c78d9a..b8fe01170c5ac 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -201,6 +201,24 @@ pub(crate) struct FirmwarePages { _qos: Arc, } +/// One compute command of an owner, from before its SUBMIT provisions the owner's compute backing +/// until the command is dropped. While any is held, what the owner was given back for its +/// publications is kept for them ([`Context::compute_claimed`]). +pub(crate) struct ComputeClaim(Arc); + +impl ComputeClaim { + pub(crate) fn new(context: &Arc) -> Self { + context.compute_claims.fetch_add(1, Ordering::AcqRel); + Self(context.clone()) + } +} + +impl Drop for ComputeClaim { + fn drop(&mut self) { + self.0.compute_claims.fetch_sub(1, Ordering::AcqRel); + } +} + pub(crate) struct Context { /// The GPU runs the M5 firmware's protocol. m5: bool, @@ -226,6 +244,9 @@ pub(crate) struct Context { /// Advisory count of bound compute channels: publication still checks the physical binding /// under the device mutex. Zero skips an inline attempt known to need admission. compute_bindings: AtomicU32, + /// This owner's compute commands from before their SUBMIT provisioned them until they are + /// dropped ([`ComputeClaim`]): while there are any, the owner's spare compute backing stays. + compute_claims: AtomicU32, /// Shared monotonic compute completion ordinal / submit sequence across an M5 multi-channel /// context's physical compute queues. compute_ordinal: AtomicU32, @@ -378,6 +399,7 @@ impl Context { closed_generation: AtomicU64::new(u64::MAX), closed_for_open_client: AtomicBool::new(false), compute_bindings: AtomicU32::new(0), + compute_claims: AtomicU32::new(0), compute_ordinal: AtomicU32::new(0), render_seen: AtomicBool::new(false), qos, @@ -421,6 +443,10 @@ impl Context { self.render_seen.store(true, Ordering::Release); } } + /// Whether a compute command of this owner holds a [`ComputeClaim`]. + pub(crate) fn compute_claimed(&self) -> bool { + self.compute_claims.load(Ordering::Acquire) != 0 + } pub(crate) fn note_compute_binding(&self, owned: bool) { if owned { self.compute_bindings.fetch_add(1, Ordering::AcqRel); diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index 9fcd45ae281b4..3d00738e8e86c 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -334,6 +334,20 @@ impl Drop for Pages { LOWER_FREED.fetch_add(1, Ordering::AcqRel); } } +impl super::queue::compute::reserve::Capacity for Pages { + fn fits(&self, required: ComputeCapacity) -> bool { + self.fits_capacity(required) + } + fn covers(&self, other: &Self) -> bool { + match (self.layout, other.layout) { + (PageLayout::Neo { blocks, .. }, PageLayout::Neo { blocks: other, .. }) => blocks >= other, + (PageLayout::M5(geometry), PageLayout::M5(other)) => + geometry.block_bytes() == other.block_bytes() && geometry.blocks >= other.blocks, + _ => false, + } + } +} + impl Pages { fn new(alloc: &Allocator<'_>, blocks: usize, runs: RunLayout) -> Result { let size = TABLE_SIZE + blocks * FREE_LIST_BLOCK_SIZE; @@ -455,6 +469,19 @@ impl Pages { _ => false, } } + /// Writes the tables of fresh backing again, for reuse by the owner that gave this backing + /// back. The caller has seen the firmware consume the pool's release. + pub(crate) fn reset(&mut self) -> Result { + match self.layout { + PageLayout::Neo { blocks, runs } => { + let base = self.backing.gpu_va(); + self.backing.initialize::(0, |tables| tables.init(base, blocks, runs))?; + } + PageLayout::M5(_) => self.populate_m5()?, + } + fence(Ordering::SeqCst); + Ok(()) + } fn is_m5(&self) -> bool { matches!(self.layout, PageLayout::M5(_)) } pub(crate) fn page_list_va(&self) -> u64 { self.backing.gpu_va() } fn run_list_va(&self) -> u64 { diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 4278f8b9be256..010feb9cc6887 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -129,6 +129,8 @@ pub(crate) struct Packet { pub(crate) order: Order, pub(crate) completion: Arc, pub(crate) footprint: Option>, + /// A compute command's hold on its owner's spare compute backing. + _claim: Option, inputs: KVec, firmware: KVec, publication: AtomicU8, @@ -159,6 +161,7 @@ impl Packet { completion: Arc, inputs: KVec, firmware: KVec, + claim: Option, ) -> Result> { let footprint = match &command { Validated::Render { attachments, pass, .. } => { @@ -176,6 +179,7 @@ impl Packet { order, completion, footprint, + _claim: claim, inputs, firmware, publication: AtomicU8::new(0), diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index c266b62c73870..03227664abe7b 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -6,6 +6,7 @@ pub(crate) mod exit; mod activation; mod configuration; +pub(crate) mod reserve; pub(crate) mod retirement; use crate::g17::{ @@ -77,9 +78,35 @@ static_assert!(core::mem::offset_of!(GraphLayout, items) == ITEMS); /// mutex. Field order drops each client alias before the storage it names. pub(crate) struct Vacated { _alias: Option, - _pages: Option, + pages: Option, _descriptors: Option, - _ring: Option, + ring: Option, + /// A spare kit freed with the rest. + _kit: Option, + /// The owner whose backing the pages and ring are, which they go back to while it has + /// compute commands ([`reserve`]). + owner: Option, +} + +impl Vacated { + /// Spare backing to free off the device mutex. + pub(crate) fn spares(pages: Option, ring: Option, + kit: Option) -> Self { + Self { _alias: None, pages, _descriptors: None, ring, _kit: kit, owner: None } + } + /// The owner the pages and ring go back to. + pub(crate) fn returns_to(&self) -> Option { + self.owner + } + /// The pages and ring, to keep for their owner. Whatever is put back is freed with the rest. + pub(crate) fn backing(&mut self) -> (&mut Option, &mut Option) { + (&mut self.pages, &mut self.ring) + } + /// Drops the client views of the backing now. + pub(crate) fn drop_aliases(&mut self) { + drop(self._alias.take()); + drop(self._descriptors.take()); + } } pub(crate) struct Binding { @@ -135,6 +162,13 @@ impl DescriptorRing { )?; Ok(Self { low, object }) } + + /// Clears the ring for its owner's next queue, as the pool clears a reused object. The caller + /// has seen the firmware consume the release of the queue that held it. + pub(crate) fn clear(&mut self) { + self.object.bytes_mut().fill(0); + fence(Ordering::SeqCst); + } } /// Firmware-shared storage of one compute QID, separate from its common kick ring. @@ -735,6 +769,9 @@ pub(crate) struct Queue { /// The owner re-arming this vacant queue: only it builds the fresh backing, so concurrent /// waiters do not each build a pool for the same queue. rearm_for: Option, + /// The owner whose compute backing (pool pages, descriptor ring) this queue holds: it goes + /// back to that owner when the queue gives it back. None once the owner closed. + backing_owner: Option, configuration: Option, m5_install: Option, /// Bit `p` set once a work slot of priority class `p` named this queue. @@ -774,37 +811,6 @@ pub(crate) struct Queue { impl Queue { /// The caller reserves a QID first, cancels it on construction failure, and retains every /// successfully installed queue until processor stop. Shared VM apertures precede this call. - pub(crate) fn new( - kit: Kit, - pages: crate::g17::freelist::Pages, - ring: DescriptorRing, - id: kick::Id, - owner: u64, - context: Arc, - pointers: PointerLayout, - operand_state: &'static OperandState, - board: Option<&'static Board>, - program: ComputeProgram, - m5: bool, - mcache: bool, - ) -> Result { - Self::new_channel( - kit, - pages, - ring, - id, - owner, - context, - pointers, - operand_state, - board, - program, - m5, - mcache, - 0, - ) - } - #[expect( clippy::too_many_arguments, reason = "A sibling compute queue takes the same physical graph inputs plus its channel \ @@ -867,6 +873,7 @@ impl Queue { kill_wait: None, installed: false, rearm_for: None, + backing_owner: Some(owner), configuration: None, m5_install: None, outer_started: 0, @@ -2043,6 +2050,42 @@ impl Queue { pub(crate) fn bind_owner(&mut self, owner: u64, context: Arc) -> Result { self.bind_owner_channel(owner, context, 0) } + /// The owner whose compute backing this queue holds. + pub(crate) fn backing_owner(&self) -> Option { + self.backing_owner + } + /// Whether `owner` may be bound to the backing this queue holds: its own, or one whose owner + /// closed. Another open owner's backing goes back to it first. + pub(crate) fn backing_free_for(&self, owner: u64) -> bool { + self.backing_owner.is_none_or(|holder| holder == owner) + } + /// Whether the pool pages this queue holds, given back or not, serve `required`. + pub(crate) fn backing_fits(&self, required: ComputeCapacity) -> bool { + self.pool.fits_capacity(required) + } + /// `owner` closed: its backing here is no longer kept for it. + pub(crate) fn untag_backing(&mut self, owner: u64) { + if self.backing_owner == Some(owner) { + self.backing_owner = None; + } + } + /// Takes the backing of a queue that was never published, before the queue is dropped, so + /// that it goes back to its owner. + pub(crate) fn take_backing(&mut self) -> Vacated { + let binding = self.binding.as_mut(); + let (alias, descriptors) = match binding { + Some(binding) => (binding.pool_alias.take(), binding.descriptors.take()), + None => (None, None), + }; + Vacated { + _alias: alias, + pages: self.pool.take_pages(), + _descriptors: descriptors, + ring: self.graph.vacate_ring(), + _kit: None, + owner: self.backing_owner.take(), + } + } /// Binds a reusable physical queue with its own dedicated compute pool as an additional /// compute channel of `owner`. pub(crate) fn bind_sibling( @@ -2062,7 +2105,7 @@ impl Queue { context: Arc, channel_index: u8, ) -> Result { - if !self.reusable() { + if !self.reusable() || !self.backing_free_for(owner) { return Err(EBUSY); } self.source_hint.reset_for_owner(&self.source_readers)?; @@ -2145,6 +2188,10 @@ impl Queue { if same_vm { 2 } else { 1 }, ); self.owner = Some(owner); + // A closed owner's backing is the binding owner's from now on. + if self.pool.populated() { + self.backing_owner.get_or_insert(owner); + } self.channel_index = channel_index; self.heavy_run = 0; self.rearm_for = None; @@ -2236,9 +2283,11 @@ impl Queue { let ring = self.graph.vacate_ring(); Some(Vacated { _alias: None, - _pages: None, + pages: None, _descriptors: descriptors, - _ring: ring, + ring, + _kit: None, + owner: self.backing_owner.take(), }) } /// An idle retained queue whose USC backing may be given back. @@ -2423,9 +2472,11 @@ impl Queue { self.release_sent_ns = None; Ok(Some(Vacated { _alias: alias, - _pages: pages, + pages, _descriptors: descriptors, - _ring: ring, + ring, + _kit: None, + owner: self.backing_owner.take(), })) } /// Installs fresh backing into a vacant pool; returns the descriptor row data @@ -2433,6 +2484,7 @@ impl Queue { /// ring to drop off-lock. pub(crate) fn rearm( &mut self, + owner: u64, pages: crate::g17::freelist::Pages, ring: DescriptorRing, ) -> Result<(PoolDescriptor, Option)> { @@ -2458,10 +2510,13 @@ impl Queue { self.needs_fresh_backing = false; let vacated = (old_ring.is_some() || descriptors.is_some()).then_some(Vacated { _alias: None, - _pages: None, + pages: None, _descriptors: descriptors, - _ring: old_ring, + ring: old_ring, + _kit: None, + owner: self.backing_owner, }); + self.backing_owner = Some(owner); Ok((self.pool.descriptor()?, vacated)) } pub(crate) fn pool_fits(&self, required: ComputeCapacity) -> bool { @@ -2536,11 +2591,15 @@ impl Queue { self.release_sent_ns = None; self.growing = false; self.growth = None; + let owner = self.backing_owner; + self.backing_owner = self.owner; Ok(Vacated { _alias: old_alias, - _pages: pages.take(), + pages: pages.take(), _descriptors: None, - _ring: None, + ring: None, + _kit: None, + owner, }) } diff --git a/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs new file mode 100644 index 0000000000000..c0b323b35aec2 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The spare compute backing of one logical queue (owner). +//! +//! An owner's compute sets (pool pages and a descriptor ring) are allocated in its SUBMIT ioctl, +//! charged to its client, and are its own until it closes: a physical queue holds one while the +//! owner is bound to it, and gives it back here when the queue is taken from the owner. A +//! publication takes from here and never allocates. A fresh queue also takes a [`Kit`] from here. +//! +//! [`Kit`]: super::Kit + +use crate::g17::freelist::ComputeCapacity; +use kernel::prelude::*; + +/// Spare pages an owner keeps at most: with more, one is covered by another (pages of one family +/// are ordered by size, and M5 has two block sizes), and the covered one is freed. +const PAGES: usize = 4; +/// Spare descriptor rings an owner keeps at most: one for each compute channel it may hold. +const RINGS: usize = crate::g17::pairs::COMPUTE_CHANNELS_MAX; + +/// Pool pages as a spare: what they can serve. +pub(crate) trait Capacity { + /// Whether these pages serve `required`. + fn fits(&self, required: ComputeCapacity) -> bool; + /// Whether these pages serve everything `other` serves. + fn covers(&self, other: &Self) -> bool; +} + +/// The spares of one owner: pages, descriptor rings and at most one kit. +pub(crate) struct Spares { + pages: [Option

; PAGES], + rings: [Option; RINGS], + kit: Option, +} + +impl Spares { + pub(crate) fn new() -> Self { + Self { pages: Default::default(), rings: Default::default(), kit: None } + } + + /// Whether spare pages serve `required`. + pub(crate) fn fits(&self, required: ComputeCapacity) -> bool { + self.pages.iter().flatten().any(|pages| pages.fits(required)) + } + + pub(crate) fn has_ring(&self) -> bool { + self.rings.iter().any(Option::is_some) + } + + pub(crate) fn has_kit(&self) -> bool { + self.kit.is_some() + } + + /// Whether nothing is spare. + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn is_empty(&self) -> bool { + self.pages.iter().all(Option::is_none) && !self.has_ring() && self.kit.is_none() + } + + /// The smallest spare pages that serve `required`: larger ones stay for larger needs. + pub(crate) fn take_pages(&mut self, required: ComputeCapacity) -> Option

{ + let pages = &self.pages; + let index = (0..PAGES) + .filter(|&i| pages[i].as_ref().is_some_and(|p| p.fits(required))) + .min_by(|&a, &b| { + let (a, b) = (pages[a].as_ref(), pages[b].as_ref()); + match (a, b) { + (Some(a), Some(b)) if b.covers(a) && !a.covers(b) => core::cmp::Ordering::Less, + (Some(a), Some(b)) if a.covers(b) && !b.covers(a) => core::cmp::Ordering::Greater, + _ => core::cmp::Ordering::Equal, + } + })?; + self.pages[index].take() + } + + pub(crate) fn take_ring(&mut self) -> Option { + self.rings.iter_mut().find_map(Option::take) + } + + pub(crate) fn take_kit(&mut self) -> Option { + self.kit.take() + } + + /// Keeps `pages`; returns what to free instead: nothing while a slot is free, else spare + /// pages another spare (or `pages`) covers, else `pages` itself. + pub(crate) fn put_pages(&mut self, pages: P) -> Option

{ + if let Some(slot) = self.pages.iter_mut().find(|slot| slot.is_none()) { + *slot = Some(pages); + return None; + } + let covered = |i: usize| { + let Some(candidate) = self.pages[i].as_ref() else { return false }; + pages.covers(candidate) + || (0..PAGES).any(|j| j != i && self.pages[j].as_ref().is_some_and(|p| p.covers(candidate))) + }; + match (0..PAGES).find(|&i| covered(i)) { + Some(i) => self.pages[i].replace(pages), + None => Some(pages), + } + } + + /// Keeps `ring`; returns it if every slot is taken. + pub(crate) fn put_ring(&mut self, ring: R) -> Option { + match self.rings.iter_mut().find(|slot| slot.is_none()) { + Some(slot) => { + *slot = Some(ring); + None + } + None => Some(ring), + } + } + + /// Keeps `kit`; returns it if one is kept already. + pub(crate) fn put_kit(&mut self, kit: K) -> Option { + if self.kit.is_some() { + return Some(kit); + } + self.kit = Some(kit); + None + } + + /// Takes some spares out, for freeing: one each of pages, ring and kit at most. None once + /// nothing is spare. + #[allow(clippy::type_complexity)] + pub(crate) fn take_any(&mut self) -> Option<(Option

, Option, Option)> { + let item = (self.pages.iter_mut().find_map(Option::take), self.take_ring(), self.kit.take()); + (item.0.is_some() || item.1.is_some() || item.2.is_some()).then_some(item) + } + + /// Takes everything out, for freeing. + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn take_all(&mut self) -> Self { + core::mem::replace(self, Self::new()) + } +} + +#[kunit_tests(asahi_g17_compute_reserve)] +mod tests { + use super::*; + use core::sync::atomic::{AtomicUsize, Ordering}; + + /// Test items freed so far. KUnit runs a suite's cases one after another. + static FREED: AtomicUsize = AtomicUsize::new(0); + + /// Pages of `0` blocks; `1` tells sizes that do not compare apart (M5's two block sizes). + struct Pages(usize, u8); + impl Drop for Pages { + fn drop(&mut self) { + FREED.fetch_add(1, Ordering::Relaxed); + } + } + impl Capacity for Pages { + fn fits(&self, required: ComputeCapacity) -> bool { + matches!(required, ComputeCapacity::Blocks(blocks) if self.1 == 0 && self.0 >= blocks) + } + fn covers(&self, other: &Self) -> bool { + self.1 == other.1 && self.0 >= other.0 + } + } + struct Ring; + impl Drop for Ring { + fn drop(&mut self) { + FREED.fetch_add(1, Ordering::Relaxed); + } + } + struct Kit; + impl Drop for Kit { + fn drop(&mut self) { + FREED.fetch_add(1, Ordering::Relaxed); + } + } + type Test = Spares; + + fn freed() -> usize { + FREED.load(Ordering::Relaxed) + } + + #[test] + fn moving_spares_frees_nothing() { + let before = freed(); + let mut spares = Test::new(); + assert!(spares.is_empty()); + assert!(spares.put_pages(Pages(21, 0)).is_none()); + assert!(spares.put_ring(Ring).is_none()); + assert!(spares.put_kit(Kit).is_none()); + assert!(spares.fits(ComputeCapacity::Blocks(21)) && spares.has_ring() && spares.has_kit()); + assert!(!spares.fits(ComputeCapacity::Blocks(22))); + let (pages, ring, kit) = (spares.take_pages(ComputeCapacity::Blocks(21)), spares.take_ring(), + spares.take_kit()); + assert!(pages.is_some() && ring.is_some() && kit.is_some()); + assert!(spares.is_empty()); + // Back again, as a queue taken from its owner gives them back: still nothing freed. + assert!(spares.put_pages(pages.unwrap()).is_none()); + assert!(spares.put_ring(ring.unwrap()).is_none()); + assert!(spares.put_kit(kit.unwrap()).is_none()); + assert_eq!(freed(), before); + drop(spares); + // Each spare is freed once. + assert_eq!(freed(), before + 3); + } + + #[test] + fn the_smallest_fitting_pages_are_taken() { + let mut spares = Test::new(); + for blocks in [30, 21, 24] { + assert!(spares.put_pages(Pages(blocks, 0)).is_none()); + } + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(22)).map(|p| p.0), Some(24)); + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(31)).map(|p| p.0), None); + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(21)).map(|p| p.0), Some(21)); + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(21)).map(|p| p.0), Some(30)); + assert!(spares.is_empty()); + } + + #[test] + fn a_full_owner_frees_only_covered_pages() { + let mut spares = Test::new(); + // Two sizes that do not compare apart, two of each. + for pages in [Pages(21, 0), Pages(21, 1), Pages(24, 1), Pages(30, 0)] { + assert!(spares.put_pages(pages).is_none()); + } + // Full: a covered spare goes, never one that serves a need nothing else serves. + let freed = spares.put_pages(Pages(40, 0)).unwrap(); + // Never one that serves a need nothing else serves. + assert!(freed.1 == 0 || freed.0 == 21); + assert!(spares.fits(ComputeCapacity::Blocks(40))); + // Pages a spare covers are themselves what goes. + let freed = spares.put_pages(Pages(21, 1)).unwrap(); + assert_eq!((freed.0, freed.1), (21, 1)); + assert!(spares.put_ring(Ring).is_none() && spares.put_ring(Ring).is_none() + && spares.put_ring(Ring).is_none()); + // Rings beyond the channels are freed. + assert!(spares.put_ring(Ring).is_some()); + assert!(spares.put_kit(Kit).is_none() && spares.put_kit(Kit).is_some()); + } + + #[test] + fn taking_all_frees_each_spare_once() { + let mut spares = Test::new(); + assert!(spares.put_pages(Pages(21, 0)).is_none()); + assert!(spares.put_ring(Ring).is_none()); + let before = freed(); + let all = spares.take_all(); + assert!(spares.is_empty()); + assert_eq!(freed(), before); + drop(all); + assert_eq!(freed(), before + 2); + drop(spares); + assert_eq!(freed(), before + 2); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 802d827b3e1a3..588db84973df6 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -262,6 +262,10 @@ impl Queue { } self.prune_frontier(index); self.prune_frontier(other); + // Claimed before the SUBMIT provisions this command's compute backing, so nothing it was + // given back for it is freed before the command is dropped. + let claim = (engine == Engine::Compute) + .then(|| super::context::ComputeClaim::new(&self.context)); if engine == Engine::Compute { self.ensure_compute(&command)?; } @@ -441,6 +445,7 @@ impl Queue { completion, checked_inputs, firmware, + claim, )?; let scheduler = match engine { Engine::Render => &mut self.render, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index e490142ff88e3..65c4defd71339 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -255,6 +255,61 @@ impl Drop for ComputeSlot { } } +/// A logical queue's spare compute backing ([`compute::reserve`]): pool pages and descriptor rings +/// charged to its client, and a kit of device memory for a fresh queue. +pub(super) struct OwnerReserve { + owner: u64, + context: Arc, + spares: compute::reserve::Spares, + /// A sibling channel found no backing: the next SUBMIT provisions some, if it can. + wants_sibling: bool, +} + +impl OwnerReserve { + pub(super) fn new(owner: u64, context: Arc) -> Self { + Self { owner, context, spares: compute::reserve::Spares::new(), wants_sibling: false } + } +} + +/// What an owner's publication at some capacity would lack ([`Registry::compute_lacks`]). +#[derive(Clone, Copy, Default)] +pub(super) struct Lacks { + pages: bool, + ring: bool, + kit: bool, + /// A sibling's backing, provisioned if it can be. + sibling: bool, +} + +impl Lacks { + fn any(&self) -> bool { + self.pages || self.ring || self.kit || self.sibling + } +} + +/// Keeps the pages and ring a queue gave back for their owner while it has compute commands +/// ([`Context::compute_claimed`]); what is not kept stays in `vacated`, to be freed with it. An +/// owner without commands is idle: its backing is freed, as before it had a reserve. +fn keep_backing(reserves: &mut KVec>, vacated: &mut compute::Vacated) { + let Some(owner) = vacated.returns_to() else { return }; + let Some(reserve) = reserves.iter_mut().find(|reserve| reserve.owner == owner) else { return }; + if !reserve.context.compute_claimed() { + return; + } + let (pages, ring) = vacated.backing(); + if let Some(mut returned) = pages.take() { + // Unreset tables would hand the firmware the old free list. + *pages = match returned.reset() { + Ok(()) => reserve.spares.put_pages(returned), + Err(_) => Some(returned), + }; + } + if let Some(mut returned) = ring.take() { + returned.clear(); + *ring = reserve.spares.put_ring(returned); + } +} + pub(super) struct Registry { pub(super) qids: kick::QueueIds, pub(super) buffers: BufferIds, @@ -269,6 +324,9 @@ pub(super) struct Registry { /// needs them: a publication never allocates them. prepared_shared: Option, prepared_scheduler: Option, + /// The spare compute backing of each logical queue that submitted compute work, from its + /// first compute SUBMIT until it closes ([`compute::reserve`]). + reserves: KVec>, replay_outer_wait: Option, /// A compute replay waits for its owner's renders to park or idle (compute_replay). replay_consumer_wait: Option, @@ -322,6 +380,7 @@ impl Registry { }, prepared_shared: None, prepared_scheduler: None, + reserves: KVec::with_capacity(kick::queue_limit(variant.qid_floor) as usize, GFP_KERNEL)?, replay_outer_wait: None, replay_consumer_wait: None, observations: compute::retirement::Batch::new()?, @@ -435,7 +494,7 @@ impl Registry { continue; } &mut vacant - } else if queue.pool_serves(vm) { + } else if queue.pool_serves(vm) && queue.backing_free_for(owner) { if queue.needs_fresh_backing() || !queue.pool_fits(required) || !queue.has_ring() { continue; } @@ -564,6 +623,162 @@ impl Registry { Ok(()) } + fn owner_reserve(&mut self, owner: u64) -> Option<&mut OwnerReserve> { + self.reserves.iter_mut().find(|reserve| reserve.owner == owner).map(|reserve| &mut **reserve) + } + + fn spares(&self, owner: u64) -> Option<&compute::reserve::Spares> { + self.reserves.iter().find(|reserve| reserve.owner == owner).map(|reserve| &reserve.spares) + } + + /// What a publication of `owner` at `required` would lack: its spares, and the backing its + /// queues hold (also while they give it back), serve it otherwise. + pub(super) fn compute_lacks(&self, owner: u64, required: super::freelist::ComputeCapacity) -> Lacks { + let spares = self.spares(owner); + let queues = || self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()); + let held = || queues().filter(|queue| queue.backing_owner() == Some(owner)); + let pages = !spares.is_some_and(|spares| spares.fits(required)) + && !held().any(|queue| queue.backing_fits(required)); + let ring = !spares.is_some_and(|spares| spares.has_ring()) && !held().any(|queue| queue.has_ring()); + // A kit for an owner without a queue of its own: a QID that frees up later is built on + // without allocating. One with a queue gets a channel through an existing queue, which + // stays until processor stop. + let kit = !spares.is_some_and(|spares| spares.has_kit()) + && !queues().any(|queue| queue.backing_owner() == Some(owner) || queue.owner() == Some(owner)); + let sibling = self.reserves.iter().any(|reserve| reserve.owner == owner && reserve.wants_sibling); + Lacks { pages, ring, kit, sibling } + } + + /// Keeps what `owner`'s SUBMIT provisioned, in `reserve` if the owner has none yet. Returns + /// what is not kept, to free off the device mutex. + pub(super) fn stock( + &mut self, + owner: u64, + mut reserve: Option>, + pages: Option, + ring: Option, + kit: Option, + ) -> (compute::Vacated, Option>) { + if self.owner_reserve(owner).is_none() { + if let Some(new) = reserve.take() { + if let Err(rejected) = self.reserves.push_within_capacity(new) { + reserve = Some(rejected.0); + } + } + } + let Some(target) = self.owner_reserve(owner) else { + return (compute::Vacated::spares(pages, ring, kit), reserve); + }; + target.wants_sibling = false; + let pages = pages.and_then(|pages| target.spares.put_pages(pages)); + let ring = ring.and_then(|ring| target.spares.put_ring(ring)); + let kit = kit.and_then(|kit| target.spares.put_kit(kit)); + (compute::Vacated::spares(pages, ring, kit), reserve) + } + + /// Takes `owner`'s spare pages that serve `required` and a ring, for a queue it re-arms: + /// both or neither. + fn take_set(&mut self, owner: u64, required: super::freelist::ComputeCapacity) + -> Option<(super::freelist::Pages, compute::DescriptorRing)> { + let spares = &mut self.owner_reserve(owner)?.spares; + if !spares.fits(required) || !spares.has_ring() { + return None; + } + Some((spares.take_pages(required)?, spares.take_ring()?)) + } + + fn has_kit(&self, owner: u64) -> bool { + self.spares(owner).is_some_and(|spares| spares.has_kit()) + } + + /// Whether `owner`'s spares build a fresh queue at `required` ([`Self::take_fresh`]). + fn can_build_fresh(&self, owner: u64, required: super::freelist::ComputeCapacity) -> bool { + self.spares(owner) + .is_some_and(|spares| spares.has_kit() && spares.has_ring() && spares.fits(required)) + } + + fn take_fresh(&mut self, owner: u64, required: super::freelist::ComputeCapacity) + -> Option<(compute::Kit, super::freelist::Pages, compute::DescriptorRing)> { + if !self.can_build_fresh(owner, required) { + return None; + } + let spares = &mut self.owner_reserve(owner)?.spares; + Some((spares.take_kit()?, spares.take_pages(required)?, spares.take_ring()?)) + } + + fn take_pages(&mut self, owner: u64, required: super::freelist::ComputeCapacity) + -> Option { + self.owner_reserve(owner)?.spares.take_pages(required) + } + + /// Gives `owner` back what one of its publications took and did not use. Returns what is + /// not kept, to free off the device mutex. + fn put_back( + &mut self, + owner: u64, + pages: Option, + ring: Option, + kit: Option, + ) -> compute::Vacated { + match self.owner_reserve(owner) { + Some(reserve) => compute::Vacated::spares( + pages.and_then(|pages| reserve.spares.put_pages(pages)), + ring.and_then(|ring| reserve.spares.put_ring(ring)), + kit.and_then(|kit| reserve.spares.put_kit(kit)), + ), + None => compute::Vacated::spares(pages, ring, kit), + } + } + + /// A sibling channel of `owner` found no backing: its next SUBMIT provisions some. + fn want_sibling(&mut self, owner: u64) { + if let Some(reserve) = self.owner_reserve(owner) { + reserve.wants_sibling = true; + } + } + + /// Keeps what a queue gave back for its owner ([`keep_backing`]). + fn keep_returned(&mut self, vacated: &mut compute::Vacated) { + keep_backing(&mut self.reserves, vacated); + } + + /// Asks the idle queues holding `owner`'s backing that serves `required` to give it back: a + /// pool pass releases them, and the owner keeps the backing. Whether any does. + fn recall_backing(&mut self, owner: u64, required: super::freelist::ComputeCapacity) -> bool { + let mut recalled = false; + for mut queue in self.compute.iter_mut().flatten() + .filter_map(|entry| entry.queue.as_deref_mut()) + .filter(|queue| queue.backing_owner() == Some(owner) && queue.reusable() + && !queue.pool_vacant() && queue.backing_fits(required)) + { + queue.require_fresh_backing(); + recalled = true; + } + recalled + } + + /// `owner` closed: the backing its queues hold is no longer kept for it, and its spares are + /// returned, to be freed off the device mutex. + pub(super) fn close_reserve(&mut self, owner: u64) -> Option> { + for mut queue in self.compute.iter_mut().flatten().filter_map(|entry| entry.queue.as_deref_mut()) { + queue.untag_backing(owner); + } + let index = self.reserves.iter().position(|reserve| reserve.owner == owner)?; + Some(self.reserves.swap_remove(index)) + } + + /// The spares of owners without compute commands go to `deferred`, to be freed: an idle + /// owner's next SUBMIT provisions again. + fn trim_reserves(&mut self, deferred: &mut DeferredBatch) { + for reserve in self.reserves.iter_mut().filter(|reserve| !reserve.context.compute_claimed()) { + while deferred.vacated_room() { + let Some((pages, ring, kit)) = reserve.spares.take_any() else { break }; + deferred.defer_vacated(compute::Vacated::spares(pages, ring, kit)); + } + } + } + /// Picks the bound compute channel of `owner` for `packet`. A command with cross-queue input /// sources always takes the primary channel, so a chain of semaphore hops between queues /// stays on one ring per queue. Dependent commands stay on the sole active channel when only @@ -723,7 +938,8 @@ impl Registry { if let Some(rebind) = self.bind_reusable(owner, context, required, admission)? { return Ok(rebind); } - if self.compute_qid_fits() { + // A fresh queue is built from the kit the owner's SUBMIT provisioned. + if self.compute_qid_fits() && self.has_kit(owner) { return Ok(Rebind::Fresh); } if self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) @@ -740,7 +956,8 @@ impl Registry { .iter() .flatten() .filter_map(|entry| entry.queue.as_deref()) - .filter(|queue| queue.reusable() && !queue.pool_vacant() && !queue.pool_serves(vm)) + .filter(|queue| queue.reusable() && !queue.pool_vacant() + && (!queue.pool_serves(vm) || !queue.backing_free_for(owner))) .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound))) .map(|queue| (queue.released_at(), queue.qid())) .min_by_key(|(key, _)| *key) @@ -757,7 +974,8 @@ impl Registry { .filter(|queue| queue.shareable()) .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound))) // A channel serving the requester's VM first, then the best fit, then the longest idle. - .map(|queue| ((!queue.pool_serves(vm), !queue.pool_fits(required), queue.last_published()), queue.qid())) + .map(|queue| ((!queue.pool_serves(vm) || !queue.backing_free_for(owner), + !queue.pool_fits(required), queue.last_published()), queue.qid())) .min_by_key(|(key, _)| *key) .map(|(_, qid)| qid); let Some(qid) = idle else { return Err(ENOSPC); }; @@ -773,8 +991,9 @@ impl Registry { if !queue.share_idle()? { return Err(ENOSPC); } - if !queue.pool_serves(vm) { - // Its backing holds another VM's scratch: vacate it, then re-arm fresh. + if !queue.pool_serves(vm) || !queue.backing_free_for(owner) { + // Its backing holds another VM's scratch, or another open owner's backing, + // which goes back to it: vacate it, then re-arm fresh. queue.require_fresh_backing(); return Err(ENOSPC); } @@ -858,7 +1077,11 @@ impl Registry { } continue; } - if !queue.pool_fits(required) || !queue.pool_serves(context.vm()) { continue; } + if !queue.pool_fits(required) || !queue.pool_serves(context.vm()) + || !queue.backing_free_for(owner) + { + continue; + } queue.bind_owner(owner, context.clone())?; return Ok(Some(Rebind::Done)); } @@ -878,6 +1101,7 @@ impl Registry { pub(super) fn rearm_compute( &mut self, qid: u8, + owner: u64, pages: crate::g17::freelist::Pages, ring: compute::DescriptorRing, ) -> Result<(super::freelist::PoolDescriptor, Option)> { @@ -888,7 +1112,7 @@ impl Registry { .filter_map(|entry| entry.queue.as_deref_mut()) .find(|queue| queue.qid() == qid) .ok_or(EAGAIN)?; - queue.rearm(pages, ring) + queue.rearm(owner, pages, ring) } /// Reserves the vacant queue `qid` for `owner`'s re-arm, as [`Self::bind_reusable`] does for a @@ -1028,7 +1252,8 @@ impl Registry { .filter_map(|entry| entry.queue.as_deref_mut()) { if !deferred.vacated_room() { break; } - if let Some(vacated) = queue.observe_vacancy(consumer, producer)? { + if let Some(mut vacated) = queue.observe_vacancy(consumer, producer)? { + keep_backing(&mut self.reserves, &mut vacated); deferred.defer_vacated(vacated); freed += 1; } @@ -1617,15 +1842,20 @@ impl Backend { /// An empty registry entry prevents reusing the QID/free-list identity while /// its old aliases still occupy canonical or client addresses. Recovery joins /// this lease before removing the session, even if its epoch was invalidated. + /// The queue's backing goes back to its owner ([`keep_backing`]). fn finish_uninstalled_compute( &self, retired: Option<(ComputeReservation, KBox)>, ) -> Result { - let Some((reservation, queue)) = retired else { return Ok(()); }; + let Some((reservation, mut queue)) = retired else { return Ok(()); }; + let mut backing = queue.take_backing(); drop(queue); + backing.drop_aliases(); let mut state = self.shared.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; firmware.queues.cancel_compute(reservation)?; + firmware.queues.keep_returned(&mut backing); drop(state); + drop(backing); // The slot and its never-published QID are free again. self.shared.channels.notify(); Ok(()) @@ -1640,6 +1870,70 @@ impl Backend { }) } + /// Builds and installs a fresh compute queue for `reservation` as this owner's channel + /// `channel_index`, from the kit and backing its SUBMIT provisioned: under the device mutex, + /// allocating no device memory. The pool row, and on G17P the global scheduler, are installed + /// first. On failure the reservation is cancelled, or the queue that was built comes back for + /// [`Self::finish_uninstalled_compute`]. Unused spares come back to be freed off the mutex. + fn install_fresh( + &self, + firmware: &mut super::Firmware, + reservation: ComputeReservation, + required: super::freelist::ComputeCapacity, + channel_index: u8, + ) -> (Result, Option, compute::Vacated) { + let none = || compute::Vacated::spares(None, None, None); + let Some((kit, pages, ring)) = firmware.queues.take_fresh(self.owner, required) else { + let _ = firmware.queues.cancel_compute(reservation); + return (Err(ENOSPC), None, none()); + }; + let installed = (|| { + firmware.queues.reserved(reservation)?; + firmware.init.install_compute_pool( + compute::pool_descriptor(&pages, reservation.id.qid())?)?; + // The global scheduler is retained even if this queue's graph fails. + // It is G17P compute state; M5 has none. + if !self.context.is_m5() && !firmware.init.has_compute_scheduler() { + let scheduler = firmware.queues.prepared_scheduler.take().ok_or(EIO)?; + firmware.init.install_compute_scheduler(scheduler)?; + } + Ok(()) + })(); + if let Err(error) = installed { + let unused = firmware.queues.put_back(self.owner, Some(pages), Some(ring), Some(kit)); + let _ = firmware.queues.cancel_compute(reservation); + return (Err(error), None, unused); + } + // Fails only on a broken invariant, or a kernel allocation too small to fail. + let queue = compute::Queue::new_channel( + kit, + pages, + ring, + reservation.id, + self.owner, + self.context.clone(), + self.shared.variant.pointers, + self.shared.operand_state, + self.shared.m5_board, + self.shared.variant.compute, + self.context.is_m5(), + self.shared.variant.mcache, + channel_index, + ) + .and_then(|queue| Ok(KBox::new(queue, GFP_KERNEL)?)); + let mut built = match queue { + Ok(queue) => Some(queue), + Err(error) => { + let _ = firmware.queues.cancel_compute(reservation); + return (Err(error), None, none()); + } + }; + match firmware.queues.install_compute(reservation, &mut built) { + Ok(()) => (Ok(()), None, none()), + Err(error) => (Err(error), built.map(|queue| (reservation, queue)), none()), + } + } + fn grow_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; { @@ -1659,17 +1953,16 @@ impl Backend { } } let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; - let uat = self.shared.state.lock().as_ref().ok_or(ENODEV)?.uat.clone(); - let alloc = super::object::Allocator { dev: &dev, uat: &uat, client: None }; - let mut pages = Some(super::freelist::Pages::for_compute(&alloc, required, - self.context.vm().memory_client())?); - let mut alias = Some(pages.as_mut().ok_or(EIO)?.map_client(self.context.vm())?); + // This owner's own pages, which its SUBMIT provisioned or a queue gave back, taken once + // growth needs them. + let mut pages = None; + let mut alias = None; let mut deferred = DeferredBatch::publication()?; let mut growth = None; let result = (|| loop { // Growth waits for this queue's retirement and for firmware to consume the pool - // release; both are progress the event worker reports. + // release; both are progress the event worker reports. So does the return of this + // owner's pages from a queue that gives them back. let observed = self.shared.progress.observe(); let mut retired_siblings: PerChannel = Default::default(); let result = (|| { @@ -1682,8 +1975,21 @@ impl Backend { // Release sibling channels before growing the primary channel so undersized // sibling pools are detached and later re-acquired at the grown capacity. firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?; + if firmware.queues.compute_primary(self.owner).ok_or(EAGAIN)?.pool_fits(required) { + return Ok(None); + } + if pages.is_none() { + pages = firmware.queues.take_pages(self.owner, required); + if pages.is_none() { + // An idle queue holds them: the next pool pass gives them back. + firmware.queues.recall_backing(self.owner, required); + return Err(EAGAIN); + } + } + if alias.is_none() { + alias = Some(pages.as_mut().ok_or(EIO)?.map_client(self.context.vm())?); + } let mut queue = firmware.queues.compute_primary(self.owner).ok_or(EAGAIN)?; - if queue.pool_fits(required) { return Ok(None); } if growth.is_none() { let notify = queue.begin_growth(&firmware.init, required)?; // Capture physical identity before any following fallible @@ -1694,7 +2000,11 @@ impl Backend { firmware.primary.notify(crate::g17::MSG_CONTROL_NOTIFY)?; } } - queue.finish_growth(&firmware.init, &mut pages, &mut alias).map(Some) + let mut old = queue.finish_growth(&firmware.init, &mut pages, &mut alias)?; + drop(queue); + // The smaller pages stay this owner's while it has compute commands. + firmware.queues.keep_returned(&mut old); + Ok(Some(old)) })(); self.finish_retired_compute(&mut retired_siblings)?; deferred.finish(); @@ -1707,9 +2017,9 @@ impl Backend { Err(error) => return Err(error), } })(); + let mut retired = None; if result.is_err() { if let Some(token) = growth { - let mut retired = None; let mut state = self.shared.state.lock(); if let Some(firmware) = state.as_deref_mut() { for index in 0..firmware.queues.compute.len() { @@ -1724,42 +2034,39 @@ impl Backend { } } } - drop(state); - // Tentative replacement mappings also belong to this builder. - // Discard them before a fresh QID can acquire a successor. - drop(alias.take()); - drop(pages.take()); - self.finish_uninstalled_compute(retired)?; - self.shared.queue_events(); } } + // Tentative replacement mappings also belong to this builder. Discard them before a + // fresh QID can acquire a successor; unused pages stay this owner's. + drop(alias.take()); + if let Some(unused) = pages.take() { + let mut state = self.shared.state.lock(); + let unused = state.as_deref_mut() + .map(|firmware| firmware.queues.put_back(self.owner, Some(unused), None, None)); + drop(state); + drop(unused); + } + if growth.is_some() && result.is_err() { + self.finish_uninstalled_compute(retired)?; + self.shared.queue_events(); + } result } - /// Re-arms the vacant queue `qid` reserved for this owner with fresh zeroed backing, built - /// without the device mutex, and binds it as compute channel `channel_index` (0: the primary; - /// a sibling only while that index is still the owner's next free one). Some(true): bound; - /// Some(false): retry (the preparation epoch changed, the queue is no longer re-armable or - /// the sibling index was taken); None: no memory for the backing now. + /// Re-arms the vacant queue `qid` reserved for this owner with its own spare backing, and + /// binds it as compute channel `channel_index` (0: the primary; a sibling only while that + /// index is still the owner's next free one). Allocates nothing: the owner's SUBMIT + /// provisioned the backing, or a queue gave it back. Some(true): bound; Some(false): retry + /// (the preparation epoch changed, the queue is no longer re-armable or the sibling index + /// was taken); None: the owner's backing is not back yet, or a sibling has none. fn rearm_vacant( &self, qid: u8, channel_index: u8, required: super::freelist::ComputeCapacity, - alloc: &super::object::Allocator<'_>, - objects: &Arc, lease: &super::preparation::Lease, admission: &Admission<'_>, ) -> Result> { - let built = (|| -> Result<_> { - let pages = crate::g17::freelist::Pages::for_compute(alloc, required, - self.context.vm().memory_client())?; - Ok((pages, compute::DescriptorRing::new(alloc, objects)?)) - })(); - let (pages, ring) = match built { - Err(error) if error == ENOSPC => return Ok(None), - result => result?, - }; let mut state = self.shared.state.lock(); admission.check()?; let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; @@ -1767,8 +2074,6 @@ impl Backend { return Ok(Some(false)); } if let Err(error) = self.admission_open() { drop(state); return Err(error); } - // Leave rejected backing local so it is dropped after the device guard, not in - // rearm(). let ready = firmware.queues.compute.iter().flatten() .filter_map(|entry| entry.queue.as_deref()) .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)) @@ -1776,10 +2081,21 @@ impl Backend { || firmware.queues.next_sibling_index(self.owner, self.compute_channels) == Some(channel_index)); if !ready { drop(state); return Ok(Some(false)); } - let (descriptor, vacated) = match firmware.queues.rearm_compute(qid, pages, ring) { + let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else { + if channel_index != 0 { + firmware.queues.want_sibling(self.owner); + } + return Ok(None); + }; + let (descriptor, mut vacated) = match firmware.queues.rearm_compute(qid, self.owner, pages, ring) { Err(error) if error == EAGAIN => return Ok(Some(false)), result => result?, }; + // A ring the queue still held goes back to its owner; the rest is dropped after the + // device guard. + if let Some(vacated) = vacated.as_mut() { + firmware.queues.keep_returned(vacated); + } // The firmware consumed this slot's release before the backing // was dropped; the row is rewritten before the queue is kicked. firmware.init.install_compute_pool(descriptor)?; @@ -1806,9 +2122,8 @@ impl Backend { // Sampled before any capacity check of this attempt. let observed = self.shared.channels.observe(); let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; let mut reclaimed = None; - let (uat, objects, reservation) = { + let built = { let mut state = self.shared.state.lock(); admission.check()?; let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; @@ -1832,8 +2147,15 @@ impl Backend { match rebound { Rebind::Done => return Ok(()), Rebind::Grow => { drop(state); drop(lease); return self.grow_compute(required, admission); } - Rebind::Rearm(qid) => (firmware.uat.clone(), firmware.pool.clone(), Err(qid)), + Rebind::Rearm(qid) => Err(qid), Rebind::Fresh => { + // This owner's backing may still be on its way back from a queue. + if !firmware.queues.can_build_fresh(self.owner, required) { + drop(state); + drop(lease); + self.wait_channels(observed, admission, true)?; + continue; + } let reservation = match firmware .queues .reserve_compute_reclaiming(self.owner, &mut reclaimed) @@ -1865,23 +2187,17 @@ impl Backend { } Err(error) => return Err(error), }; - (firmware.uat.clone(), firmware.pool.clone(), Ok(reservation)) + Ok(self.install_fresh(firmware, reservation, required, 0)) } } }; drop(reclaimed); - let alloc = super::object::Allocator { - dev: &dev, - uat: &uat, - client: None, - }; - let reservation = match reservation { - Ok(reservation) => reservation, + let (result, retired, unused) = match built { + Ok(built) => built, Err(qid) => { // bind_reusable reserved `qid` for this owner: any outcome but binding it // ends the reservation, so another owner may re-arm it. - let result = - self.rearm_vacant(qid, 0, required, &alloc, &objects, &lease, admission); + let result = self.rearm_vacant(qid, 0, required, &lease, admission); if !matches!(result, Ok(Some(true))) { if let Some(firmware) = self.shared.state.lock().as_deref_mut() { firmware.queues.release_rearm(qid, self.owner); @@ -1898,75 +2214,11 @@ impl Backend { } } }; - let built = (|| { - let pages = super::freelist::Pages::for_compute(&alloc, required, - self.context.vm().memory_client())?; - let ring = compute::DescriptorRing::new(&alloc, &objects)?; - let kit = compute::Kit::new(&alloc, &objects, self.shared.operand_state, - alloc.uat.is_m5())?; - { - let mut state = self.shared.state.lock(); - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { - return Err(EAGAIN); - } - self.admission_open()?; - firmware.queues.reserved(reservation)?; - firmware.init.install_compute_pool( - compute::pool_descriptor(&pages, reservation.id.qid())?)?; - // The global scheduler is retained even if this queue's graph fails. - // It is G17P compute state; M5 has none. - if !self.context.is_m5() && !firmware.init.has_compute_scheduler() { - let scheduler = firmware.queues.prepared_scheduler.take().ok_or(EIO)?; - firmware.init.install_compute_scheduler(scheduler)?; - } - } - let queue = compute::Queue::new( - kit, - pages, - ring, - reservation.id, - self.owner, - self.context.clone(), - self.shared.variant.pointers, - self.shared.operand_state, - self.shared.m5_board, - self.shared.variant.compute, - alloc.uat.is_m5(), - self.shared.variant.mcache, - )?; - Ok(KBox::new(queue, GFP_KERNEL)?) - })(); - let (mut built, build_error) = match built { - Ok(queue) => (Some(queue), None), - Err(error) => (None, Some(error)), - }; - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() { - Err(EAGAIN) - } else if let Some(error) = build_error { - Err(error) - } else { - admission.check().and_then(|()| firmware.queues.install_compute(reservation, &mut built)) - } - }; + drop(unused); // The old aliases must disappear before a waiting constructor can // reuse the QID and its queue-local free-list identity. Keep the // preparation lease until both mappings and reservation are gone. - drop(built); - if result.is_err() { - let mut state = self.shared.state.lock(); - (*state) - .as_mut() - .ok_or(ENODEV)? - .queues - .cancel_compute(reservation)?; - } + self.finish_uninstalled_compute(retired)?; drop(lease); if result == Err(ENOSPC) { self.wait_channels(observed, admission, true)?; @@ -1978,11 +2230,12 @@ impl Backend { /// Best-effort acquisition of an additional compute channel with its own dedicated compute /// pool for a multi-channel M5 owner, from the source [`Registry::sibling_source`] names: a - /// warm reusable queue is bound at once, a vacant one is re-armed with fresh backing and - /// bound as [`Self::rearm_vacant`] re-arms a primary's, a fresh QID gets a new queue, and an - /// idle queue still holding another VM's pool is given back for the next attempt. An owner - /// waiting for its first channel goes first. Never blocks or fails the submission if no - /// sibling is available. + /// warm reusable queue is bound at once, a vacant one is re-armed with the owner's spare + /// backing and bound as [`Self::rearm_vacant`] re-arms a primary's, a fresh QID gets a new + /// queue from the owner's spares, and an idle queue still holding another VM's (or another + /// owner's) pool is given back for the next attempt. An owner waiting for its first channel + /// goes first. Never blocks or fails the submission if no sibling is available; without + /// spare backing, the owner's next SUBMIT provisions some. fn try_add_compute_sibling( &self, required: super::freelist::ComputeCapacity, @@ -1993,8 +2246,7 @@ impl Backend { } admission.check()?; let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; - let (uat, objects, source, channel_index) = { + let (source, channel_index) = { let mut state = self.shared.state.lock(); admission.check()?; let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; @@ -2039,36 +2291,32 @@ impl Backend { firmware.queues.reserve_rearm(qid, self.owner)?; Err(qid) } - Some(SiblingSource::Fresh) => match firmware - .queues - .reserve_compute_channel(self.owner, self.compute_channels) - { - Ok(reservation) => Ok(reservation), - Err(_) => return Ok(false), - }, + Some(SiblingSource::Fresh) => { + if !firmware.queues.can_build_fresh(self.owner, required) { + firmware.queues.want_sibling(self.owner); + return Ok(false); + } + match firmware + .queues + .reserve_compute_channel(self.owner, self.compute_channels) + { + Ok(reservation) => { + Ok(self.install_fresh(firmware, reservation, required, channel_index)) + } + Err(_) => return Ok(false), + } + } }; - ( - firmware.uat.clone(), - firmware.pool.clone(), - source, - channel_index, - ) + (source, channel_index) }; - let alloc = super::object::Allocator { - dev: &dev, - uat: &uat, - client: None, - }; - let reservation = match source { - Ok(reservation) => reservation, + let (result, retired, unused) = match source { + Ok(built) => built, Err(qid) => { // The reservation ends with any outcome but binding the queue. let result = self.rearm_vacant( qid, channel_index, required, - &alloc, - &objects, &lease, admission, ); @@ -2084,64 +2332,9 @@ impl Backend { return Ok(bound); } }; - let built = (|| { - let pages = super::freelist::Pages::for_compute(&alloc, required, - self.context.vm().memory_client())?; - let ring = compute::DescriptorRing::new(&alloc, &objects)?; - let kit = compute::Kit::new(&alloc, &objects, self.shared.operand_state, true)?; - { - let mut state = self.shared.state.lock(); - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { - return Err(EAGAIN); - } - self.admission_open()?; - firmware.queues.reserved(reservation)?; - firmware.init.install_compute_pool( - compute::pool_descriptor(&pages, reservation.id.qid())?)?; - } - let queue = compute::Queue::new_channel( - kit, - pages, - ring, - reservation.id, - self.owner, - self.context.clone(), - self.shared.variant.pointers, - self.shared.operand_state, - self.shared.m5_board, - self.shared.variant.compute, - true, - self.shared.variant.mcache, - channel_index, - )?; - Ok(KBox::new(queue, GFP_KERNEL)?) - })(); - let (mut built, build_error) = match built { - Ok(queue) => (Some(queue), None), - Err(error) => (None, Some(error)), - }; - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() || self.admission_open().is_err() { - Err(EAGAIN) - } else if let Some(error) = build_error { - Err(error) - } else { - firmware.queues.install_compute(reservation, &mut built) - } - }; - drop(built); - if result.is_err() { - let mut state = self.shared.state.lock(); - if let Some(firmware) = (*state).as_deref_mut() { - let _ = firmware.queues.cancel_compute(reservation); - } - } + drop(unused); + // Best effort, as the sibling itself. + let _ = self.finish_uninstalled_compute(retired); drop(lease); Ok(result.is_ok()) } @@ -3059,8 +3252,14 @@ impl Backend { /// In the SUBMIT ioctl of a compute command: allocates what its publication will install /// and must not allocate, so that a refusal is this ioctl's error (ENOMEM, or ENOSPC for - /// address space): G17P's device-wide compute aperture and scheduler, until installed. - pub(super) fn provision_compute(&self, _required: super::freelist::ComputeCapacity) -> Result { + /// address space). The caller holds the command's [`super::context::ComputeClaim`]. + pub(super) fn provision_compute(&self, required: super::freelist::ComputeCapacity) -> Result { + self.provision_shared()?; + self.provision_backing(required) + } + + /// G17P's device-wide compute aperture and scheduler, until installed. + fn provision_shared(&self) -> Result { if self.context.is_m5() { return Ok(()); } @@ -3098,6 +3297,63 @@ impl Backend { Ok(()) } + /// This owner's compute backing for a publication at `required`, unless its spares or its + /// queues hold some ([`Registry::compute_lacks`]): pool pages and a descriptor ring charged + /// to its client, and for an owner without a queue of its own a kit of device memory. A + /// sibling channel that found none gets a set too, if it can be allocated. + fn provision_backing(&self, required: super::freelist::ComputeCapacity) -> Result { + let (uat, objects, lacks, reserved) = { + let state = self.shared.state.lock(); + let firmware = state.as_deref().ok_or(ENODEV)?; + let reserved = firmware.queues.reserves.iter().any(|reserve| reserve.owner == self.owner); + (firmware.uat.clone(), firmware.pool.clone(), + firmware.queues.compute_lacks(self.owner, required), reserved) + }; + if !lacks.any() && reserved { + return Ok(()); + } + let dev = self.shared.drm()?; + let client = self.context.vm().memory_client(); + let charged = super::object::Allocator { dev: &dev, uat: &uat, client }; + let device = super::object::Allocator { dev: &dev, uat: &uat, client: None }; + let reserve = (!reserved) + .then(|| KBox::new(OwnerReserve::new(self.owner, self.context.clone()), GFP_KERNEL)) + .transpose()?; + let mut pages = lacks.pages + .then(|| super::freelist::Pages::for_compute(&charged, required, client)).transpose()?; + let mut ring = lacks.ring + .then(|| compute::DescriptorRing::new(&charged, &objects)).transpose()?; + // A kit outlives the owner in the queue it builds: device memory. + let new_kit = || crate::memacct::device_memory(|| compute::Kit::new( + &device, &objects, self.shared.operand_state, self.context.is_m5())); + let mut kit = lacks.kit.then(&new_kit).transpose()?; + if lacks.sibling && !lacks.pages && !lacks.ring { + // Best effort, as the sibling: a refusal fails nothing. + pages = super::freelist::Pages::for_compute(&charged, required, client).ok(); + ring = compute::DescriptorRing::new(&charged, &objects).ok(); + kit = kit.or_else(|| new_kit().ok()); + } + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + // A queue that closed meanwhile keeps nothing. + let closed = self.closed.load(Ordering::Acquire); + let (unused, reserve) = if closed { + (compute::Vacated::spares(pages, ring, kit), reserve) + } else { + firmware.queues.stock(self.owner, reserve, pages, ring, kit) + }; + let stocked = closed || firmware.queues.reserves.iter().any(|reserve| reserve.owner == self.owner); + drop(state); + drop((unused, reserve)); + // Every logical queue has room for a reserve; without one, the command must not be queued. + if !stocked { + return Err(ENOSPC); + } + // A publication of this owner may be waiting for its backing. + self.shared.channels.notify(); + Ok(()) + } + fn ensure_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; let mut deferred = DeferredBatch::publication()?; @@ -4275,7 +4531,8 @@ impl super::Firmware { queue.recycle_killed()?; queue.recycle_quarantined_idle()?; if deferred.vacated_room() { - if let Some(vacated) = queue.take_recycled_ring() { + if let Some(mut vacated) = queue.take_recycled_ring() { + keep_backing(&mut self.queues.reserves, &mut vacated); deferred.defer_vacated(vacated); freed = true; } @@ -4287,6 +4544,7 @@ impl super::Firmware { releasing |= queue.pool_release_pending(); } freed |= self.queues.observe_pool_releases(&self.init, deferred)? != 0; + self.queues.trim_reserves(deferred); let shared = &self.primary.state.shared; // Edge notifications cover the transitions this driver makes; every // event pass also rechecks the level, so capacity that appeared through diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index c72c5c448c19c..7e9429eba5216 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -116,7 +116,10 @@ impl Backend { firmware.queues.sync_render_holds(); firmware.queues.admission.release_owner(self.owner); } + // Its spare compute backing is freed; what its queues hold is no longer kept for it. + let reserve = firmware.queues.close_reserve(self.owner); drop(state); + drop(reserve); // Its idle channel, or its slot and never-published QID, is free. self.shared.channels.notify(); self.shared.queue_events(); diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index 2f13f870d44b6..cbcbb9081e398 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -32,12 +32,14 @@ //! out-of-device-memory, instead of pushing the machine into a global OOM. //! //! Imported dma-bufs are charged to their exporter and are not counted here. -//! Kernel objects a client's queue creation builds (on G17, its context) are charged to -//! that client as its held memory, whatever the limits, and their pages to its memory -//! cgroup ([`Client::charging`]). Kernel objects built later, when a submission is -//! published, and global kernel objects (firmware heaps and boot structures) count -//! towards the device total and its limit, but are attributed to no process: a failure -//! after a submission was accepted would lose the device. +//! Kernel objects a client's ioctls build for its queues (on G17, its context at queue +//! creation, and its compute pool pages and descriptor rings at a compute SUBMIT) are +//! charged to that client as its held memory, whatever the limits, and their pages to its +//! memory cgroup ([`Client::charging`]). Kernel objects built later, when a submission is +//! published, and device memory (firmware heaps and boot structures, and objects that +//! outlive the client that caused them, [`device_memory`]) count towards the device total +//! and its limit, but are attributed to no process: a failure after a submission was +//! accepted would lose the device. use core::sync::atomic::{ AtomicBool, diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index a0fbb2383ce9f..7ddefc5c6f012 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -554,6 +554,7 @@ def release_fixture(): } impl Registry { pub fn release_compute(&mut self, _: u64) -> Result { Ok(()) } + pub fn close_reserve(&mut self, _: u64) -> Option<()> { None } pub fn note_build_room(&self) {} """ + item(render_teardown, 'pub(in crate::g17::runtime) fn release_render(') + '\n' + runtime + r""" } diff --git a/tools/asahi/g17-compute-constructor-tests.py b/tools/asahi/g17-compute-constructor-tests.py index 51407cbbdd9a8..c75b1ee4bd919 100644 --- a/tools/asahi/g17-compute-constructor-tests.py +++ b/tools/asahi/g17-compute-constructor-tests.py @@ -2,7 +2,7 @@ # SPDX-License-Identifier: GPL-2.0-only OR MIT """G17P's device-wide compute objects are allocated in SUBMIT and installed at publication. -Runs the production `Backend::provision_compute` (SUBMIT) and `Backend::shared_compute` +Runs the production `Backend::provision_shared` (SUBMIT) and `Backend::shared_compute` (publication) against mocked firmware state, allocations and leases: - SUBMIT allocates the shared aperture and the scheduler while neither is installed nor @@ -31,7 +31,7 @@ def item(text, signature): def fixture(): runtime = (ROOT / 'runtime.rs').read_text() - methods = '\n'.join(item(runtime, sig) for sig in [' pub(super) fn provision_compute(', ' fn shared_compute(']) + methods = '\n'.join(item(runtime, sig) for sig in [' fn provision_shared(', ' fn shared_compute(']) methods = (methods.replace('super::object::Allocator', 'Allocator').replace('super::initdata::', '') .replace('super::freelist::ComputeCapacity', 'ComputeCapacity').replace('super::Firmware', 'Firmware') .replace('crate::memacct::device_memory', 'device_memory').replace('pub(super) ', '')) @@ -86,10 +86,10 @@ def fixture(): fn main(){ // SUBMIT: allocates what is neither installed nor prepared, once. let b=backend(false,false,false); - assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(b.provision_shared(),Ok(())); assert_eq!(ALLOCATED.load(Ordering::SeqCst),2); assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_some()&&fw(&b).as_ref().unwrap().queues.prepared_scheduler.is_some()); - assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(b.provision_shared(),Ok(())); assert_eq!(ALLOCATED.load(Ordering::SeqCst),2,"prepared objects must not be allocated again"); // Publication installs the prepared aperture and allocates nothing. assert_eq!(b.shared_compute(&ADMISSION),Ok(())); @@ -99,19 +99,19 @@ def fixture(): assert_eq!(ALLOCATED.load(Ordering::SeqCst),2,"publication must not allocate"); // Installed objects are not prepared again. let b=backend(false,true,true); - assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(b.provision_shared(),Ok(())); assert_eq!(ALLOCATED.load(Ordering::SeqCst),2); // A refused allocation is the SUBMIT's error and prepares nothing. let b=backend(false,false,false); REFUSE.store(true,Ordering::SeqCst); - assert_eq!(b.provision_compute(ComputeCapacity),Err(ENOMEM),"a refused allocation must fail the SUBMIT"); + assert_eq!(b.provision_shared(),Err(ENOMEM),"a refused allocation must fail the SUBMIT"); REFUSE.store(false,Ordering::SeqCst); assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_none()); // Publication without a prepared aperture fails and installs nothing; it never builds one. assert_eq!(b.shared_compute(&ADMISSION),Err(EIO),"publication must not allocate an aperture SUBMIT did not prepare"); assert!(!fw(&b).as_ref().unwrap().init.shared); // A cancelled admission, a stale lease or a crash installs nothing. - assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(b.provision_shared(),Ok(())); CANCEL.store(true,Ordering::SeqCst); assert_eq!(b.shared_compute(&ADMISSION),Err(ECANCELED)); CANCEL.store(false,Ordering::SeqCst); @@ -127,7 +127,7 @@ def fixture(): // M5 has neither: nothing is allocated or installed. let before=ALLOCATED.load(Ordering::SeqCst); let b=backend(true,false,false); - assert_eq!(b.provision_compute(ComputeCapacity),Ok(())); + assert_eq!(b.provision_shared(),Ok(())); assert_eq!(b.shared_compute(&ADMISSION),Ok(())); assert_eq!(ALLOCATED.load(Ordering::SeqCst),before); assert!(!fw(&b).as_ref().unwrap().init.shared); diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index 0877ed9afdcd7..727c839efc997 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -49,7 +49,7 @@ def fixture(): const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const EBUSY:i32=-16;const ECANCELED:i32=-125; const RECOVERY_WAIT_MS:u32=26_000; static NOW:AtomicU64=AtomicU64::new(0);static ALIAS:AtomicBool=AtomicBool::new(false);static PAGES:AtomicBool=AtomicBool::new(false); -static RESERVED:AtomicBool=AtomicBool::new(false);static ABORTED:AtomicBool=AtomicBool::new(false); +static RESERVED:AtomicBool=AtomicBool::new(false);static ABORTED:AtomicBool=AtomicBool::new(false);static RETURNED:AtomicBool=AtomicBool::new(false); fn now_ns()->u64{NOW.load(Ordering::SeqCst)} mod kernel{pub mod time{ pub struct Delta(pub u64);impl Delta{pub fn from_millis(ms:u64)->Self{Self(ms)}} @@ -78,7 +78,9 @@ def fixture(): } impl Drop for Pages{fn drop(&mut self){PAGES.store(false,Ordering::SeqCst);}} impl Drop for Alias{fn drop(&mut self){ALIAS.store(false,Ordering::SeqCst);}} -mod compute{pub(crate) use crate::Queue;} +mod compute{pub(crate) use crate::{Queue,Vacated};} +// What a queue or a builder gives back to its owner. +struct Vacated;impl Vacated{fn drop_aliases(&mut self){}} const COMPUTE_CHANNELS_MAX:usize=3; ''' + aliases + r''' struct Queue{fresh:bool} @@ -87,7 +89,8 @@ def fixture(): fn pool_fits(&self,_:usize)->bool{false} fn begin_growth(&mut self,_:&(),_:usize)->Result{Ok(false)} fn growth_token(&self)->Option{Some(7)} - fn finish_growth(&mut self,_:&(),_:&mut Option,_:&mut Option)->Result{Err(EAGAIN)} + fn finish_growth(&mut self,_:&(),_:&mut Option,_:&mut Option)->Result{Err(EAGAIN)} + fn take_backing(&mut self)->Vacated{Vacated} fn abort_growth(&mut self,t:u64)->Result>{assert_eq!(t,7);ABORTED.store(true,Ordering::SeqCst);Ok(Some(self.fresh))} } impl Drop for Queue{fn drop(&mut self){if self.fresh{assert!(RESERVED.load(Ordering::SeqCst));assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst),"growth aliases must precede fresh QID return");}}} @@ -100,6 +103,12 @@ def fixture(): fn compute_primary(&mut self,owner:u64)->Option<&mut Queue>{self.compute_mut(owner)} fn drain_compute_siblings(&mut self,_:u64,_:&mut PerChannel)->Result{Ok(())} fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} + // The owner's spare pages: a SUBMIT provisioned them. + fn take_pages(&mut self,_:u64,_:ComputeCapacity)->Option{PAGES.store(true,Ordering::SeqCst);Some(Pages)} + fn recall_backing(&mut self,_:u64,_:ComputeCapacity)->bool{false} + fn keep_returned(&mut self,_:&mut Vacated){} + fn put_back(&mut self,_:u64,pages:Option,_:Option<()>,_:Option<()>)->Vacated{ + if let Some(pages)=pages{std::mem::forget(pages);PAGES.store(false,Ordering::SeqCst);RETURNED.store(true,Ordering::SeqCst);}Vacated} } struct Primary;impl Primary{fn notify(&self,_:u32)->Result{Ok(())}} struct Firmware{queues:Registry,uat:(),init:(),primary:Primary} @@ -115,7 +124,7 @@ def fixture(): } fn main(){ for fresh in [false,true]{for cancel in [false,true]{ - NOW.store(0,Ordering::SeqCst);ABORTED.store(false,Ordering::SeqCst);RESERVED.store(true,Ordering::SeqCst); + NOW.store(0,Ordering::SeqCst);ABORTED.store(false,Ordering::SeqCst);RESERVED.store(true,Ordering::SeqCst);RETURNED.store(false,Ordering::SeqCst); let b=Backend{owner:1,context:Context,shared:Shared{preparations:Gate,progress:Available,channels:Available,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(),init:(),primary:Primary,queues:Registry{compute:vec![Some(Entry{reservation:ComputeReservation,queue:Some(Box::new(Queue{fresh}))})]}}))))}}; let check=||{if cancel&&now_ns()>=10_000_000{Err(ECANCELED)}else{Ok(())}}; let admission=Admission::new(20_000_000,&check); @@ -123,8 +132,9 @@ def fixture(): assert_eq!(now_ns(),if cancel{10_000_000}else{20_000_000}); assert!(ABORTED.load(Ordering::SeqCst));assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst)); assert_eq!(RESERVED.load(Ordering::SeqCst),!fresh,"only unpublished QIDs may return without firmware release"); + assert!(RETURNED.load(Ordering::SeqCst),"unused growth pages must go back to their owner"); }} - println!("PASS 4 complete production growth waits: deadline, cancellation, installed retention, fresh rollback and tentative-alias/QID order"); + println!("PASS 4 complete production growth waits: deadline, cancellation, installed retention, fresh rollback, tentative-alias/QID order and unused pages back to their owner"); } ''' @@ -133,7 +143,8 @@ def main(): source = fixture() mutants = [('fixed', source, ''), ('ignore-shared-deadline', source.replace('if now_ns() >= self.deadline.get()', 'if false').replace('if remaining == 0 { return Err(EBUSY); }', ''), 'growth admission exceeded'), - ('keep-growth-alias', source.replace(' drop(alias.take());', ''), 'growth aliases must precede')] + ('keep-growth-alias', source.replace(' drop(alias.take());', ''), 'growth aliases must precede'), + ('drop-unused-pages', source.replace('firmware.queues.put_back(self.owner, Some(unused), None, None)', 'drop(unused)'), 'must go back to their owner')] with tempfile.TemporaryDirectory(prefix='g17-compute-growth-') as tmp: for name, code, expected in mutants: if name != 'fixed': diff --git a/tools/asahi/g17-compute-reserve-tests.py b/tools/asahi/g17-compute-reserve-tests.py index 8309132eb3e08..1653138b9f885 100644 --- a/tools/asahi/g17-compute-reserve-tests.py +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""A compute queue's objects are allocated apart from the QID they are bound to. +"""Compute publication allocates nothing: SUBMIT provisions, publication takes. A fresh G17 compute queue is built for a QID that publication reserves from firmware state. Its objects (the pool's control and state, the kick ring, the @@ -11,9 +11,28 @@ `Queue::new_channel` allocate no device memory; - `Kit::new` allocates the kit through an Allocator. ---mutation allocating-bind / allocating-graph inject an allocation into a bind -step and must be caught. +A compute SUBMIT allocates them (`Backend::provision_compute`): the pool pages +and ring charged to the client, the kit as device memory. Its claim is taken +before, and the command is queued only after. Publication only takes from the +owner's spares, and what a queue gives back returns to its owner: + +- the publication paths (`shared_compute`, `build_compute`, `install_fresh`, + `rearm_vacant`, `grow_compute`, `try_add_compute_sibling`, + `finish_uninstalled_compute`) allocate no device memory; +- every place a queue gives backing back keeps it for its owner; close and the + pool pass free spares; another open owner's backing is never bound; +- compiled: the production `keep_backing`, `stock` and `trim_reserves` with the + production spare bookkeeping keep a claimed owner's backing, free an idle or + unknown owner's, and free every spare exactly once. + +--mutation allocating-bind / allocating-graph / publication-allocates / +claim-after-provision / free-returned / bind-other-owner / kit-needs-qid / +keep-idle inject a +fault and must be caught. """ +import os +import subprocess +import tempfile import argparse import re import sys @@ -42,7 +61,8 @@ def code(text): def sources(mutation): files = {name: (G17 / name).read_text() for name in - ['freelist.rs', 'kick.rs', 'queue/compute.rs', 'runtime.rs', 'runtime/backend.rs']} + ['freelist.rs', 'kick.rs', 'queue/compute.rs', 'runtime.rs', 'runtime/backend.rs', + 'queue/mod.rs', 'queue/compute/reserve.rs']} if mutation == 'allocating-bind': files['freelist.rs'] = files['freelist.rs'].replace( ' let PoolObjects { mut control, state } = objects;', @@ -52,6 +72,31 @@ def sources(mutation): files['queue/compute.rs'] = files['queue/compute.rs'].replace( ' let graph_va = graph.gpu_va();', ' let ring = DescriptorRing::new(alloc, objects)?;\n let graph_va = graph.gpu_va();', 1) + elif mutation == 'publication-allocates': + files['runtime.rs'] = files['runtime.rs'].replace( + ' let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else {', + ' let pages = super::freelist::Pages::for_compute(&alloc, required, None)?;\n' + ' let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else {', 1) + elif mutation == 'claim-after-provision': + files['queue/mod.rs'] = files['queue/mod.rs'].replace( + ' .then(|| super::context::ComputeClaim::new(&self.context));\n' + ' if engine == Engine::Compute {\n self.ensure_compute(&command)?;\n }', + ' .then(|| ());\n if engine == Engine::Compute {\n self.ensure_compute(&command)?;\n' + ' }\n let claim = claim.map(|()| super::context::ComputeClaim::new(&self.context));', 1) + elif mutation == 'free-returned': + files['runtime.rs'] = files['runtime.rs'].replace( + ' keep_backing(&mut self.reserves, &mut vacated);\n', '', 1) + elif mutation == 'bind-other-owner': + files['runtime.rs'] = files['runtime.rs'].replace( + ' if !queue.pool_fits(required) || !queue.pool_serves(context.vm())\n' + ' || !queue.backing_free_for(owner)\n', + ' if !queue.pool_fits(required) || !queue.pool_serves(context.vm())\n', 1) + elif mutation == 'kit-needs-qid': + files['runtime.rs'] = files['runtime.rs'].replace( + '|| queue.owner() == Some(owner));', '|| queue.owner() == Some(owner))\n && self.compute_qid_fits();', 1) + elif mutation == 'keep-idle': + files['runtime.rs'] = files['runtime.rs'].replace( + ' if !reserve.context.compute_claimed() {\n return;\n }\n', '', 1) return files @@ -64,8 +109,198 @@ def sources(mutation): ] -def check(files): +# Publication paths, which take from the owner's spares and allocate no device memory. +PUBLICATION = [' fn shared_compute(', ' fn install_fresh(', ' fn grow_compute(', ' fn rearm_vacant(', + ' fn build_compute(', ' fn try_add_compute_sibling(', ' fn finish_uninstalled_compute('] + + +def ordered(text, *parts): + position = 0 + for part in parts: + position = text.find(part, position) + if position < 0: + return False + position += len(part) + return True + + +def structure(files): failures = [] + runtime = files['runtime.rs'] + for signature in PUBLICATION: + body = item(runtime, signature) + for m in ALLOCATING.finditer(code(body)): + failures.append(f'FAIL line {runtime.count(chr(10), 0, runtime.index(signature)) + 1}: runtime.rs: ' + f'publication {signature.strip()} allocates ({m.group(0)})') + backend = files['runtime/backend.rs'] + provision = item(runtime, ' fn provision_backing(') + checks = { + 'SUBMIT provisions before validation returns': 'self.provision_compute(required)' in item(backend, ' fn ensure_compute('), + 'SUBMIT charges pages and ring to the client, the kit is device memory': ordered( + provision, 'let charged = super::object::Allocator { dev: &dev, uat: &uat, client };', + 'let device = super::object::Allocator { dev: &dev, uat: &uat, client: None };', + 'super::freelist::Pages::for_compute(&charged, required, client)', + 'compute::DescriptorRing::new(&charged, &objects)', + 'crate::memacct::device_memory(|| compute::Kit::new(', 'firmware.queues.stock('), + 'the claim precedes the SUBMIT provision, and the command is queued after it': ordered( + item(files['queue/mod.rs'], ' fn enqueue('), 'super::context::ComputeClaim::new(&self.context)', + 'self.ensure_compute(&command)?;', 'Packet::new(', 'claim,', '.enqueue(packet'), + 'given-back pools go to their owner': 'keep_backing(&mut self.reserves, &mut vacated);' in item(runtime, 'pub(super) fn observe_pool_releases('), + 'recycled rings go to their owner': 'keep_backing(&mut self.queues.reserves, &mut vacated);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), + 'the pool pass frees idle owners\' spares': 'self.queues.trim_reserves(deferred);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), + 'growth keeps the smaller pages': 'firmware.queues.keep_returned(&mut old);' in item(runtime, ' fn grow_compute('), + 'a never-published queue gives its backing back': ordered(item(runtime, ' fn finish_uninstalled_compute('), + 'queue.take_backing()', 'drop(queue);', 'backing.drop_aliases();', 'cancel_compute(reservation)?;', + 'firmware.queues.keep_returned(&mut backing);', 'drop(state);', 'drop(backing);'), + 'close frees the spares off the device mutex': ordered(item(backend, ' fn release_queue('), + 'firmware.queues.close_reserve(self.owner);', 'drop(state);', 'drop(reserve);'), + 'another open owner\'s backing is not bound': all( + '!queue.backing_free_for(owner)' in item(runtime, sig) for sig in + [' fn bind_reusable(', ' pub(super) fn rebind_compute(']) and + 'queue.pool_serves(vm) && queue.backing_free_for(owner)' in item(runtime, ' fn sibling_source('), + # Else a QID freed after SUBMIT would find the owner with no kit and no queue to share. + 'a queue-less owner always gets a kit': 'compute_qid_fits' not in item(runtime, ' pub(super) fn compute_lacks('), + 'a queue refuses another open owner\'s backing': '!self.backing_free_for(owner)' in item(files['queue/compute.rs'], ' fn bind_owner_channel('), + } + failures += [f'FAIL line 0: {name}' for name, ok in checks.items() if not ok] + return failures + + +def compiled(files): + """Runs the production give-back, stock and trim with the production spare bookkeeping.""" + runtime = files['runtime.rs'] + reserve = files['queue/compute/reserve.rs'] + spares = reserve[reserve.index('const PAGES'):reserve.index('#[kunit_tests')] + owner = item(runtime, 'pub(super) struct OwnerReserve {') + '\n' + item(runtime, 'impl OwnerReserve {') + methods = '\n'.join(item(runtime, sig) for sig in [' fn owner_reserve(', ' pub(super) fn stock(', + ' fn trim_reserves(']) + keep = item(runtime, 'fn keep_backing(') + replace = lambda text: (text.replace('pub(super) ', '').replace('super::freelist::Pages', 'Pages') + .replace('compute::reserve::Spares', 'Spares').replace('compute::DescriptorRing', 'Ring') + .replace('compute::Kit', 'Kit').replace('compute::Vacated', 'Vacated') + .replace('crate::g17::pairs::COMPUTE_CHANNELS_MAX', '3') + .replace('self.reserves.push_within_capacity(new)', 'push_within(&mut self.reserves, new)')) + source = r''' +#![allow(dead_code)] +use std::sync::{Arc, atomic::{AtomicUsize, AtomicU32, Ordering}}; +type KVec = Vec; +type KBox = Box; +type Result = std::result::Result; +#[derive(Clone, Copy)] enum ComputeCapacity { Blocks(usize) } +static MADE: AtomicUsize = AtomicUsize::new(0); +static FREED: AtomicUsize = AtomicUsize::new(0); +struct Pages(usize, bool); +impl Pages { + fn new(blocks: usize) -> Self { MADE.fetch_add(1, Ordering::SeqCst); Self(blocks, false) } + fn reset(&mut self) -> Result { self.1 = true; Ok(()) } +} +impl Drop for Pages { fn drop(&mut self) { FREED.fetch_add(1, Ordering::SeqCst); } } +struct Ring(bool); +impl Ring { + fn new() -> Self { MADE.fetch_add(1, Ordering::SeqCst); Self(false) } + fn clear(&mut self) { self.0 = true; } +} +impl Drop for Ring { fn drop(&mut self) { FREED.fetch_add(1, Ordering::SeqCst); } } +struct Kit; +impl Kit { fn new() -> Self { MADE.fetch_add(1, Ordering::SeqCst); Self } } +struct PushError(T); +fn push_within(v: &mut Vec, x: T) -> std::result::Result<(), PushError> { + if v.len() < v.capacity() { v.push(x); Ok(()) } else { Err(PushError(x)) } +} +impl Drop for Kit { fn drop(&mut self) { FREED.fetch_add(1, Ordering::SeqCst); } } +''' + replace(spares.replace('pub(crate) ', '')) + r''' +impl Capacity for Pages { + fn fits(&self, required: ComputeCapacity) -> bool { let ComputeCapacity::Blocks(b) = required; self.0 >= b } + fn covers(&self, other: &Self) -> bool { self.0 >= other.0 } +} +struct Context(AtomicU32); +impl Context { fn compute_claimed(&self) -> bool { self.0.load(Ordering::SeqCst) != 0 } } +/// What a queue gives back. +struct Vacated { pages: Option, ring: Option, kit: Option, owner: Option } +impl Vacated { + fn spares(pages: Option, ring: Option, kit: Option) -> Self { Self { pages, ring, kit, owner: None } } + fn returns_to(&self) -> Option { self.owner } + fn backing(&mut self) -> (&mut Option, &mut Option) { (&mut self.pages, &mut self.ring) } +} +struct DeferredBatch { vacated: Vec, room: usize } +impl DeferredBatch { + fn vacated_room(&self) -> bool { self.vacated.len() < self.room } + fn defer_vacated(&mut self, vacated: Vacated) { self.vacated.push(vacated) } +} +struct Registry { reserves: KVec> } +''' + replace(owner) + '\n' + replace(keep) + '\nimpl Registry {\n' + replace(methods) + r''' +} +fn back(owner: u64, blocks: usize) -> Vacated { + Vacated { pages: Some(Pages::new(blocks)), ring: Some(Ring::new()), kit: None, owner: Some(owner) } +} +fn main() { + let a = Arc::new(Context(AtomicU32::new(1))); + let b = Arc::new(Context(AtomicU32::new(1))); + let mut registry = Registry { reserves: Vec::with_capacity(2) }; + // SUBMIT stocks a new owner: its reserve and its first set. + let (unused, rest) = registry.stock(1, Some(Box::new(OwnerReserve::new(1, a.clone()))), + Some(Pages::new(21)), Some(Ring::new()), Some(Kit::new())); + assert!(rest.is_none() && unused.pages.is_none() && unused.ring.is_none() && unused.kit.is_none()); + drop(unused); + let (unused, _) = registry.stock(2, Some(Box::new(OwnerReserve::new(2, b.clone()))), Some(Pages::new(21)), None, None); + drop(unused); + assert_eq!(FREED.load(Ordering::SeqCst), 0, "stocking frees nothing"); + // A queue gives owner 1's backing back while it has commands: kept, reset, cleared. + let mut returned = back(1, 30); + keep_backing(&mut registry.reserves, &mut returned); + assert!(returned.pages.is_none() && returned.ring.is_none(), "a claimed owner's backing must be kept"); + drop(returned); + assert_eq!(FREED.load(Ordering::SeqCst), 0); + { + let spares = &mut registry.owner_reserve(1).unwrap().spares; + let pages = spares.take_pages(ComputeCapacity::Blocks(30)).unwrap(); + assert!(pages.1, "kept pages are reset"); + let (first, second) = (spares.take_ring().unwrap(), spares.take_ring().unwrap()); + assert!(first.0 != second.0, "the kept ring is cleared, the stocked one is fresh"); + spares.put_pages(pages); spares.put_ring(first); spares.put_ring(second); + } + // Owner 2 has no commands: what comes back is freed, as is an unknown owner's. + b.0.store(0, Ordering::SeqCst); + let mut idle = back(2, 30); + keep_backing(&mut registry.reserves, &mut idle); + assert!(idle.pages.is_some() && idle.ring.is_some(), "an idle owner's backing must be freed"); + drop(idle); + let mut unknown = back(9, 21); + keep_backing(&mut registry.reserves, &mut unknown); + assert!(unknown.pages.is_some()); + drop(unknown); + // The pool pass frees an idle owner's spares and keeps a claimed owner's. + let mut deferred = DeferredBatch { vacated: Vec::new(), room: 8 }; + registry.trim_reserves(&mut deferred); + assert!(registry.owner_reserve(2).unwrap().spares.is_empty(), "the pool pass must free idle spares"); + assert!(!registry.owner_reserve(1).unwrap().spares.is_empty(), "a claimed owner keeps its spares"); + drop(deferred); + // Close: owner 1 exits with its reserve unused; everything was freed exactly once. + let index = registry.reserves.iter().position(|reserve| reserve.owner == 1).unwrap(); + drop(registry.reserves.swap_remove(index)); + drop(registry); + assert_eq!(MADE.load(Ordering::SeqCst), FREED.load(Ordering::SeqCst), "every spare is freed exactly once"); + println!("PASS compute reserve: SUBMIT stocks, a claimed owner keeps what its queues give back (reset), an idle or unknown owner's backing and idle spares are freed, and close frees the rest, each once"); +} +''' + with tempfile.TemporaryDirectory(prefix='g17-compute-reserve-') as tmp: + path = Path(tmp) / 'reserve.rs' + path.write_text(source) + # The fixture slices in KUnit-only helpers (`is_empty`), so build it as KUnit does. + build = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-Awarnings', + '--cfg', 'CONFIG_KUNIT="y"', str(path), + '-o', str(path.with_suffix(''))], capture_output=True, text=True) + if build.returncode != 0: + return [f'FAIL line 0: compiled reserve fixture does not build:\n{build.stderr}'] + run = subprocess.run([str(path.with_suffix(''))], capture_output=True, text=True, timeout=30) + if run.returncode != 0: + return [f'FAIL line 0: compiled reserve: {run.stderr.strip()}'] + print(run.stdout.strip()) + return [] + + +def check(files): + failures = structure(files) + compiled(files) for name, signature, why in BINDS: text = files[name] if signature not in text: @@ -85,14 +320,16 @@ def check(files): def main(): parser = argparse.ArgumentParser() - parser.add_argument('--mutation', choices=['allocating-bind', 'allocating-graph']) + parser.add_argument('--mutation', choices=['allocating-bind', 'allocating-graph', 'publication-allocates', + 'claim-after-provision', 'free-returned', 'bind-other-owner', + 'kit-needs-qid', 'keep-idle']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: print(f) if failures: sys.exit(1) - print('ok: compute queue objects are allocated apart from their QID, and binding only stores') + print('ok: compute objects are allocated in SUBMIT apart from their QID; publication only takes and binds') if __name__ == '__main__': diff --git a/tools/asahi/g17-compute-retired-tests.py b/tools/asahi/g17-compute-retired-tests.py index 900fdee4c47b4..b71f817ae6f1d 100755 --- a/tools/asahi/g17-compute-retired-tests.py +++ b/tools/asahi/g17-compute-retired-tests.py @@ -167,7 +167,19 @@ def build_harness(mutation=None): log(format!("binding {}", self.0)); } } -mod compute { pub(super) use super::{Binding, Queue}; } +mod compute { pub(super) use super::{Binding, Queue, Vacated}; } +/// The backing a never-published queue gives back to its owner. +struct Vacated(u8); +impl Vacated { + fn drop_aliases(&mut self) { + assert!(!locked(), "aliases of qid {} dropped under the device mutex", self.0); + } +} +impl Drop for Vacated { + fn drop(&mut self) { + assert!(!locked(), "backing of qid {} freed under the device mutex", self.0); + } +} #[derive(Clone, Copy, PartialEq)] enum Rollback { Cancel, Displace, Keep, Fail } @@ -182,6 +194,7 @@ def build_harness(mutation=None): } impl Queue { fn owner(&self) -> Option { self.owner } + fn take_backing(&mut self) -> Vacated { Vacated(self.qid) } fn is_primary(&self) -> bool { self.primary } fn active_len(&self) -> u32 { self.active } fn has_replays(&self) -> bool { false } @@ -270,6 +283,9 @@ def build_harness(mutation=None): if error == ENOSPC { EAGAIN } else { error } } fn note_build_room(&mut self) {} + fn keep_returned(&mut self, vacated: &mut Vacated) { + assert!(locked(), "backing of qid {} kept off the device mutex", vacated.0); + } ''' + '\n'.join([drain, rollback, reserve, reserved, cancel]) + r''' } diff --git a/tools/asahi/g17-growth-tests.py b/tools/asahi/g17-growth-tests.py index f763fd5b5ff80..df73171e0d15e 100644 --- a/tools/asahi/g17-growth-tests.py +++ b/tools/asahi/g17-growth-tests.py @@ -39,13 +39,13 @@ def fixture(): pool_phase:PoolPhase,release_sent_ns:Option,pool:Pool,binding:Option,previous:Option,graph:Graph, active:Fifo,replays:Fifo,quarantined:bool,released:bool,retirement_ready:bool, retired_by_teardown:bool,released_at:u64,exit:Option<()>,needs_fresh_backing:bool, - source_hint:ReaderHint,source_readers:AtomicU32, + source_hint:ReaderHint,source_readers:AtomicU32,backing_owner:Option, } fn idle(live:&Arc)->Queue{Queue{owner:Some(1),channel_index:0,binding_noted:false,installed:true,growing:false,channel_error:false,growth:None, free_list_generation:0,configuration:None,retained_owner:None,pool_phase:PoolPhase::Populated,release_sent_ns:None,pool:Pool{pages:Some(Pages(10,21)),fail:false}, binding:Some(Binding{context:Context::new(live),pool_alias:Some(1),descriptors:Some(2)}),previous:None,graph:Graph, active:Fifo{len:0},replays:Fifo{len:0},quarantined:false,released:false,retirement_ready:true, - retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0)}} + retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0),backing_owner:Some(1)}} impl Queue { fn clear_binding_note(&mut self){if self.binding_noted{if let Some(binding)=&self.binding{binding.context.note_compute_binding(false);}self.binding_noted=false;}} fn clear_owner(&mut self,stamp:bool){self.clear_binding_note();self.owner=None;self.channel_index=0;if stamp{self.released_at=now_ns();}} @@ -92,7 +92,9 @@ def fixture(): enum ControlRecord {FreeListRelease(u64)} struct Rings; impl Rings {fn publish_control(_:&initdata::InitData,_:&ControlRecord)->Result{Ok(3)}} -struct Vacated {_alias:Option,_pages:Option,_descriptors:Option,_ring:Option} +struct Vacated {_alias:Option,pages:Option,_descriptors:Option,ring:Option,_kit:Option<()>,owner:Option} +// The owners' spare backing: what a queue gives back stays its owner's while it has commands. +fn keep_backing(_:&mut (),_:&mut Vacated){} impl Graph {fn vacate_ring(&mut self)->Option{Some(1)}} ''' + '#[derive(Clone, Copy)]\n' + item(source, 'pub(crate) struct Growth') + r''' impl Queue { @@ -100,7 +102,7 @@ def fixture(): ''' + methods + r''' } struct Entry {queue:Option>} -struct Registry {compute:Vec>} +struct Registry {compute:Vec>,reserves:()} struct DeferredBatch {vacated:Vec,capacity:usize} impl DeferredBatch { fn vacated_room(&self)->bool{self.vacated.len() bool {{ self.needs_fresh_backing }} fn pool_vacant(&self) -> bool {{ self.pool_vacant }} fn pool_serves(&self, vm: u32) -> bool {{ self.pool_vm == vm }} + // The backing of a closed owner, or of the asking one. + fn backing_free_for(&self, _: u64) -> bool {{ true }} fn pool_fits(&self, req: ComputeCapacity) -> bool {{ self.pool_cap >= req.0 }} fn has_ring(&self) -> bool {{ self.has_ring }} fn context(&self) -> Option<&Arc> {{ self.context.as_ref() }} diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py index 3068c820beb54..020ba0ba7a693 100755 --- a/tools/asahi/g17-m5-sibling-gate-tests.py +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -322,6 +322,8 @@ def build(mutation=None): fn released_at(&self) -> u64 { 0 } fn vacancy_pending(&self) -> bool { false } fn pool_serves(&self, vm: u32) -> bool { self.pool_vm == vm } + // The backing of a closed owner, or of the asking one. + fn backing_free_for(&self, _: u64) -> bool { true } fn pool_fits(&self, required: ComputeCapacity) -> bool { self.pool_cap >= required.0 } fn has_ring(&self) -> bool { true } fn context(&self) -> Option<&Arc> { None } diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index 079c206368a34..14fe29722d25d 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -179,7 +179,7 @@ def build(mutation=None): 'pub(crate) fn observe_vacancy(', 'pub(crate) fn shareable(', 'pub(crate) fn owner(&self)', 'pub(crate) fn channel_index(&self)', 'pub(crate) fn is_primary(&self)', 'pub(crate) fn active_len(&self)', 'pub(crate) fn has_replays(&self)', 'pub(crate) fn configuring(&self)', 'pub(crate) fn context(&self)', - 'pub(crate) fn bind_sibling(', 'pub(crate) fn bind_owner(&mut self', + 'pub(crate) fn bind_sibling(', 'pub(crate) fn bind_owner(&mut self', 'pub(crate) fn backing_free_for(', ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') \ .replace('crate::g17::freelist::Pages', 'Pages').replace('crate::g17::initdata::InitData', 'InitData') \ .replace('crate::g17::now_ns()', 'now_ns()').replace('crate::g17::freelist::control_consumed', 'control_consumed') @@ -218,18 +218,19 @@ def build(mutation=None): 'Some(SiblingSource::Fresh) =>', 'reserve_compute_channel(self.owner, self.compute_channels)', 'Err(qid) => {', 'self.rearm_vacant(\n qid,\n channel_index,\n required,', 'if !bound {', 'firmware.queues.release_rearm(qid, self.owner);', 'admission.check()?;', - 'return Ok(bound);', 'compute::Kit::new('), + 'return Ok(bound);', 'let _ = self.finish_uninstalled_compute(retired);'), 'a re-arm binds the channel it was reserved for, through the primary path': ordered_ok( - rearm_vacant, 'crate::g17::freelist::Pages::for_compute(', 'compute::DescriptorRing::new(', + rearm_vacant, 'let mut state = self.shared.state.lock();', 'if !lease.is_current()', 'self.admission_open()', 'queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)', '&& (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' ' == Some(channel_index));', - 'firmware.queues.rearm_compute(qid, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', + 'firmware.queues.take_set(self.owner, required)', + 'firmware.queues.rearm_compute(qid, self.owner, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', 'firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?;'), 'the primary re-arms channel 0': 'self.rearm_vacant(qid, 0, required,' in build_compute, 'the primary gives back other VMs\' queues through the same helper': ordered_ok( - rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant() && !queue.pool_serves(vm))', + rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant()\n && (!queue.pool_serves(vm) || !queue.backing_free_for(owner)))', 'if let Some(qid) = foreign {', 'self.give_back_foreign(qid)?;', 'return Err(ENOSPC);'), } checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) @@ -284,7 +285,7 @@ def build(mutation=None): pub struct PoolDescriptor(u32); pub struct InitData { control_cursor: std::cell::Cell } pub struct KernelMapping; -pub struct Vacated { _alias: Option, _pages: Option, _descriptors: Option, _ring: Option } +pub struct Vacated { _alias: Option, pages: Option, _descriptors: Option, ring: Option, _kit: Option<()>, owner: Option } pub struct FreeListRelease; enum ControlRecord { FreeListRelease(FreeListRelease) } struct Rings; @@ -326,7 +327,7 @@ def build(mutation=None): previous: Option<()>, source_hint: SourceHint, source_readers: AtomicU32, rearm_for: Option, pool: Pool, graph: Graph, binding: Option, release_sent_ns: Option, free_list_generation: u64, released_at: u64, claims: u32, awaiting_witness: bool, - channel_index: u8, sustained: bool, + channel_index: u8, sustained: bool, backing_owner: Option, } impl Queue { @@QUEUE@@ @@ -405,13 +406,15 @@ def build(mutation=None): graph: Graph { ring: Some(DescriptorRing), m5: true }, binding: Some(Binding { context: context.clone(), pool_alias: None, descriptors: None }), release_sent_ns: None, free_list_generation: 1, released_at: 0, claims: 0, awaiting_witness: false, - channel_index: 0, sustained: true, + channel_index: 0, sustained: true, backing_owner: Some(owner), } } /// An idle queue whose owner released it at `released_at`; its pool still serves `vm`. fn released(qid: u8, vm: u32, released_at: u64) -> Queue { let mut queue = bound(qid, 0, &Context::new(1000 + u32::from(qid), vm), 0); queue.owner = None; + // Its owner closed: the backing is no longer kept for it. + queue.backing_owner = None; queue.released = true; queue.released_at = released_at; queue.sustained = false; @@ -442,8 +445,7 @@ def build(mutation=None): Some(SiblingSource::Fresh) => Ok(false), Some(SiblingSource::Vacant(qid)) => { reg.reserve_rearm(qid, owner)?; - // Off the device mutex: fresh pages and a descriptor ring; then, locked again, the - // production rearm_vacant() checks and steps. + // The production rearm_vacant() checks and steps, with the owner's spare pages and ring. let ready = { let queue = reg.queue(qid); queue.can_rearm() && queue.rearm_open(owner) @@ -452,7 +454,7 @@ def build(mutation=None): reg.release_rearm(qid, owner); return Ok(false); } - let (descriptor, _vacated) = reg.rearm_compute(qid, Pages(2), DescriptorRing)?; + let (descriptor, _vacated) = reg.rearm_compute(qid, owner, Pages(2), DescriptorRing)?; assert_eq!(descriptor, PoolDescriptor(u32::from(qid)), "the re-armed queue's row is written"); reg.bind_rearmed(qid, owner, context, channel_index)?; Ok(true) diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 681aaac2860e9..4d0d50f2a0e8a 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -1020,7 +1020,7 @@ def need(text, pattern, what): need(compute, r'Family::Descriptor,\s*size,\s*if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ size \},', 'compute descriptors: M5 uncached, G17P cached') # The compute graph, whose queue record is rebound in place, is an ordinary uncached allocation. - need(compute, r'let mut graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', + need(compute, r'let graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', 'compute graph uncached') if 'Family::QueueState' in compute: failures.append('compute graph not pooled') diff --git a/tools/asahi/g17-queue-object-charge-tests.py b/tools/asahi/g17-queue-object-charge-tests.py index fa4ad66de9a12..275942570136e 100644 --- a/tools/asahi/g17-queue-object-charge-tests.py +++ b/tools/asahi/g17-queue-object-charge-tests.py @@ -1,27 +1,31 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Kernel objects a client's QUEUE_CREATE builds are charged to that client. +"""Kernel objects a client's ioctls build for its queues are charged to that client. The G17 code builds per-queue firmware objects through an `Allocator` that -names the client whose queue they are for. QUEUE_CREATE builds the context -(scheduler storage, work state) in the client's ioctl, where a failure comes -back from the ioctl, so that Allocator names the client and its objects are -charged to it. +names the client whose queue they are for. Two ioctls build them, where a +failure comes back from the ioctl, so their Allocators name the client and +their objects are charged to it: +- QUEUE_CREATE builds the context (scheduler storage, work state) in + `Backend::new`; +- a compute SUBMIT builds its queue's compute backing (pool pages, descriptor + ring) in `Backend::provision_backing`. -Everything else is built at publication, after SUBMIT accepted the job: render -pairs, rings, generations, tiler heaps, compute state, timestamps. A failure -there would cost the client its device, so these stay uncharged (`client: -None`, plain `KernelObject::backing`) until they are built at QUEUE_CREATE or -SUBMIT. That work then charges them and empties PUBLICATION below. This test -fails when the split moves: +Everything else is built at publication, after SUBMIT accepted the job, or is +device memory: render pairs, rings, generations, tiler heaps, timestamps, and +the compute kit and shared compute objects, which outlive the client. A +failure at publication would cost the client its device, so these stay +uncharged (`client: None`, plain `KernelObject::backing`) until they are +built at QUEUE_CREATE or SUBMIT. That work then charges them and empties +PUBLICATION below. This test fails when the split moves: -- every `Allocator { .. }` literal sets `client`, exactly one (QUEUE_CREATE's, - in `Backend::new`) names the client, and all others say None; +- every `Allocator { .. }` literal sets `client`; exactly the two above name + the client, and all others say None; - `KernelObject::backing`, `KernelObject::new` and `gem::new_kernel_object*` appear only in object.rs, the global boot files and the PUBLICATION files. ---mutation drop-client / uncharged-backing / none-client inject each fault -and must be caught. +--mutation drop-client / uncharged-backing / none-client / uncharged-compute / +charged-kit inject each fault and must be caught. """ import argparse import re @@ -48,6 +52,14 @@ def sources(mutation): elif mutation == 'none-client': k = 'runtime.rs' files[k] = files[k].replace('client: vm.memory_client(),', 'client: None,', 1) + elif mutation == 'uncharged-compute': + k = 'runtime.rs' + files[k] = files[k].replace('let charged = super::object::Allocator { dev: &dev, uat: &uat, client };', + 'let charged = super::object::Allocator { dev: &dev, uat: &uat, client: None };', 1) + elif mutation == 'charged-kit': + k = 'runtime.rs' + files[k] = files[k].replace('let device = super::object::Allocator { dev: &dev, uat: &uat, client: None };', + 'let device = super::object::Allocator { dev: &dev, uat: &uat, client };', 1) return files @@ -71,15 +83,17 @@ def check(files): if 'client' not in body: failures.append(f'FAIL line {line(code, m.start())}: {name}: Allocator without a client') elif not re.search(r'client:\s*None', body): - named.append((name, code[m.end():m.end() + 200])) + functions = re.findall(r'\bfn (\w+)\s*[<(]', code[:m.start()]) + named.append((name, functions[-1] if functions else '')) if name not in GLOBAL | PUBLICATION: for m in UNCHARGED.finditer(code): failures.append(f'FAIL line {line(code, m.start())}: {name}: uncharged kernel object ' f'{m.group(0)} outside the global boot and publication files') - # QUEUE_CREATE's context is the only allocator that names a client. - if len(named) != 1 or named[0][0] != 'runtime.rs' or 'owner_pid' not in named[0][1]: - failures.append(f'FAIL line 0: allocators naming a client {[n for n, _ in named]}, ' - "expected only QUEUE_CREATE's context (Backend::new)") + # QUEUE_CREATE's context and a compute SUBMIT's backing are the allocators that name a client. + if sorted(named) != [('runtime.rs', 'new'), ('runtime.rs', 'provision_backing')]: + failures.append(f'FAIL line 0: allocators naming a client {named}, expected only ' + "QUEUE_CREATE's context (Backend::new) and SUBMIT's compute backing " + '(Backend::provision_backing)') if literals < 10: failures.append(f'FAIL line 0: only {literals} Allocator literals found; the scan is broken') return failures @@ -87,14 +101,16 @@ def check(files): def main(): parser = argparse.ArgumentParser() - parser.add_argument('--mutation', choices=['drop-client', 'uncharged-backing', 'none-client']) + parser.add_argument('--mutation', choices=['drop-client', 'uncharged-backing', 'none-client', + 'uncharged-compute', 'charged-kit']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: print(f) if failures: sys.exit(1) - print("ok: QUEUE_CREATE's context objects are charged to the client, publication's are not yet") + print("ok: QUEUE_CREATE's context and SUBMIT's compute backing are charged to the client, " + "publication's objects and device memory are not") if __name__ == '__main__': diff --git a/tools/asahi/g17-uninstalled-cleanup-tests.py b/tools/asahi/g17-uninstalled-cleanup-tests.py index d74f67aba6267..15edba3f67e3a 100644 --- a/tools/asahi/g17-uninstalled-cleanup-tests.py +++ b/tools/asahi/g17-uninstalled-cleanup-tests.py @@ -23,8 +23,8 @@ def fixture(): assert 'retired = entry.queue.take().map(|queue| (entry.reservation, queue));' in abort assert 'self.finish_uninstalled_compute(retired)?;' in abort assert 'cancel_unpublished' not in abort - start=abort.index(' drop(state);\n // Tentative replacement mappings') - end=abort.index('\n }',start) + start=abort.index(' // Tentative replacement mappings') + end=abort.index(' self.shared.queue_events();\n }',start)+len(' self.shared.queue_events();\n }') cleanup=abort[start:end] return r''' use std::sync::{Arc,Mutex,atomic::{AtomicBool,Ordering}}; @@ -45,15 +45,27 @@ def fixture(): assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst),"tentative aliases still live at identity return"); MAPPED.store(false,Ordering::SeqCst); }} +impl Queue {fn take_backing(&mut self)->Vacated{Vacated}} struct Tentative(&'static AtomicBool); impl Drop for Tentative{fn drop(&mut self){assert!(!LOCKED.load(Ordering::SeqCst));self.0.store(false,Ordering::SeqCst);}} +/// A queue's backing on its way back to its owner. +struct Vacated; +impl Vacated {fn drop_aliases(&mut self){assert!(!LOCKED.load(Ordering::SeqCst));}} +impl Drop for Vacated {fn drop(&mut self){assert!(!LOCKED.load(Ordering::SeqCst),"backing freed under device mutex");}} mod compute {pub(crate) use crate::Queue;} struct Registry; -impl Registry {fn cancel_compute(&mut self,res:ComputeReservation)->Result{ - assert_eq!(res.0,7); - assert!(!MAPPED.load(Ordering::SeqCst),"identity returned before aliases disappeared"); - assert!(RESERVED.swap(false,Ordering::SeqCst));Ok(()) -}} +impl Registry { + fn cancel_compute(&mut self,res:ComputeReservation)->Result{ + assert_eq!(res.0,7); + assert!(!MAPPED.load(Ordering::SeqCst),"identity returned before aliases disappeared"); + assert!(RESERVED.swap(false,Ordering::SeqCst));Ok(()) + } + fn keep_returned(&mut self,_:&mut Vacated){assert!(LOCKED.load(Ordering::SeqCst));} + // The tentative pages go back to their owner, no longer the builder's. + fn put_back(&mut self,_:u64,pages:Option,_:Option<()>,_:Option<()>)->Vacated{ + if let Some(pages)=pages{std::mem::forget(pages);PAGES.store(false,Ordering::SeqCst);}Vacated + } +} struct Firmware{queues:Registry} struct Guard<'a>(std::sync::MutexGuard<'a,Option>>); impl Deref for Guard<'_>{type Target=Option>;fn deref(&self)->&Self::Target{&self.0}} @@ -64,20 +76,20 @@ def fixture(): struct Available; impl Available {fn notify(&self){}} struct Shared{state:State,channels:Available} impl Shared{fn queue_events(&self){}} -struct Backend{shared:Arc} +struct Backend{shared:Arc,owner:u64} impl Backend { ''' +helper+r''' fn growth_cleanup(&self)->Result{ let mut alias=Some(Tentative(&ALIAS));let mut pages=Some(Tentative(&PAGES)); ALIAS.store(true,Ordering::SeqCst);PAGES.store(true,Ordering::SeqCst); let retired=Some((ComputeReservation(7),Box::new(Queue))); - let state=self.shared.state.lock(); + let (growth,result)=(Some(()),Err::<(),i32>(-11)); ''' +cleanup+r''' Ok(()) } } fn main(){ - let b=Backend{shared:Arc::new(Shared{state:State(Mutex::new(Some(Box::new(Firmware{queues:Registry})))),channels:Available})}; + let b=Backend{owner:1,shared:Arc::new(Shared{state:State(Mutex::new(Some(Box::new(Firmware{queues:Registry})))),channels:Available})}; b.finish_uninstalled_compute(None).unwrap(); for _ in 0..512 { MAPPED.store(true,Ordering::SeqCst);RESERVED.store(true,Ordering::SeqCst); @@ -95,8 +107,8 @@ def fixture(): def main(): source=fixture() cases=[('fixed',source),('cancel-before-alias-drop',source.replace('drop(queue);','core::mem::forget(queue);')), - ('keep-tentative-growth-aliases',source.replace('drop(alias.take());','').replace('drop(pages.take());','')), - ('drop-under-device-mutex',source.replace(' drop(queue);\n','').replace(' let mut state = self.shared.state.lock();',' let mut state = self.shared.state.lock();\n drop(queue);'))] + ('keep-tentative-growth-aliases',source.replace('drop(alias.take());','')), + ('drop-under-device-mutex',source.replace(' drop(queue);\n backing.drop_aliases();\n let mut state = self.shared.state.lock();',' backing.drop_aliases();\n let mut state = self.shared.state.lock();\n drop(queue);'))] with tempfile.TemporaryDirectory(prefix='g17-uninstalled-') as tmp: for name,code in cases: path=Path(tmp)/(name+'.rs');path.write_text(code);binary=path.with_suffix('') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 55f086d4591a4..e45eaffd4ec25 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -319,7 +319,9 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('no-guard', 'no-finish-enqueue'), []), 'g17-compute-constructor-tests.py': [([], PASS)], 'g17-compute-reserve-tests.py': [([], PASS)] + mutations( - '--mutation', ['allocating-bind', 'allocating-graph'], []), + '--mutation', ['allocating-bind', 'allocating-graph', 'publication-allocates', + 'claim-after-provision', 'free-returned', 'bind-other-owner', 'kit-needs-qid', + 'keep-idle'], []), 'g17-compute-owed-stamp-tests.py': [([], PASS)] + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', @@ -447,7 +449,8 @@ def mutations(flag, names, base, expect=KILL): 'g17-resource-tests.py': [([], PASS)], 'g17-shared-pool-tests.py': [([], PASS)], 'g17-queue-object-charge-tests.py': [([], PASS)] + mutations( - '--mutation', ['drop-client', 'uncharged-backing', 'none-client'], []), + '--mutation', ['drop-client', 'uncharged-backing', 'none-client', 'uncharged-compute', + 'charged-kit'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)], From 936c70c9dbddd7b67d5d7c5ebb0de50bb167e031 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 16:23:48 -0500 Subject: [PATCH 04/13] drm/asahi: commit compute backing after all channel preparation succeeds Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/freelist.rs | 24 ++-- drivers/gpu/drm/asahi/g17/fw/compute.rs | 6 + drivers/gpu/drm/asahi/g17/kick.rs | 13 ++- drivers/gpu/drm/asahi/g17/mod.rs | 3 + drivers/gpu/drm/asahi/g17/queue/compute.rs | 109 +++++++++++-------- drivers/gpu/drm/asahi/g17/runtime.rs | 102 +++++++---------- tools/asahi/g17-compute-constructor-tests.py | 16 ++- tools/asahi/g17-compute-reserve-tests.py | 20 +++- tools/asahi/g17-m5-sibling-compute-tests.py | 3 +- tools/asahi/g17-m5-sibling-rearm-tests.py | 5 +- 10 files changed, 167 insertions(+), 134 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index 3d00738e8e86c..91dac5a0131be 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -408,8 +408,9 @@ impl Pages { let (backing, charge) = match client { Some(client) => { let commit = crate::memacct::LEDGER.admit(client, size as u64)?; - let backing = alloc.lower_user_charged(size, mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_SHARED_RW)?; + let backing = client.charging(|| alloc.lower_user_charged( + size, mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, + ))?; let charge = crate::memacct::Charge::user(commit, None); charge.set_held(true); (backing, Some(charge)) @@ -1104,16 +1105,17 @@ impl ComputePool { } /// Binds `objects` and `pages` to the pool slot of `qid`: stores only. - pub(crate) fn bind(objects: PoolObjects, qid: u8, pages: Pages) -> Result { - if qid > super::fw::kick::QID_MAX { - return Err(EINVAL); - } - let PoolObjects { mut control, state } = objects; - let id = Self::slot(qid); - let m5 = pages.is_m5(); - Self::initialize_control(&mut control, &pages, id, state.gpu_va(), [0; 8])?; + pub(crate) fn prepare(objects: &mut PoolObjects, qid: u8, pages: &Pages) -> Result { + if qid > super::fw::kick::QID_MAX { return Err(EINVAL); } + Self::initialize_control(&mut objects.control, pages, Self::slot(qid), objects.state.gpu_va(), [0; 8])?; fence(Ordering::SeqCst); - Ok(Self { pages: Some(pages), client_vm: 0, control, state, id, m5 }) + Ok(()) + } + + pub(crate) fn bind(objects: PoolObjects, qid: u8, pages: Pages, client_vm: u64) -> Self { + let PoolObjects { control, state } = objects; + let m5 = pages.is_m5(); + Self { pages: Some(pages), client_vm, control, state, id: Self::slot(qid), m5 } } /// The pool slot (buffer slot) of `qid`'s pool. pub(crate) fn slot(qid: u8) -> u16 { diff --git a/drivers/gpu/drm/asahi/g17/fw/compute.rs b/drivers/gpu/drm/asahi/g17/fw/compute.rs index 6456eef4e7cda..6df87d1f45687 100644 --- a/drivers/gpu/drm/asahi/g17/fw/compute.rs +++ b/drivers/gpu/drm/asahi/g17/fw/compute.rs @@ -35,6 +35,12 @@ pub(crate) enum ComputeProgram { V25F84, } +impl ComputeProgram { + pub(crate) fn needs_shared_aperture(self) -> bool { + matches!(self, Self::G17P) + } +} + const V25F84_REGISTERS: usize = 36; const V25F84_CHECKPOINTS: [u16; 4] = [34, 35, 35, V25F84_REGISTERS as u16]; const V25F84_UNK_0A599_FIRST: u64 = 0x0000_0132_0040_0020; diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 8915bd9fef3fa..9662cc94af20d 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -646,21 +646,22 @@ impl ComputeRing { fence(Ordering::SeqCst); Ok(Self { high, low }) } + + pub(crate) fn map_client(&self, vm: &mmu::Vm) -> Result { + self.low.map_alias(vm, self.low.gpu_va(), CLIENT_KICK_PROT) + } } impl Queue { /// Binds `ring` to the QID of `id`: stores only. - pub(crate) fn compute(ring: ComputeRing, id: Id) -> Result { - if id.engine != DataMaster::Compute { - return Err(EINVAL); - } + pub(crate) fn compute(ring: ComputeRing, id: Id) -> Self { let ComputeRing { high, low } = ring; - Ok(Self { + Self { backing: Backing::Compute { high, low }, id, timestamp: KickTimestamp::FIRST, previous: None, - }) + } } /// Retired storage of a never-written ring is reused first. The returned view of the ring diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 5b35177f2331a..7d98e245ec481 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -1293,6 +1293,8 @@ struct Shared { #[pin] feed_work: Work, preparations: Arc, + #[pin] + compute_provision: Mutex<()>, /// Compute admission waiting for a physical channel: signalled when a channel becomes /// reusable or shareable, a QID or slot is returned, or a pool vacancy is witnessed. channels: Arc, @@ -2205,6 +2207,7 @@ impl Gpu { reclaim <- new_mutex!(reclaim, "g17::Shared::reclaim"), stop <- new_mutex!((), "g17::Shared::stop"), state <- new_mutex!(None, "g17::Shared::state"), + compute_provision <- new_mutex!((), "g17 compute provisioning"), actuators <- new_mutex!(thermal::Actuators::new(), "g17::Shared::actuators"), port: core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()), }), diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 03227664abe7b..9ea786a5f6d39 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -273,21 +273,7 @@ impl GraphObjects { impl Graph { /// Writes `context`'s queue record into `objects`: stores only. - fn new( - objects: GraphObjects, - ring: DescriptorRing, - context: &Context, - pointers: PointerLayout, - operand_state: &'static OperandState, - board: Option<&'static Board>, - program: ComputeProgram, - m5: bool, - mcache: bool, - ) -> Result { - let GraphObjects { - preempt, usage, operand, support, m5_timestamps, mut graph, context_low, context_high, - records, cached_records, - } = objects; + fn initialize(graph: &mut KernelObject, context: &Context, pointers: PointerLayout, m5: bool) -> Result { let graph_va = graph.gpu_va(); graph.initialize::(0, |view| { view.pointers = PointerBlock::new(&pointers)?; @@ -313,7 +299,24 @@ impl Graph { } else { graph.write(0, QueueRecord::new(&record))?; } - Ok(Self { + Ok(()) + } + + fn new( + objects: GraphObjects, + ring: DescriptorRing, + pointers: PointerLayout, + operand_state: &'static OperandState, + board: Option<&'static Board>, + program: ComputeProgram, + m5: bool, + mcache: bool, + ) -> Self { + let GraphObjects { + preempt, usage, operand, support, m5_timestamps, graph, context_low, context_high, + records, cached_records, + } = objects; + Self { m5, ring: Some(ring), preempt, @@ -333,7 +336,7 @@ impl Graph { board, program, mcache, - }) + } } /// All fallible mapping work finishes before replacing a physical queue's logical owner. @@ -342,24 +345,33 @@ impl Graph { context: Arc, kick_alias: mmu::KernelMapping, pool_alias: Option, + ) -> Result { + Self::map_binding( + self.m5, self.ring.as_ref().ok_or(EAGAIN)?, &self.preempt, &self.usage, + &self.operand, self.context_low.as_ref(), context, kick_alias, pool_alias, + ) + } + + fn map_binding( + m5: bool, ring: &DescriptorRing, preempt: &KernelObject, usage: &KernelObject, + operand: &KernelObject, context_low: Option<&KernelObject>, context: Arc, + kick_alias: mmu::KernelMapping, pool_alias: Option, ) -> Result { if !context.is_current() { return Err(EFAULT); } let vm = context.vm(); - if !self.m5 { vm.install_job_context_aliases()?; } - let descriptors = self.descriptor_alias(vm)?; - let prot = if self.m5 { mmu::PROT_GPU_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }; + if !m5 { vm.install_job_context_aliases()?; } + let descriptors = ring.object.map_alias(vm, ring.low.iova(), mmu::PROT_GPU_SHARED_RO)?; + let prot = if m5 { mmu::PROT_GPU_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }; let page = mmu::UAT_PGSZ as u64; let private = vm.client_private_range(); - let preempt = self - .preempt + let preempt = preempt .alias_in(vm, private.clone(), page, prot)?; - let usage = self.usage.alias_in(vm, private.clone(), page, prot)?; - let operand = self - .operand + let usage = usage.alias_in(vm, private.clone(), page, prot)?; + let operand = operand .alias_in(vm, private.clone(), page, prot)?; - let queue_context = self.context_low.as_ref() + let queue_context = context_low .map(|context| context.alias_in(vm, private.clone(), page, prot)).transpose()?; Ok(Binding { _kick_alias: kick_alias, @@ -817,9 +829,7 @@ impl Queue { identity." )] pub(crate) fn new_channel( - kit: Kit, - pages: crate::g17::freelist::Pages, - ring: DescriptorRing, + backing: &mut Option<(Kit, crate::g17::freelist::Pages, DescriptorRing)>, id: kick::Id, owner: u64, context: Arc, @@ -830,20 +840,32 @@ impl Queue { m5: bool, mcache: bool, channel_index: u8, - ) -> Result { - let Kit { pool, kick, graph } = kit; - let mut pool = ComputePool::bind(pool, id.qid(), pages)?; - let mut kick = kick::Queue::compute(kick, id)?; + install_row: impl FnOnce(PoolDescriptor) -> Result, + ) -> Result> { + let (kit, pages, ring) = backing.as_mut().ok_or(ENOSPC)?; + if id.engine() != DataMaster::Compute { return Err(EINVAL); } + let boxed = KBox::::new_uninit(GFP_KERNEL)?; let (active, replays) = (Fifo::new()?, Fifo::new()?); - let mut graph = - Graph::new(graph, ring, &context, pointers, operand_state, board, program, m5, mcache)?; - let kick_alias = kick.map_client(context.vm())?; - let pool_alias = Some(pool.map_client(context.vm())?); - let binding = graph.bind(context.clone(), kick_alias, pool_alias)?; + let source_readers = Arc::new(core::sync::atomic::AtomicU32::new(0), GFP_KERNEL)?; + ComputePool::prepare(&mut kit.pool, id.qid(), pages)?; + Graph::initialize(&mut kit.graph.graph, &context, pointers, m5)?; + let kick_alias = kit.kick.map_client(context.vm())?; + let pool_alias = Some(pages.map_client(context.vm())?); + let binding = Graph::map_binding( + m5, ring, &kit.graph.preempt, &kit.graph.usage, &kit.graph.operand, + kit.graph.context_low.as_ref(), context.clone(), kick_alias, pool_alias, + )?; + // Until the row is visible a failure returns the original backing to + // its owner. Every remaining step is an infallible ownership transfer. + install_row(pool_descriptor(pages, id.qid())?)?; + let (kit, pages, ring) = backing.take().expect("borrowed fresh backing"); + let pool = ComputePool::bind(kit.pool, id.qid(), pages, context.vm().id()); + let kick = kick::Queue::compute(kit.kick, id); + let graph = Graph::new(kit.graph, ring, pointers, operand_state, board, program, m5, mcache); context.mark_published(); context.note_compute_binding(true); crate::g17::trace::bind(crate::g17::trace::COMPUTE, kick.id().qid(), context.id(), 0); - Ok(Self { + Ok(boxed.write(Self { owner: Some(owner), channel_index, binding_noted: true, @@ -898,9 +920,9 @@ impl Queue { quarantine_error: None, failure_status_pending: false, retirement_proved: false, - source_readers: Arc::new(core::sync::atomic::AtomicU32::new(0), GFP_KERNEL)?, + source_readers, source_hint: crate::g17::sync_input::ReaderHint::new(), - }) + })) } /// The firmware failed the command whose completion stamp is `stamp`. It writes a /// zero-duration completion record for it, which quarantines the queue, but stores no @@ -2054,10 +2076,9 @@ impl Queue { pub(crate) fn backing_owner(&self) -> Option { self.backing_owner } - /// Whether `owner` may be bound to the backing this queue holds: its own, or one whose owner - /// closed. Another open owner's backing goes back to it first. + /// Only the provisioning owner can retain the charged pages and ring across a rebind. pub(crate) fn backing_free_for(&self, owner: u64) -> bool { - self.backing_owner.is_none_or(|holder| holder == owner) + self.backing_owner == Some(owner) } /// Whether the pool pages this queue holds, given back or not, serve `required`. pub(crate) fn backing_fits(&self, required: ComputeCapacity) -> bool { diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 297f935e0941b..ed09f90356c9d 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1353,22 +1353,6 @@ impl Registry { Ok(entry) } - /// The caller checked its preparation epoch and retained the same device - /// session before placing this graph where publication can find it. - pub(super) fn install_compute( - &mut self, - reservation: ComputeReservation, - queue: &mut Option>, - ) -> Result { - let built = queue.as_ref().ok_or(EINVAL)?; - if built.qid() != reservation.id.qid() || built.owner() != Some(reservation.owner) { - return Err(EIO); - } - let entry = self.reserved(reservation)?; - entry.queue.put(queue.take()); - Ok(()) - } - pub(super) fn cancel_compute(&mut self, reservation: ComputeReservation) -> Result { self.reserved(reservation)?; self.qids.cancel_unpublished(reservation.id)?; @@ -1816,7 +1800,7 @@ impl Backend { fn shared_compute(&self, admission: &Admission<'_>) -> Result { // The shared aperture is G17P compute state. M5 compute queues need only // their own pools, and the objects it would install are not M5's. - if self.context.is_m5() { + if !self.shared.variant.compute.needs_shared_aperture() { return Ok(()); } admission.check()?; @@ -1872,9 +1856,8 @@ impl Backend { /// Builds and installs a fresh compute queue for `reservation` as this owner's channel /// `channel_index`, from the kit and backing its SUBMIT provisioned: under the device mutex, - /// allocating no device memory. The pool row, and on G17P the global scheduler, are installed - /// first. On failure the reservation is cancelled, or the queue that was built comes back for - /// [`Self::finish_uninstalled_compute`]. Unused spares come back to be freed off the mutex. + /// allocating no device memory. Publish the pool row only after the channel and aliases + /// are ready. On failure, cancel the QID and restore all three spares to the owner. fn install_fresh( &self, firmware: &mut super::Firmware, @@ -1883,55 +1866,39 @@ impl Backend { channel_index: u8, ) -> (Result, Option, compute::Vacated) { let none = || compute::Vacated::spares(None, None, None); - let Some((kit, pages, ring)) = firmware.queues.take_fresh(self.owner, required) else { - let _ = firmware.queues.cancel_compute(reservation); - return (Err(ENOSPC), None, none()); - }; + let mut backing = firmware.queues.take_fresh(self.owner, required); let installed = (|| { - firmware.queues.reserved(reservation)?; - firmware.init.install_compute_pool( - compute::pool_descriptor(&pages, reservation.id.qid())?)?; - // The global scheduler is retained even if this queue's graph fails. - // It is G17P compute state; M5 has none. - if !self.context.is_m5() && !firmware.init.has_compute_scheduler() { + if backing.is_none() { return Err(ENOSPC); } + if self.shared.variant.compute.needs_shared_aperture() && !firmware.init.has_compute_scheduler() { let scheduler = firmware.queues.prepared_scheduler.take().ok_or(EIO)?; firmware.init.install_compute_scheduler(scheduler)?; } + let entry = firmware.queues.reserved(reservation)?; + let queue = compute::Queue::new_channel( + &mut backing, + reservation.id, + self.owner, + self.context.clone(), + self.shared.variant.pointers, + self.shared.operand_state, + self.shared.m5_board, + self.shared.variant.compute, + self.context.is_m5(), + self.shared.variant.mcache, + channel_index, + |row| firmware.init.install_compute_pool(row), + )?; + entry.queue.put(Some(queue)); Ok(()) })(); - if let Err(error) = installed { - let unused = firmware.queues.put_back(self.owner, Some(pages), Some(ring), Some(kit)); + if installed.is_err() { let _ = firmware.queues.cancel_compute(reservation); - return (Err(error), None, unused); - } - // Fails only on a broken invariant, or a kernel allocation too small to fail. - let queue = compute::Queue::new_channel( - kit, - pages, - ring, - reservation.id, - self.owner, - self.context.clone(), - self.shared.variant.pointers, - self.shared.operand_state, - self.shared.m5_board, - self.shared.variant.compute, - self.context.is_m5(), - self.shared.variant.mcache, - channel_index, - ) - .and_then(|queue| Ok(KBox::new(queue, GFP_KERNEL)?)); - let mut built = match queue { - Ok(queue) => Some(queue), - Err(error) => { - let _ = firmware.queues.cancel_compute(reservation); - return (Err(error), None, none()); + if let Some((kit, pages, ring)) = backing { + let unused = firmware.queues.put_back(self.owner, Some(pages), Some(ring), Some(kit)); + return (installed, None, unused); } - }; - match firmware.queues.install_compute(reservation, &mut built) { - Ok(()) => (Ok(()), None, none()), - Err(error) => (Err(error), built.map(|queue| (reservation, queue)), none()), } + (installed, None, none()) } fn grow_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { @@ -3267,13 +3234,23 @@ impl Backend { /// G17P's device-wide compute aperture and scheduler, until installed. fn provision_shared(&self) -> Result { - if self.context.is_m5() { + if !self.shared.variant.compute.needs_shared_aperture() { return Ok(()); } let needed = |firmware: &super::Firmware| ( !firmware.init.has_compute_shared() && firmware.queues.prepared_shared.is_none(), !firmware.init.has_compute_scheduler() && firmware.queues.prepared_scheduler.is_none(), ); + { + let state = self.shared.state.lock(); + if needed(state.as_deref().ok_or(ENODEV)?) == (false, false) { + return Ok(()); + } + } + // No device mutex is held across allocation. Recovery joins this + // lease before replacing the firmware or tearing down its roots. + let _builder = self.shared.compute_provision.lock(); + let lease = self.shared.preparations.enter(true)?; let (uat, (shared, scheduler)) = { let state = self.shared.state.lock(); let firmware = state.as_deref().ok_or(ENODEV)?; @@ -3291,6 +3268,7 @@ impl Backend { })?; let mut state = self.shared.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { return Err(EAGAIN); } let (want_shared, want_scheduler) = needed(firmware); if want_shared { firmware.queues.prepared_shared = shared.take(); @@ -3299,7 +3277,7 @@ impl Backend { firmware.queues.prepared_scheduler = scheduler.take(); } drop(state); - // Another SUBMIT prepared them first: these drop off the device mutex. + // Drop any unused allocation off the device mutex. drop((shared, scheduler)); Ok(()) } diff --git a/tools/asahi/g17-compute-constructor-tests.py b/tools/asahi/g17-compute-constructor-tests.py index c75b1ee4bd919..a6959201e00e1 100644 --- a/tools/asahi/g17-compute-constructor-tests.py +++ b/tools/asahi/g17-compute-constructor-tests.py @@ -47,11 +47,14 @@ def fixture(): const ADMISSION: Admission<'static> = Admission(std::marker::PhantomData); impl Admission<'_>{fn check(&self)->Result{if CANCEL.load(Ordering::SeqCst){Err(ECANCELED)}else{Ok(())}}} struct Gate;struct Lease; -impl Gate{fn enter_until(&self,a:&Admission<'_>)->Result{a.check()?;Ok(Lease)}} +impl Gate{fn enter(&self,_:bool)->Result{Ok(Lease)} fn enter_until(&self,a:&Admission<'_>)->Result{a.check()?;Ok(Lease)}} impl Lease{fn is_current(&self)->bool{CURRENT.load(Ordering::SeqCst)}} struct State(Mutex>>); impl State{fn lock(&self)->MutexGuard<'_,Option>>{self.0.lock().unwrap()}} -struct Shared{preparations:Gate,state:State,crashed:AtomicBool} +struct Variant{compute:Layout} +struct Layout(bool);impl Layout{fn needs_shared_aperture(&self)->bool{self.0}} +struct Builder(Mutex<()>);impl Builder{fn lock(&self)->MutexGuard<'_,()>{self.0.lock().unwrap()}} +struct Shared{variant:Variant,compute_provision:Builder,preparations:Gate,state:State,crashed:AtomicBool} impl Shared{fn drm(&self)->Result<()>{Ok(())}} struct Context{m5:bool}impl Context{fn vm(&self)->&(){&()} fn is_m5(&self)->bool{self.m5}} struct Backend{shared:Shared,context:Context} @@ -79,14 +82,19 @@ def fixture(): ''' + methods + r''' } fn backend(m5:bool,shared:bool,scheduler:bool)->Backend{ - Backend{context:Context{m5},shared:Shared{preparations:Gate,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(), + Backend{context:Context{m5},shared:Shared{variant:Variant{compute:Layout(!m5)},compute_provision:Builder(Mutex::new(())),preparations:Gate,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(), init:Init{shared,scheduler,cached:0},queues:Queues{prepared_shared:None,prepared_scheduler:None}}))))}} } fn fw<'a>(b:&'a Backend)->MutexGuard<'a,Option>>{b.shared.state.lock()} fn main(){ // SUBMIT: allocates what is neither installed nor prepared, once. let b=backend(false,false,false); - assert_eq!(b.provision_shared(),Ok(())); + let start=std::sync::Barrier::new(8); + std::thread::scope(|scope| { + for _ in 0..8 { + scope.spawn(|| { start.wait(); assert_eq!(b.provision_shared(),Ok(())); }); + } + }); assert_eq!(ALLOCATED.load(Ordering::SeqCst),2); assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_some()&&fw(&b).as_ref().unwrap().queues.prepared_scheduler.is_some()); assert_eq!(b.provision_shared(),Ok(())); diff --git a/tools/asahi/g17-compute-reserve-tests.py b/tools/asahi/g17-compute-reserve-tests.py index 1653138b9f885..b5356b54e84cc 100644 --- a/tools/asahi/g17-compute-reserve-tests.py +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -65,8 +65,8 @@ def sources(mutation): 'queue/mod.rs', 'queue/compute/reserve.rs']} if mutation == 'allocating-bind': files['freelist.rs'] = files['freelist.rs'].replace( - ' let PoolObjects { mut control, state } = objects;', - ' let PoolObjects { mut control, state } = objects;\n' + ' let PoolObjects { control, state } = objects;', + ' let PoolObjects { control, state } = objects;\n' ' let _ = alloc.kernel(CONTROL_SIZE, 0, mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined);', 1) elif mutation == 'allocating-graph': files['queue/compute.rs'] = files['queue/compute.rs'].replace( @@ -104,7 +104,8 @@ def sources(mutation): BINDS = [ ('freelist.rs', 'pub(crate) fn bind(objects: PoolObjects', 'binding pool objects to a QID'), ('kick.rs', 'pub(crate) fn compute(ring: ComputeRing', 'binding a kick ring to a QID'), - ('queue/compute.rs', 'impl Graph {\n /// Writes', "writing an owner's queue record"), + ('queue/compute.rs', 'fn initialize(graph: &mut KernelObject', "writing an owner's queue record"), + ('queue/compute.rs', 'fn new(\n objects: GraphObjects', 'assembling a fresh graph'), ('queue/compute.rs', 'pub(crate) fn new_channel(', 'assembling a fresh queue'), ] @@ -134,7 +135,18 @@ def structure(files): f'publication {signature.strip()} allocates ({m.group(0)})') backend = files['runtime/backend.rs'] provision = item(runtime, ' fn provision_backing(') + channel = item(files['queue/compute.rs'], 'pub(crate) fn new_channel(') + fresh = item(runtime, ' fn install_fresh(') checks = { + 'failed channel construction returns the kit, pages and ring to their owner': + ordered(channel, 'KBox::::new_uninit', 'Graph::map_binding(', 'install_row(', 'backing.take()') + and '?' not in channel.split('backing.take()', 1)[1], + 'a failed build restores the reservation': + ordered(fresh, 'Queue::new_channel(', 'cancel_compute(reservation)', 'put_back(self.owner, Some(pages), Some(ring), Some(kit))'), + 'M5 pool population uses the DRM opener': + 'client.charging(|| alloc.lower_user_charged(' in files['freelist.rs'], + 'charged backing from a closed owner cannot be rebound to a different client': + 'self.backing_owner == Some(owner)' in item(files['queue/compute.rs'], 'pub(crate) fn backing_free_for('), 'SUBMIT provisions before validation returns': 'self.provision_compute(required)' in item(backend, ' fn ensure_compute('), 'SUBMIT charges pages and ring to the client, the kit is device memory': ordered( provision, 'let charged = super::object::Allocator { dev: &dev, uat: &uat, client };', @@ -307,8 +319,6 @@ def check(files): failures.append(f'FAIL line 0: {name}: {signature!r} is missing') continue body = item(text, signature) - if signature.startswith('impl Graph'): - body = item(body, 'fn new(') for m in ALLOCATING.finditer(code(body)): line = text.count('\n', 0, text.index(signature)) + code(body).count('\n', 0, m.start()) + 1 failures.append(f'FAIL line {line}: {name}: {why} allocates ({m.group(0)})') diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py index d276ba1a55f74..27ef6aabd73ab 100755 --- a/tools/asahi/g17-m5-sibling-compute-tests.py +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -179,7 +179,8 @@ def build_harness(mutation=None): and 'PoolBorrow' not in queue_src and 'shared_pool' not in queue_src and 'self.install_fresh(firmware, reservation, required, channel_index)' in try_add_sib_fn - and 'compute::pool_descriptor(&pages, reservation.id.qid())?' in item(runtime_src, 'fn install_fresh(') + and '|row| firmware.init.install_compute_pool(row)' in item(runtime_src, 'fn install_fresh(') + and 'install_row(pool_descriptor(pages, id.qid())?)?' in item(queue_src, 'pub(crate) fn new_channel(') and ordered_ok(source_fn, 'if queue.pool_vacant() {', '} else if queue.pool_serves(vm) && queue.backing_free_for(owner) {', '!queue.pool_fits(required)', '&mut warm') diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index 14fe29722d25d..9adb38d865de6 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -612,9 +612,12 @@ def build(mutation=None): reg.push(bound(10, B, &b, 2)); reg.push(released(12, 999, 6)); assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Fresh)); - // A warm same-VM queue comes before a vacant one. + // A closed owner's charge cannot follow the ring to another queue, even in the same VM. reg.push(vacant(11, 1)); reg.push(released(18, 200, 9)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(11))); + // A warm same-VM queue retaining B's own backing comes before a vacant one. + reg.compute_queue_mut(18).unwrap().backing_owner = Some(B); assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Warm(18))); assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(true))); assert_eq!(reg.queue(18).channel_index, 1); From dd689189fef6273aaa8098deb8fba0ce46d70b7f Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:07:28 -0300 Subject: [PATCH 05/13] drm/asahi: g17: provision the compute aperture where InitData has its objects The device-wide compute aperture and scheduler are provisioned at SUBMIT and installed at publication only where needs_shared_aperture(), the variant's compute program, said so. That is G17P for the M5 variants too, which inherit it: an M5 SUBMIT then prepared the aperture and its publication installed it into InitData that has no boot free list (ENODEV), losing the device at boot on J714s. The V25F84 program, which T6041's 26B123 build also has, got no aperture or scheduler at all, where main builds both for every G17 firmware but M5. Decide by the InitData itself: hosts_compute_aperture() is whether the firmware build has the boot free list's control and state the aperture is installed into. M5's has none; every other G17 build has both. All three sites (SUBMIT provisioning, publication install, scheduler install) use it, and needs_shared_aperture() goes. While here, the publication takes the prepared aperture only once its install succeeded, so a failed install leaves it for the next one, and a recovery that replaced the firmware while SUBMIT allocated now prepares again for the new firmware, as the gate reopens, instead of returning EAGAIN from SUBMIT; the stale allocation is dropped off the device mutex. g17-compute-constructor-tests covers M5 with G17P's compute program, V25F84 and the retry, with mutations that gate on the compute program again and that return EAGAIN. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/fw/compute.rs | 6 - drivers/gpu/drm/asahi/g17/initdata.rs | 19 +++- drivers/gpu/drm/asahi/g17/runtime.rs | 112 ++++++++++--------- tools/asahi/g17-compute-constructor-tests.py | 66 ++++++++--- 4 files changed, 123 insertions(+), 80 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fw/compute.rs b/drivers/gpu/drm/asahi/g17/fw/compute.rs index a1753770ae559..cd7cc86aedbd5 100644 --- a/drivers/gpu/drm/asahi/g17/fw/compute.rs +++ b/drivers/gpu/drm/asahi/g17/fw/compute.rs @@ -35,12 +35,6 @@ pub(crate) enum ComputeProgram { V25F84, } -impl ComputeProgram { - pub(crate) fn needs_shared_aperture(self) -> bool { - matches!(self, Self::G17P) - } -} - const V25F84_REGISTERS: usize = 36; const V25F84_REGISTERS_MAX: usize = V25F84_REGISTERS + 1; const V25F84_CHECKPOINTS: [u16; 4] = [34, 35, 35, V25F84_REGISTERS as u16]; diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 499359d3d4559..97b815b963029 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -519,12 +519,23 @@ impl InitData { self.compute_shared.is_some() } - /// Install a prepared pool once while holding the device mutex. A competing preparer may - /// have installed its own first; the redundant one then drops. - pub(super) fn install_compute_shared(&mut self, shared: ComputeShared) -> Result { + /// Whether this firmware's InitData has the objects the device-wide compute aperture and + /// scheduler serve: the boot free list's control and state. An M5 build has none, whatever + /// its compute program. + pub(super) fn hosts_compute_aperture(&self) -> bool { + self.boot_control.is_some() && self.boot_state.is_some() + } + + /// Install the pool in `prepared` once while holding the device mutex, taking it only once + /// the install succeeded: a failed install leaves it prepared. A competing preparer may + /// have installed its own first; the redundant one then stays in `prepared`. + pub(super) fn install_compute_shared(&mut self, prepared: &mut Option) -> Result { if self.compute_shared.is_some() { return Ok(()); } + if prepared.is_none() { + return Err(EIO); + } let boot_control = self.boot_control.ok_or(ENODEV)?; let boot_state = self.boot_state.ok_or(ENODEV)?; let state_va = self.object(boot_state)?.gpu_va(); @@ -541,7 +552,7 @@ impl InitData { self.object_mut(boot_control)?.write(0, control)?; self.object_mut(boot_state)?.bytes_mut().fill(0); fence(Ordering::SeqCst); - self.compute_shared = Some(shared); + self.compute_shared = prepared.take(); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 650225872126b..7476a8c6187b3 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1929,11 +1929,6 @@ impl Backend { /// Installs the shared aperture this owner's SUBMIT prepared, if no publication did yet, and /// maps it into the owner's VM. Recovery joins the lease before closing roots. fn shared_compute(&self, admission: &Admission<'_>) -> Result { - // The shared aperture is G17P compute state. M5 compute queues need only - // their own pools, and the objects it would install are not M5's. - if !self.shared.variant.compute.needs_shared_aperture() { - return Ok(()); - } admission.check()?; let lease = self.shared.preparations.enter_until(admission)?; let mut state = self.shared.state.lock(); @@ -1945,11 +1940,13 @@ impl Backend { if !lease.is_current() { return Err(EAGAIN); } - if !firmware.init.has_compute_shared() { - // This command's SUBMIT left it prepared; only an install takes it. - let shared = firmware.queues.prepared_shared.take().ok_or(EIO)?; - firmware.init.install_compute_shared(shared)?; + // The shared aperture is G17P compute state. M5 compute queues need only their own + // pools, and M5's InitData has nothing it would install into. + if !firmware.init.hosts_compute_aperture() { + return Ok(()); } + // This command's SUBMIT left it prepared; only an install takes it. + firmware.init.install_compute_shared(&mut firmware.queues.prepared_shared)?; firmware.init.cache_compute_vm(self.context.vm()) } @@ -2000,7 +1997,7 @@ impl Backend { let mut backing = firmware.queues.take_fresh(self.owner, required); let installed = (|| { if backing.is_none() { return Err(ENOSPC); } - if self.shared.variant.compute.needs_shared_aperture() && !firmware.init.has_compute_scheduler() { + if firmware.init.hosts_compute_aperture() && !firmware.init.has_compute_scheduler() { let scheduler = firmware.queues.prepared_scheduler.take().ok_or(EIO)?; firmware.init.install_compute_scheduler(scheduler)?; } @@ -3593,54 +3590,61 @@ impl Backend { self.provision_backing(required) } - /// G17P's device-wide compute aperture and scheduler, until installed. + /// G17P's device-wide compute aperture and scheduler, until installed. Firmware whose + /// InitData has nothing to install them into (M5) needs neither. fn provision_shared(&self) -> Result { - if !self.shared.variant.compute.needs_shared_aperture() { - return Ok(()); - } - let needed = |firmware: &super::Firmware| ( - !firmware.init.has_compute_shared() && firmware.queues.prepared_shared.is_none(), - !firmware.init.has_compute_scheduler() && firmware.queues.prepared_scheduler.is_none(), - ); - { - let state = self.shared.state.lock(); - if needed(state.as_deref().ok_or(ENODEV)?) == (false, false) { + let needed = |firmware: &super::Firmware| { + let hosts = firmware.init.hosts_compute_aperture(); + (hosts && !firmware.init.has_compute_shared() && firmware.queues.prepared_shared.is_none(), + hosts && !firmware.init.has_compute_scheduler() && firmware.queues.prepared_scheduler.is_none()) + }; + loop { + { + let state = self.shared.state.lock(); + if needed(state.as_deref().ok_or(ENODEV)?) == (false, false) { + return Ok(()); + } + } + // No device mutex is held across allocation. Recovery joins this + // lease before replacing the firmware or tearing down its roots. + let _builder = self.shared.compute_provision.lock(); + let lease = self.shared.preparations.enter(true)?; + let (uat, (shared, scheduler)) = { + let state = self.shared.state.lock(); + let firmware = state.as_deref().ok_or(ENODEV)?; + (firmware.uat.clone(), needed(firmware)) + }; + if !shared && !scheduler { + return Ok(()); + } + let dev = self.shared.drm()?; + // Device memory: installed, they serve every client until processor stop. + let alloc = super::object::Allocator { dev: &dev, uat: &uat, client: None }; + let (mut shared, mut scheduler) = crate::memacct::device_memory(|| -> Result<_> { + Ok((shared.then(super::initdata::ComputeShared::new).transpose()?, + scheduler.then(|| super::initdata::ComputeScheduler::new(&alloc)).transpose()?)) + })?; + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + // A recovery replaced the firmware meanwhile: prepare for the new one, once the + // gate reopens, instead of failing the SUBMIT. + let current = lease.is_current(); + if current { + let (want_shared, want_scheduler) = needed(firmware); + if want_shared { + firmware.queues.prepared_shared = shared.take(); + } + if want_scheduler { + firmware.queues.prepared_scheduler = scheduler.take(); + } + } + drop(state); + // Drop any unused allocation off the device mutex. + drop((shared, scheduler)); + if current { return Ok(()); } } - // No device mutex is held across allocation. Recovery joins this - // lease before replacing the firmware or tearing down its roots. - let _builder = self.shared.compute_provision.lock(); - let lease = self.shared.preparations.enter(true)?; - let (uat, (shared, scheduler)) = { - let state = self.shared.state.lock(); - let firmware = state.as_deref().ok_or(ENODEV)?; - (firmware.uat.clone(), needed(firmware)) - }; - if !shared && !scheduler { - return Ok(()); - } - let dev = self.shared.drm()?; - // Device memory: installed, they serve every client until processor stop. - let alloc = super::object::Allocator { dev: &dev, uat: &uat, client: None }; - let (mut shared, mut scheduler) = crate::memacct::device_memory(|| -> Result<_> { - Ok((shared.then(super::initdata::ComputeShared::new).transpose()?, - scheduler.then(|| super::initdata::ComputeScheduler::new(&alloc)).transpose()?)) - })?; - let mut state = self.shared.state.lock(); - let firmware = state.as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { return Err(EAGAIN); } - let (want_shared, want_scheduler) = needed(firmware); - if want_shared { - firmware.queues.prepared_shared = shared.take(); - } - if want_scheduler { - firmware.queues.prepared_scheduler = scheduler.take(); - } - drop(state); - // Drop any unused allocation off the device mutex. - drop((shared, scheduler)); - Ok(()) } /// This owner's compute backing for a publication at `required`, unless its spares or its diff --git a/tools/asahi/g17-compute-constructor-tests.py b/tools/asahi/g17-compute-constructor-tests.py index 0c0e6f04d64bc..47a23f2851272 100644 --- a/tools/asahi/g17-compute-constructor-tests.py +++ b/tools/asahi/g17-compute-constructor-tests.py @@ -6,8 +6,10 @@ (publication) against mocked firmware state, allocations and leases: - SUBMIT allocates the shared aperture and the scheduler while neither is installed nor - prepared, as device memory (the root memory cgroup), and nothing on M5; an allocation - failure is the SUBMIT's error and leaves nothing prepared; + prepared, as device memory (the root memory cgroup), and nothing where the firmware's + InitData has no aperture objects (M5, whose variants share G17P's compute program); an + allocation failure is the SUBMIT's error and leaves nothing prepared, and a recovery + during the allocation prepares again instead of failing the SUBMIT; - publication installs the prepared aperture, never allocates, fails with EIO if none was prepared, and checks the admission, the crash flag and its lease before installing. """ @@ -42,13 +44,13 @@ def fixture(): const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const ENOMEM:i32=-12;const ECANCELED:i32=-125; static ALLOCATED:AtomicUsize=AtomicUsize::new(0);static REFUSE:AtomicBool=AtomicBool::new(false); static DEVICE_SCOPE:AtomicBool=AtomicBool::new(false);static CANCEL:AtomicBool=AtomicBool::new(false); -static CURRENT:AtomicBool=AtomicBool::new(true); +static CURRENT:AtomicBool=AtomicBool::new(true);static STALE:AtomicUsize=AtomicUsize::new(0); struct Admission<'a>(std::marker::PhantomData<&'a ()>); const ADMISSION: Admission<'static> = Admission(std::marker::PhantomData); impl Admission<'_>{fn check(&self)->Result{if CANCEL.load(Ordering::SeqCst){Err(ECANCELED)}else{Ok(())}}} struct Gate;struct Lease; impl Gate{fn enter(&self,_:bool)->Result{Ok(Lease)} fn enter_until(&self,a:&Admission<'_>)->Result{a.check()?;Ok(Lease)}} -impl Lease{fn is_current(&self)->bool{CURRENT.load(Ordering::SeqCst)}} +impl Lease{fn is_current(&self)->bool{if STALE.load(Ordering::SeqCst)>0{STALE.fetch_sub(1,Ordering::SeqCst);return false;}CURRENT.load(Ordering::SeqCst)}} struct State(Mutex>>); impl State{fn lock(&self)->MutexGuard<'_,Option>>{self.0.lock().unwrap()}} struct Variant{compute:Layout} @@ -69,21 +71,27 @@ def fixture(): #[derive(Debug)]struct ComputeShared;#[derive(Debug)]struct ComputeScheduler; impl ComputeShared{fn new()->Result{allocate()?;Ok(Self)}} impl ComputeScheduler{fn new(a:&Allocator<'_>)->Result{assert!(a.client.is_none());allocate()?;Ok(Self)}} -struct Init{shared:bool,scheduler:bool,cached:usize} +struct Init{aperture:bool,shared:bool,scheduler:bool,cached:usize} impl Init{ + fn hosts_compute_aperture(&self)->bool{self.aperture} fn has_compute_shared(&self)->bool{self.shared} fn has_compute_scheduler(&self)->bool{self.scheduler} fn cache_compute_vm(&mut self,_:&())->Result{self.cached+=1;Ok(())} - fn install_compute_shared(&mut self,_:ComputeShared)->Result{self.shared=true;Ok(())} + fn install_compute_shared(&mut self,prepared:&mut Option)->Result{ + if self.shared{return Ok(());}if prepared.is_none(){return Err(EIO);}if !self.aperture{return Err(ENODEV);} + *prepared=None;self.shared=true;Ok(())} } struct Queues{prepared_shared:Option,prepared_scheduler:Option} struct Firmware{init:Init,uat:(),queues:Queues} impl Backend{ ''' + methods + r''' } -fn backend(m5:bool,shared:bool,scheduler:bool)->Backend{ - Backend{context:Context{m5},shared:Shared{variant:Variant{compute:Layout(!m5)},compute_provision:Builder(Mutex::new(())),preparations:Gate,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(), - init:Init{shared,scheduler,cached:0},queues:Queues{prepared_shared:None,prepared_scheduler:None}}))))}} +// `g17p`: the variant's compute program is G17P's, which M5 variants share; only the InitData +// objects decide. +fn backend(m5:bool,shared:bool,scheduler:bool)->Backend{backend_of(m5,!m5,shared,scheduler)} +fn backend_of(m5:bool,g17p:bool,shared:bool,scheduler:bool)->Backend{ + Backend{context:Context{m5},shared:Shared{variant:Variant{compute:Layout(g17p)},compute_provision:Builder(Mutex::new(())),preparations:Gate,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(), + init:Init{aperture:!m5,shared,scheduler,cached:0},queues:Queues{prepared_shared:None,prepared_scheduler:None}}))))}} } fn fw<'a>(b:&'a Backend)->MutexGuard<'a,Option>>{b.shared.state.lock()} fn main(){ @@ -132,14 +140,30 @@ def fixture(): assert!(!fw(&b).as_ref().unwrap().init.shared&&fw(&b).as_ref().unwrap().queues.prepared_shared.is_some(),"a refused publication must keep the prepared aperture"); assert_eq!(b.shared_compute(&ADMISSION),Ok(())); assert!(fw(&b).as_ref().unwrap().init.shared); - // M5 has neither: nothing is allocated or installed. + // M5 has neither, also with G17P's compute program: nothing is allocated or installed. + for g17p in [false,true]{ + let before=ALLOCATED.load(Ordering::SeqCst); + let b=backend_of(true,g17p,false,false); + assert_eq!(b.provision_shared(),Ok(()),"M5 has neither"); + assert_eq!(b.shared_compute(&ADMISSION),Ok(()),"M5 has neither"); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before,"M5 has neither"); + assert!(!fw(&b).as_ref().unwrap().init.shared,"M5 has neither"); + } + // A G17 variant whose compute program is not G17P's (V25F84) still has both. let before=ALLOCATED.load(Ordering::SeqCst); - let b=backend(true,false,false); + let b=backend_of(false,false,false,false); assert_eq!(b.provision_shared(),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before+2,"V25F84 firmware has the aperture objects"); assert_eq!(b.shared_compute(&ADMISSION),Ok(())); - assert_eq!(ALLOCATED.load(Ordering::SeqCst),before); - assert!(!fw(&b).as_ref().unwrap().init.shared); - println!("PASS G17P compute aperture and scheduler: SUBMIT prepares them once as device memory and fails on a refusal; publication installs the prepared aperture, never allocates, and keeps it on cancel, stale lease or crash; M5 has neither"); + assert!(fw(&b).as_ref().unwrap().init.shared,"V25F84 firmware has the aperture objects"); + // A recovery while SUBMIT allocated: it prepares again for the new firmware, not EAGAIN. + let before=ALLOCATED.load(Ordering::SeqCst); + let b=backend(false,false,false); + STALE.store(1,Ordering::SeqCst); + assert_eq!(b.provision_shared(),Ok(()),"a stale lease must prepare again"); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before+4); + assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_some()); + println!("PASS G17P compute aperture and scheduler: SUBMIT prepares them once as device memory, fails on a refusal and prepares again after a recovery; publication installs the prepared aperture, never allocates, and keeps it on cancel, stale lease or crash; M5 has neither, whatever its compute program"); } ''' @@ -149,8 +173,10 @@ def main(): mutants = [ ('fixed', source, ''), ('publication-builds', source.replace( - 'let shared = firmware.queues.prepared_shared.take().ok_or(EIO)?;', - 'let shared = firmware.queues.prepared_shared.take().map_or_else(|| device_memory(ComputeShared::new), Ok)?;'), + 'firmware.init.install_compute_shared(&mut firmware.queues.prepared_shared)?;', + 'if firmware.queues.prepared_shared.is_none() { firmware.queues.prepared_shared = ' + 'Some(device_memory(ComputeShared::new)?); }\n' + ' firmware.init.install_compute_shared(&mut firmware.queues.prepared_shared)?;'), 'publication must not allocate'), ('charged-to-client', source.replace('= device_memory(|| -> Result<_>', '= no_scope(|| -> Result<_>'), 'must be device memory'), @@ -158,6 +184,14 @@ def main(): 'shared.then(ComputeShared::new).transpose()?', 'shared.then(ComputeShared::new).transpose().unwrap_or(None)').replace( '(&alloc)).transpose()?', '(&alloc)).transpose().unwrap_or(None)'), 'must fail the SUBMIT'), + ('program-gate', source.replace( + 'let hosts = firmware.init.hosts_compute_aperture();', + 'let hosts = self.shared.variant.compute.needs_shared_aperture();'), + 'M5 has neither'), + ('stale-lease-fails', source.replace( + ' let current = lease.is_current();\n', + ' let current = lease.is_current();\n if !current { return Err(EAGAIN); }\n'), + 'a stale lease must prepare again'), ] with tempfile.TemporaryDirectory(prefix='g17-compute-constructors-') as tmp: for name, code, expected in mutants: From b5f721b011a96f41a632e1ff67d980727c60a267 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:12:40 -0300 Subject: [PATCH 06/13] drm/asahi: g17: return compute backing to its owner after its client views A queue that gives its pool pages and descriptor ring back to an owner with compute commands put them into the owner's spares under the device mutex, from observe_pool_releases(), service_compute_pools(), rearm_vacant() and growth, while the Vacated still held the client aliases of the same pages and ring, to be dropped off the mutex later. Pages and rings map into a client VM at their own fixed addresses, so a publication of the same owner that took them in between (the event pass notifies channel waiters before its deferred batch runs) mapped them again over the live alias: a drm_mm collision, and a lost device. keep_backing() also reset the pages there, which on M5 allocates with GFP_KERNEL under the device mutex, and on a failed reset kept the pages in the Vacated, to be freed without a word. Give each owner's spares their own lock, in an Arc that the owner's reserve and backing on its way back share (compute::reserve::Reserve). keep_backing() now only names that reserve as where the Vacated returns; dropping the Vacated, off the device mutex, drops its client views first, then resets the pages and clears the ring, puts them back and wakes the channel waiters. Pages whose tables cannot be written again are freed; the owner's next SUBMIT provisions. The spares lock is a leaf: taken inside the device mutex, never around it. g17-compute-reserve-tests runs the production keep_backing(), give_back() and Vacated drop: backing returns only after its client views and with a wake, and unresettable pages are freed; the return-before-unmap mutation must be caught. Fixtures of the growth and M5 sibling re-arm tests follow the Vacated field. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/compute.rs | 33 +++++- .../drm/asahi/g17/queue/compute/reserve.rs | 66 ++++++++++- drivers/gpu/drm/asahi/g17/runtime.rs | 88 +++++++-------- tools/asahi/g17-compute-reserve-tests.py | 106 +++++++++++++----- tools/asahi/g17-growth-tests.py | 4 +- tools/asahi/g17-m5-sibling-rearm-tests.py | 2 +- tools/asahi/run-host-tests.py | 2 +- 7 files changed, 214 insertions(+), 87 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index f61b329724e99..f281c813a4410 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -74,8 +74,8 @@ static_assert!(core::mem::offset_of!(GraphLayout, items) == ITEMS); /// Aliases are destroyed before the logical root they name. Superseded bindings remain owned /// until the first exact successful publication under their replacement has retired. -/// Backing of a vacated pool and descriptor ring, freed outside the device -/// mutex. Field order drops each client alias before the storage it names. +/// Backing of a vacated pool and descriptor ring, freed or returned to its owner outside the +/// device mutex. Field order drops each client alias before the storage it names. pub(crate) struct Vacated { _alias: Option, pages: Option, @@ -86,21 +86,37 @@ pub(crate) struct Vacated { /// The owner whose backing the pages and ring are, which they go back to while it has /// compute commands ([`reserve`]). owner: Option, + /// The owner's spares, which the pages and ring return to when this is dropped. + returns: Option>, +} + +impl Drop for Vacated { + fn drop(&mut self) { + let Some(reserve) = self.returns.take() else { return }; + // The pages and ring map at the same client addresses again: their views go first. + self.drop_aliases(); + reserve.give_back(self.pages.take(), self.ring.take()); + } } impl Vacated { /// Spare backing to free off the device mutex. pub(crate) fn spares(pages: Option, ring: Option, kit: Option) -> Self { - Self { _alias: None, pages, _descriptors: None, ring, _kit: kit, owner: None } + Self { _alias: None, pages, _descriptors: None, ring, _kit: kit, owner: None, returns: None } } /// The owner the pages and ring go back to. pub(crate) fn returns_to(&self) -> Option { self.owner } - /// The pages and ring, to keep for their owner. Whatever is put back is freed with the rest. - pub(crate) fn backing(&mut self) -> (&mut Option, &mut Option) { - (&mut self.pages, &mut self.ring) + /// Returns the pages and ring to `reserve`, their owner's, when this is dropped. + pub(crate) fn return_to(&mut self, reserve: Arc) { + self.returns = Some(reserve); + } + /// Whether dropping this frees pool pages or a ring, rather than returning them to their + /// owner or freeing only client views. + pub(crate) fn frees_backing(&self) -> bool { + self.returns.is_none() && (self.pages.is_some() || self.ring.is_some()) } /// Drops the client views of the backing now. pub(crate) fn drop_aliases(&mut self) { @@ -2163,6 +2179,7 @@ impl Queue { ring: self.graph.vacate_ring(), _kit: None, owner: self.backing_owner.take(), + returns: None, } } /// Binds a reusable physical queue with its own dedicated compute pool as an additional @@ -2367,6 +2384,7 @@ impl Queue { ring, _kit: None, owner: self.backing_owner.take(), + returns: None, }) } /// An idle retained queue whose USC backing may be given back. @@ -2564,6 +2582,7 @@ impl Queue { ring, _kit: None, owner: self.backing_owner.take(), + returns: None, })) } /// Installs fresh backing into a vacant pool; returns the descriptor row data @@ -2602,6 +2621,7 @@ impl Queue { ring: old_ring, _kit: None, owner: self.backing_owner, + returns: None, }); self.backing_owner = Some(owner); Ok((self.pool.descriptor()?, vacated)) @@ -2687,6 +2707,7 @@ impl Queue { ring: None, _kit: None, owner, + returns: None, }) } diff --git a/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs index c0b323b35aec2..bbcc0dace9962 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs @@ -7,10 +7,18 @@ //! owner is bound to it, and gives it back here when the queue is taken from the owner. A //! publication takes from here and never allocates. A fresh queue also takes a [`Kit`] from here. //! +//! The spares are behind their own lock ([`Reserve`]), so backing a queue gives back returns to +//! them off the device mutex, once its client views are gone: the same pages and ring map at the +//! same client addresses again. +//! //! [`Kit`]: super::Kit use crate::g17::freelist::ComputeCapacity; -use kernel::prelude::*; +use kernel::{ + new_mutex, + prelude::*, + sync::{Arc, Mutex, MutexGuard}, +}; /// Spare pages an owner keeps at most: with more, one is covered by another (pages of one family /// are ordered by size, and M5 has two block sizes), and the covered one is freed. @@ -134,6 +142,62 @@ impl Spares { } } +/// The spares of one owner. +pub(crate) type OwnerSpares = Spares; + +impl Reserve { + /// The spares. Taken under the device mutex too; nothing takes the device mutex under it. + pub(crate) fn lock(&self) -> MutexGuard<'_, OwnerSpares> { + self.spares.lock() + } + + /// Keeps pages and a ring a queue gave back, off the device mutex and after their client + /// views are gone ([`super::Vacated`]), and wakes a publication that waits for them. Pages + /// whose tables cannot be written again are freed; the owner's next SUBMIT provisions. + pub(crate) fn give_back( + &self, + pages: Option, + ring: Option, + ) { + // Unreset tables would hand the firmware the old free list. + let pages = pages.and_then(|mut pages| pages.reset().is_ok().then_some(pages)); + let ring = ring.map(|mut ring| { + ring.clear(); + ring + }); + let unused = { + let mut spares = self.lock(); + ( + pages.and_then(|pages| spares.put_pages(pages)), + ring.and_then(|ring| spares.put_ring(ring)), + ) + }; + drop(unused); + self.returned.notify(); + } +} + +/// An owner's spares behind their own lock, shared with the backing its queues give back. +#[pin_data] +pub(crate) struct Reserve { + #[pin] + spares: Mutex, + /// Woken when backing comes back: the device's compute channel waiters. + returned: Arc, +} + +impl Reserve { + pub(crate) fn new(returned: Arc) -> Result> { + Arc::pin_init( + pin_init!(Self { + spares <- new_mutex!(Spares::new(), "g17::compute::Reserve"), + returned, + }), + GFP_KERNEL, + ) + } +} + #[kunit_tests(asahi_g17_compute_reserve)] mod tests { use super::*; diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 7476a8c6187b3..c5d6785ad4404 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -260,14 +260,14 @@ impl Drop for ComputeSlot { pub(super) struct OwnerReserve { owner: u64, context: Arc, - spares: compute::reserve::Spares, + spares: Arc, /// A sibling channel found no backing: the next SUBMIT provisions some, if it can. wants_sibling: bool, } impl OwnerReserve { - pub(super) fn new(owner: u64, context: Arc) -> Self { - Self { owner, context, spares: compute::reserve::Spares::new(), wants_sibling: false } + pub(super) fn new(owner: u64, context: Arc, spares: Arc) -> Self { + Self { owner, context, spares, wants_sibling: false } } } @@ -288,26 +288,16 @@ impl Lacks { } /// Keeps the pages and ring a queue gave back for their owner while it has compute commands -/// ([`Context::compute_claimed`]); what is not kept stays in `vacated`, to be freed with it. An -/// owner without commands is idle: its backing is freed, as before it had a reserve. -fn keep_backing(reserves: &mut KVec>, vacated: &mut compute::Vacated) { +/// ([`Context::compute_claimed`]): they return to its spares when `vacated` is dropped, off the +/// device mutex and after their client views ([`compute::Vacated`]). An owner without commands +/// is idle: its backing is freed, as before it had a reserve. +fn keep_backing(reserves: &KVec>, vacated: &mut compute::Vacated) { let Some(owner) = vacated.returns_to() else { return }; - let Some(reserve) = reserves.iter_mut().find(|reserve| reserve.owner == owner) else { return }; + let Some(reserve) = reserves.iter().find(|reserve| reserve.owner == owner) else { return }; if !reserve.context.compute_claimed() { return; } - let (pages, ring) = vacated.backing(); - if let Some(mut returned) = pages.take() { - // Unreset tables would hand the firmware the old free list. - *pages = match returned.reset() { - Ok(()) => reserve.spares.put_pages(returned), - Err(_) => Some(returned), - }; - } - if let Some(mut returned) = ring.take() { - returned.clear(); - *ring = reserve.spares.put_ring(returned); - } + vacated.return_to(reserve.spares.clone()); } pub(super) struct Registry { @@ -645,24 +635,24 @@ impl Registry { self.reserves.iter_mut().find(|reserve| reserve.owner == owner).map(|reserve| &mut **reserve) } - fn spares(&self, owner: u64) -> Option<&compute::reserve::Spares> { - self.reserves.iter().find(|reserve| reserve.owner == owner).map(|reserve| &reserve.spares) + /// `owner`'s spares, under their own lock (inside the device mutex). + fn spares(&self, owner: u64) -> Option> { + self.reserves.iter().find(|reserve| reserve.owner == owner).map(|reserve| reserve.spares.lock()) } /// What a publication of `owner` at `required` would lack: its spares, and the backing its /// queues hold (also while they give it back), serve it otherwise. pub(super) fn compute_lacks(&self, owner: u64, required: super::freelist::ComputeCapacity) -> Lacks { - let spares = self.spares(owner); + let (spare_pages, spare_ring, spare_kit) = self.spares(owner).map_or((false, false, false), + |spares| (spares.fits(required), spares.has_ring(), spares.has_kit())); let queues = || self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()); let held = || queues().filter(|queue| queue.backing_owner() == Some(owner)); - let pages = !spares.is_some_and(|spares| spares.fits(required)) - && !held().any(|queue| queue.backing_fits(required)); - let ring = !spares.is_some_and(|spares| spares.has_ring()) && !held().any(|queue| queue.has_ring()); + let pages = !spare_pages && !held().any(|queue| queue.backing_fits(required)); + let ring = !spare_ring && !held().any(|queue| queue.has_ring()); // A kit for an owner without a queue of its own: a QID that frees up later is built on // without allocating. One with a queue gets a channel through an existing queue, which // stays until processor stop. - let kit = !spares.is_some_and(|spares| spares.has_kit()) + let kit = !spare_kit && !queues().any(|queue| queue.backing_owner() == Some(owner) || queue.owner() == Some(owner)); let sibling = self.reserves.iter().any(|reserve| reserve.owner == owner && reserve.wants_sibling); Lacks { pages, ring, kit, sibling } @@ -689,9 +679,11 @@ impl Registry { return (compute::Vacated::spares(pages, ring, kit), reserve); }; target.wants_sibling = false; - let pages = pages.and_then(|pages| target.spares.put_pages(pages)); - let ring = ring.and_then(|ring| target.spares.put_ring(ring)); - let kit = kit.and_then(|kit| target.spares.put_kit(kit)); + let mut spares = target.spares.lock(); + let pages = pages.and_then(|pages| spares.put_pages(pages)); + let ring = ring.and_then(|ring| spares.put_ring(ring)); + let kit = kit.and_then(|kit| spares.put_kit(kit)); + drop(spares); (compute::Vacated::spares(pages, ring, kit), reserve) } @@ -699,7 +691,7 @@ impl Registry { /// both or neither. fn take_set(&mut self, owner: u64, required: super::freelist::ComputeCapacity) -> Option<(super::freelist::Pages, compute::DescriptorRing)> { - let spares = &mut self.owner_reserve(owner)?.spares; + let mut spares = self.spares(owner)?; if !spares.fits(required) || !spares.has_ring() { return None; } @@ -721,13 +713,13 @@ impl Registry { if !self.can_build_fresh(owner, required) { return None; } - let spares = &mut self.owner_reserve(owner)?.spares; + let mut spares = self.spares(owner)?; Some((spares.take_kit()?, spares.take_pages(required)?, spares.take_ring()?)) } fn take_pages(&mut self, owner: u64, required: super::freelist::ComputeCapacity) -> Option { - self.owner_reserve(owner)?.spares.take_pages(required) + self.spares(owner)?.take_pages(required) } /// Gives `owner` back what one of its publications took and did not use. Returns what is @@ -739,11 +731,11 @@ impl Registry { ring: Option, kit: Option, ) -> compute::Vacated { - match self.owner_reserve(owner) { - Some(reserve) => compute::Vacated::spares( - pages.and_then(|pages| reserve.spares.put_pages(pages)), - ring.and_then(|ring| reserve.spares.put_ring(ring)), - kit.and_then(|kit| reserve.spares.put_kit(kit)), + match self.spares(owner) { + Some(mut spares) => compute::Vacated::spares( + pages.and_then(|pages| spares.put_pages(pages)), + ring.and_then(|ring| spares.put_ring(ring)), + kit.and_then(|kit| spares.put_kit(kit)), ), None => compute::Vacated::spares(pages, ring, kit), } @@ -758,7 +750,7 @@ impl Registry { /// Keeps what a queue gave back for its owner ([`keep_backing`]). fn keep_returned(&mut self, vacated: &mut compute::Vacated) { - keep_backing(&mut self.reserves, vacated); + keep_backing(&self.reserves, vacated); } /// Asks the idle queues holding `owner`'s backing that serves `required` to give it back: a @@ -789,9 +781,10 @@ impl Registry { /// The spares of owners without compute commands go to `deferred`, to be freed: an idle /// owner's next SUBMIT provisions again. fn trim_reserves(&mut self, deferred: &mut DeferredBatch) { - for reserve in self.reserves.iter_mut().filter(|reserve| !reserve.context.compute_claimed()) { + for reserve in self.reserves.iter().filter(|reserve| !reserve.context.compute_claimed()) { + let mut spares = reserve.spares.lock(); while deferred.vacated_room() { - let Some((pages, ring, kit)) = reserve.spares.take_any() else { break }; + let Some((pages, ring, kit)) = spares.take_any() else { break }; deferred.defer_vacated(compute::Vacated::spares(pages, ring, kit)); } } @@ -1334,7 +1327,7 @@ impl Registry { { if !deferred.vacated_room() { break; } if let Some(mut vacated) = queue.observe_vacancy(consumer, producer)? { - keep_backing(&mut self.reserves, &mut vacated); + keep_backing(&self.reserves, &mut vacated); deferred.defer_vacated(vacated); freed += 1; } @@ -3666,9 +3659,12 @@ impl Backend { let client = self.context.vm().memory_client(); let charged = super::object::Allocator { dev: &dev, uat: &uat, client }; let device = super::object::Allocator { dev: &dev, uat: &uat, client: None }; - let reserve = (!reserved) - .then(|| KBox::new(OwnerReserve::new(self.owner, self.context.clone()), GFP_KERNEL)) - .transpose()?; + let reserve = if reserved { + None + } else { + let spares = compute::reserve::Reserve::new(self.shared.channels.clone())?; + Some(KBox::new(OwnerReserve::new(self.owner, self.context.clone(), spares), GFP_KERNEL)?) + }; let mut pages = lacks.pages .then(|| super::freelist::Pages::for_compute(&charged, required, client)).transpose()?; let mut ring = lacks.ring @@ -5000,7 +4996,7 @@ impl super::Firmware { queue.recycle_quarantined_idle()?; if deferred.vacated_room() { if let Some(mut vacated) = queue.take_recycled_ring() { - keep_backing(&mut self.queues.reserves, &mut vacated); + keep_backing(&self.queues.reserves, &mut vacated); deferred.defer_vacated(vacated); freed = true; } diff --git a/tools/asahi/g17-compute-reserve-tests.py b/tools/asahi/g17-compute-reserve-tests.py index 4a952b39053d5..b9626c6a16bca 100644 --- a/tools/asahi/g17-compute-reserve-tests.py +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -21,14 +21,15 @@ `finish_uninstalled_compute`) allocate no device memory; - every place a queue gives backing back keeps it for its owner; close and the pool pass free spares; another open owner's backing is never bound; -- compiled: the production `keep_backing`, `stock` and `trim_reserves` with the - production spare bookkeeping keep a claimed owner's backing, free an idle or - unknown owner's, and free every spare exactly once. +- compiled: the production `keep_backing`, `Reserve::give_back`, `Vacated`'s drop, + `stock` and `trim_reserves` with the production spare bookkeeping keep a claimed + owner's backing, return it only once its client views are gone, free an idle or + unknown owner's and pages whose tables cannot be reset, and free every spare + exactly once. --mutation allocating-bind / allocating-graph / publication-allocates / claim-after-provision / free-returned / bind-other-owner / kit-needs-qid / -keep-idle inject a -fault and must be caught. +keep-idle / return-before-unmap inject a fault and must be caught. """ import os import subprocess @@ -87,7 +88,7 @@ def sources(mutation): ' }\n let claim = claim.map(|()| super::context::ComputeClaim::new(&self.context));', 1) elif mutation == 'free-returned': files['runtime.rs'] = files['runtime.rs'].replace( - ' keep_backing(&mut self.reserves, &mut vacated);\n', '', 1) + ' keep_backing(&self.reserves, &mut vacated);\n', '', 1) elif mutation == 'bind-other-owner': files['runtime.rs'] = files['runtime.rs'].replace( ' if !queue.pool_fits(required) || !queue.pool_serves(context.vm())\n' @@ -96,6 +97,9 @@ def sources(mutation): elif mutation == 'kit-needs-qid': files['runtime.rs'] = files['runtime.rs'].replace( '|| queue.owner() == Some(owner));', '|| queue.owner() == Some(owner))\n && self.compute_qid_fits();', 1) + elif mutation == 'return-before-unmap': + files['queue/compute.rs'] = files['queue/compute.rs'].replace( + ' self.drop_aliases();\n reserve.give_back(', ' reserve.give_back(', 1) elif mutation == 'keep-idle': files['runtime.rs'] = files['runtime.rs'].replace( ' if !reserve.context.compute_claimed() {\n return;\n }\n', '', 1) @@ -159,8 +163,11 @@ def structure(files): 'the claim precedes the SUBMIT provision, and the command is queued after it': ordered( item(files['queue/mod.rs'], ' fn enqueue('), 'super::context::ComputeClaim::new(&self.context)', 'self.ensure_compute(command)?;', 'Packet::new(', 'claim,', '.enqueue(packet'), - 'given-back pools go to their owner': 'keep_backing(&mut self.reserves, &mut vacated);' in item(runtime, 'pub(super) fn observe_pool_releases('), - 'recycled rings go to their owner': 'keep_backing(&mut self.queues.reserves, &mut vacated);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), + 'given-back pools go to their owner': 'keep_backing(&self.reserves, &mut vacated);' in item(runtime, 'pub(super) fn observe_pool_releases('), + 'recycled rings go to their owner': 'keep_backing(&self.queues.reserves, &mut vacated);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), + # Resetting may allocate, and the pages may still be mapped where they map again. + 'returned backing goes back off the device mutex': 'return_to(' in item(runtime, 'fn keep_backing(') + and not re.search(r'reset\(|put_pages\(|put_ring\(', item(runtime, 'fn keep_backing(')), 'the pool pass frees idle owners\' spares': 'self.queues.trim_reserves(deferred);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), 'growth keeps the smaller pages': 'firmware.queues.keep_returned(&mut old);' in item(runtime, ' fn grow_compute('), 'a never-published queue gives its backing back': ordered(item(runtime, ' fn finish_uninstalled_compute('), @@ -184,7 +191,8 @@ def compiled(files): """Runs the production give-back, stock and trim with the production spare bookkeeping.""" runtime = files['runtime.rs'] reserve = files['queue/compute/reserve.rs'] - spares = reserve[reserve.index('const PAGES'):reserve.index('#[kunit_tests')] + spares = reserve[reserve.index('const PAGES'):reserve.index('/// An owner\'s spares behind their own lock')] + vacated_drop = item(files['queue/compute.rs'], 'impl Drop for Vacated {') owner = item(runtime, 'pub(super) struct OwnerReserve {') + '\n' + item(runtime, 'impl OwnerReserve {') methods = '\n'.join(item(runtime, sig) for sig in [' fn owner_reserve(', ' pub(super) fn stock(', ' fn trim_reserves(']) @@ -192,22 +200,41 @@ def compiled(files): replace = lambda text: (text.replace('pub(super) ', '').replace('super::freelist::Pages', 'Pages') .replace('compute::reserve::Spares', 'Spares').replace('compute::DescriptorRing', 'Ring') .replace('compute::Kit', 'Kit').replace('compute::Vacated', 'Vacated') + .replace('compute::reserve::Reserve', 'Reserve').replace('crate::g17::freelist::Pages', 'Pages') + .replace('super::DescriptorRing', 'Ring').replace('super::Kit', 'Kit') .replace('crate::g17::pairs::COMPUTE_CHANNELS_MAX', '3') .replace('self.reserves.push_within_capacity(new)', 'push_within(&mut self.reserves, new)')) source = r''' #![allow(dead_code)] -use std::sync::{Arc, atomic::{AtomicUsize, AtomicU32, Ordering}}; +use std::sync::{Arc, MutexGuard, atomic::{AtomicBool, AtomicUsize, AtomicU32, Ordering}}; type KVec = Vec; type KBox = Box; type Result = std::result::Result; #[derive(Clone, Copy)] enum ComputeCapacity { Blocks(usize) } static MADE: AtomicUsize = AtomicUsize::new(0); static FREED: AtomicUsize = AtomicUsize::new(0); +static ALIASES: AtomicUsize = AtomicUsize::new(0); +static RESET_FAILS: AtomicBool = AtomicBool::new(false); +static NOTIFIED: AtomicUsize = AtomicUsize::new(0); struct Pages(usize, bool); impl Pages { fn new(blocks: usize) -> Self { MADE.fetch_add(1, Ordering::SeqCst); Self(blocks, false) } - fn reset(&mut self) -> Result { self.1 = true; Ok(()) } + fn reset(&mut self) -> Result { + assert_eq!(ALIASES.load(Ordering::SeqCst), 0, "returned backing must lose its client views before reuse"); + if RESET_FAILS.load(Ordering::SeqCst) { return Err(-12); } + self.1 = true; Ok(()) + } } +/// A client view of returned backing. +struct Alias; +impl Alias { fn new() -> Self { ALIASES.fetch_add(1, Ordering::SeqCst); Self } } +impl Drop for Alias { fn drop(&mut self) { ALIASES.fetch_sub(1, Ordering::SeqCst); } } +struct Mutex(std::sync::Mutex); +impl Mutex { fn lock(&self) -> MutexGuard<'_, T> { self.0.lock().unwrap() } } +struct Availability; +impl Availability { fn notify(&self) { NOTIFIED.fetch_add(1, Ordering::SeqCst); } } +struct Reserve { spares: Mutex, returned: Arc } +fn reserve() -> Arc { Arc::new(Reserve { spares: Mutex(std::sync::Mutex::new(Spares::new())), returned: Arc::new(Availability) }) } impl Drop for Pages { fn drop(&mut self) { FREED.fetch_add(1, Ordering::SeqCst); } } struct Ring(bool); impl Ring { @@ -230,11 +257,15 @@ def compiled(files): struct Context(AtomicU32); impl Context { fn compute_claimed(&self) -> bool { self.0.load(Ordering::SeqCst) != 0 } } /// What a queue gives back. -struct Vacated { pages: Option, ring: Option, kit: Option, owner: Option } +struct Vacated { _alias: Option, pages: Option, ring: Option, kit: Option, + owner: Option, returns: Option> } impl Vacated { - fn spares(pages: Option, ring: Option, kit: Option) -> Self { Self { pages, ring, kit, owner: None } } + fn spares(pages: Option, ring: Option, kit: Option) -> Self { + Self { _alias: None, pages, ring, kit, owner: None, returns: None } + } fn returns_to(&self) -> Option { self.owner } - fn backing(&mut self) -> (&mut Option, &mut Option) { (&mut self.pages, &mut self.ring) } + fn return_to(&mut self, reserve: Arc) { self.returns = Some(reserve); } + fn drop_aliases(&mut self) { drop(self._alias.take()); } } struct DeferredBatch { vacated: Vec, room: usize } impl DeferredBatch { @@ -242,31 +273,37 @@ def compiled(files): fn defer_vacated(&mut self, vacated: Vacated) { self.vacated.push(vacated) } } struct Registry { reserves: KVec> } -''' + replace(owner) + '\n' + replace(keep) + '\nimpl Registry {\n' + replace(methods) + r''' +''' + replace(owner) + '\n' + replace(keep) + '\n' + vacated_drop + '\nimpl Registry {\n' + replace(methods) + r''' } fn back(owner: u64, blocks: usize) -> Vacated { - Vacated { pages: Some(Pages::new(blocks)), ring: Some(Ring::new()), kit: None, owner: Some(owner) } + Vacated { _alias: Some(Alias::new()), pages: Some(Pages::new(blocks)), ring: Some(Ring::new()), kit: None, + owner: Some(owner), returns: None } } fn main() { let a = Arc::new(Context(AtomicU32::new(1))); let b = Arc::new(Context(AtomicU32::new(1))); let mut registry = Registry { reserves: Vec::with_capacity(2) }; // SUBMIT stocks a new owner: its reserve and its first set. - let (unused, rest) = registry.stock(1, Some(Box::new(OwnerReserve::new(1, a.clone()))), + let (unused, rest) = registry.stock(1, Some(Box::new(OwnerReserve::new(1, a.clone(), reserve()))), Some(Pages::new(21)), Some(Ring::new()), Some(Kit::new())); assert!(rest.is_none() && unused.pages.is_none() && unused.ring.is_none() && unused.kit.is_none()); drop(unused); - let (unused, _) = registry.stock(2, Some(Box::new(OwnerReserve::new(2, b.clone()))), Some(Pages::new(21)), None, None); + let (unused, _) = registry.stock(2, Some(Box::new(OwnerReserve::new(2, b.clone(), reserve()))), Some(Pages::new(21)), None, None); drop(unused); assert_eq!(FREED.load(Ordering::SeqCst), 0, "stocking frees nothing"); - // A queue gives owner 1's backing back while it has commands: kept, reset, cleared. + // A queue gives owner 1's backing back while it has commands: kept, reset, cleared, and + // only once it is dropped, off the device mutex, after its client view. let mut returned = back(1, 30); - keep_backing(&mut registry.reserves, &mut returned); - assert!(returned.pages.is_none() && returned.ring.is_none(), "a claimed owner's backing must be kept"); + keep_backing(®istry.reserves, &mut returned); + assert!(returned.returns.is_some(), "a claimed owner's backing must be kept"); + assert!(!registry.owner_reserve(1).unwrap().spares.lock().fits(ComputeCapacity::Blocks(30)), + "backing must not return while its client view is mapped"); + let notified = NOTIFIED.load(Ordering::SeqCst); drop(returned); assert_eq!(FREED.load(Ordering::SeqCst), 0); + assert_eq!(NOTIFIED.load(Ordering::SeqCst), notified + 1, "a returned set wakes its waiters"); { - let spares = &mut registry.owner_reserve(1).unwrap().spares; + let mut spares = registry.owner_reserve(1).unwrap().spares.lock(); let pages = spares.take_pages(ComputeCapacity::Blocks(30)).unwrap(); assert!(pages.1, "kept pages are reset"); let (first, second) = (spares.take_ring().unwrap(), spares.take_ring().unwrap()); @@ -276,25 +313,34 @@ def compiled(files): // Owner 2 has no commands: what comes back is freed, as is an unknown owner's. b.0.store(0, Ordering::SeqCst); let mut idle = back(2, 30); - keep_backing(&mut registry.reserves, &mut idle); - assert!(idle.pages.is_some() && idle.ring.is_some(), "an idle owner's backing must be freed"); + keep_backing(®istry.reserves, &mut idle); + assert!(idle.returns.is_none(), "an idle owner's backing must be freed"); drop(idle); let mut unknown = back(9, 21); - keep_backing(&mut registry.reserves, &mut unknown); - assert!(unknown.pages.is_some()); + keep_backing(®istry.reserves, &mut unknown); + assert!(unknown.returns.is_none()); drop(unknown); + // Pages whose tables cannot be written again are freed, never kept stale. + let before = FREED.load(Ordering::SeqCst); + RESET_FAILS.store(true, Ordering::SeqCst); + let mut stale = back(1, 40); + keep_backing(®istry.reserves, &mut stale); + drop(stale); + RESET_FAILS.store(false, Ordering::SeqCst); + assert_eq!(FREED.load(Ordering::SeqCst), before + 1, "unreset pages must be freed"); + assert!(!registry.owner_reserve(1).unwrap().spares.lock().fits(ComputeCapacity::Blocks(40))); // The pool pass frees an idle owner's spares and keeps a claimed owner's. let mut deferred = DeferredBatch { vacated: Vec::new(), room: 8 }; registry.trim_reserves(&mut deferred); - assert!(registry.owner_reserve(2).unwrap().spares.is_empty(), "the pool pass must free idle spares"); - assert!(!registry.owner_reserve(1).unwrap().spares.is_empty(), "a claimed owner keeps its spares"); + assert!(registry.owner_reserve(2).unwrap().spares.lock().is_empty(), "the pool pass must free idle spares"); + assert!(!registry.owner_reserve(1).unwrap().spares.lock().is_empty(), "a claimed owner keeps its spares"); drop(deferred); // Close: owner 1 exits with its reserve unused; everything was freed exactly once. let index = registry.reserves.iter().position(|reserve| reserve.owner == 1).unwrap(); drop(registry.reserves.swap_remove(index)); drop(registry); assert_eq!(MADE.load(Ordering::SeqCst), FREED.load(Ordering::SeqCst), "every spare is freed exactly once"); - println!("PASS compute reserve: SUBMIT stocks, a claimed owner keeps what its queues give back (reset), an idle or unknown owner's backing and idle spares are freed, and close frees the rest, each once"); + println!("PASS compute reserve: SUBMIT stocks, a claimed owner keeps what its queues give back (reset, after its client views, with a wake), an idle or unknown owner's backing, unresettable pages and idle spares are freed, and close frees the rest, each once"); } ''' with tempfile.TemporaryDirectory(prefix='g17-compute-reserve-') as tmp: @@ -334,7 +380,7 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument('--mutation', choices=['allocating-bind', 'allocating-graph', 'publication-allocates', 'claim-after-provision', 'free-returned', 'bind-other-owner', - 'kit-needs-qid', 'keep-idle']) + 'kit-needs-qid', 'keep-idle', 'return-before-unmap']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: diff --git a/tools/asahi/g17-growth-tests.py b/tools/asahi/g17-growth-tests.py index 807277e1dab02..79089400967f9 100644 --- a/tools/asahi/g17-growth-tests.py +++ b/tools/asahi/g17-growth-tests.py @@ -93,9 +93,9 @@ def fixture(): enum ControlRecord {FreeListRelease(u64)} struct Rings; impl Rings {fn publish_control(_:&initdata::InitData,_:&ControlRecord)->Result{Ok(3)}} -struct Vacated {_alias:Option,pages:Option,_descriptors:Option,ring:Option,_kit:Option<()>,owner:Option} +struct Vacated {_alias:Option,pages:Option,_descriptors:Option,ring:Option,_kit:Option<()>,owner:Option,returns:Option<()>} // The owners' spare backing: what a queue gives back stays its owner's while it has commands. -fn keep_backing(_:&mut (),_:&mut Vacated){} +fn keep_backing(_:&(),_:&mut Vacated){} impl Graph {fn vacate_ring(&mut self)->Option{Some(1)}} ''' + '#[derive(Clone, Copy)]\n' + item(source, 'pub(crate) struct Growth') + r''' impl Queue { diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index 30f37597c5a09..5308731aa0173 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -289,7 +289,7 @@ def build(mutation=None): pub struct PoolDescriptor(u32); pub struct InitData { control_cursor: std::cell::Cell } pub struct KernelMapping; -pub struct Vacated { _alias: Option, pages: Option, _descriptors: Option, ring: Option, _kit: Option<()>, owner: Option } +pub struct Vacated { _alias: Option, pages: Option, _descriptors: Option, ring: Option, _kit: Option<()>, owner: Option, returns: Option<()> } pub struct FreeListRelease; enum ControlRecord { FreeListRelease(FreeListRelease) } struct Rings; diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index badf35277ab55..6d40ff748fc68 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -506,7 +506,7 @@ def mutations(flag, names, base, expect=KILL): 'g17-compute-reserve-tests.py': [([], PASS)] + mutations( '--mutation', ['allocating-bind', 'allocating-graph', 'publication-allocates', 'claim-after-provision', 'free-returned', 'bind-other-owner', 'kit-needs-qid', - 'keep-idle'], []), + 'keep-idle', 'return-before-unmap'], []), 'g17-compute-owed-stamp-tests.py': [([], PASS)] + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', From 5adab0a2d35b0b5caf36ca9feda581fa542f0875 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:13:45 -0300 Subject: [PATCH 07/13] drm/asahi: g17: keep an owner's set when re-arming its queue fails rearm_vacant() took the owner's pages and ring from its spares and moved them into rearm_compute(). When that failed (EAGAIN because the queue was taken, or the pool refused the pages) the set was dropped there, under the device mutex, and never went back: the retry then found no spares and waited out its admission. Queue::rearm() also swapped the new ring in before the pool took the pages, so on failure it dropped the new ring under the device mutex or, with no old ring to swap back, left it installed in the graph. And when install_compute_pool() or bind_rearmed() failed, the Vacated holding the old ring and its client view dropped before the device guard. ComputePool::rearm(), Queue::rearm() and rearm_compute() now take the pages and ring by &mut Option and consume them only on success, with the queue unchanged on failure; rearm_vacant() puts a set it could not use back to its owner and frees what the owner does not keep after the device guard, and drops the Vacated after the guard on every path. A re-armed queue that then fails to install or bind keeps the set, tagged for its owner to recall. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/freelist.rs | 7 ++--- drivers/gpu/drm/asahi/g17/queue/compute.rs | 21 +++++++-------- drivers/gpu/drm/asahi/g17/runtime.rs | 30 ++++++++++++++-------- tools/asahi/g17-m5-sibling-rearm-tests.py | 10 +++++--- 4 files changed, 39 insertions(+), 29 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index 541885a34e5df..3d8660b27b07f 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -1237,12 +1237,13 @@ impl ComputePool { /// rewrites the page-pool descriptor row before the queue is kicked again. /// As render repopulation does, the firmware-completed counter is carried /// over so it stays consistent with the host submitted counter in `state`. - pub(crate) fn rearm(&mut self, pages: Pages) -> Result { + /// Takes `pages` only once they are written in: on failure they stay with the caller. + pub(crate) fn rearm(&mut self, pages: &mut Option) -> Result { if self.pages.is_some() { return Err(EBUSY); } - self.write_pages(&pages)?; - self.pages = Some(pages); + self.write_pages(pages.as_ref().ok_or(EINVAL)?)?; + self.pages = pages.take(); Ok(()) } /// Preserve both sets of pages on failure. The caller owns the consumed diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index f281c813a4410..0806ebe2416f9 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -2588,29 +2588,26 @@ impl Queue { /// Installs fresh backing into a vacant pool; returns the descriptor row data /// the caller writes before binding an owner, plus any previous sibling descriptor /// ring to drop off-lock. + /// Takes `pages` and `ring` only on success: on failure the queue is unchanged and both stay + /// with the caller, to go back to their owner. pub(crate) fn rearm( &mut self, owner: u64, - pages: crate::g17::freelist::Pages, - ring: DescriptorRing, + pages: &mut Option, + ring: &mut Option, ) -> Result<(PoolDescriptor, Option)> { if !self.can_rearm() { return Err(EAGAIN); } + if ring.is_none() { + return Err(EINVAL); + } + self.pool.rearm(pages)?; let descriptors = self .binding .as_mut() .and_then(|binding| binding.descriptors.take()); - let old_ring = self.graph.rearm_ring(ring); - if let Err(error) = self.pool.rearm(pages) { - if let Some(old) = old_ring { - let _ = self.graph.rearm_ring(old); - } - if let (Some(binding), Some(descriptors)) = (self.binding.as_mut(), descriptors) { - binding.descriptors = Some(descriptors); - } - return Err(error); - } + let old_ring = self.graph.rearm_ring(ring.take().ok_or(EINVAL)?); self.pool_phase = PoolPhase::Populated; self.release_sent_ns = None; self.needs_fresh_backing = false; diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index c5d6785ad4404..a300adac07883 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1171,13 +1171,14 @@ impl Registry { } /// Installs fresh USC backing into the vacant queue `qid`; the caller writes - /// the returned descriptor row before binding. EAGAIN if the queue was taken. + /// the returned descriptor row before binding. EAGAIN if the queue was taken. Takes `pages` + /// and `ring` only on success. pub(super) fn rearm_compute( &mut self, qid: u8, owner: u64, - pages: crate::g17::freelist::Pages, - ring: compute::DescriptorRing, + pages: &mut Option, + ring: &mut Option, ) -> Result<(super::freelist::PoolDescriptor, Option)> { let mut queue = self .compute @@ -2196,9 +2197,17 @@ impl Backend { } return Ok(None); }; - let (descriptor, mut vacated) = match firmware.queues.rearm_compute(qid, self.owner, pages, ring) { - Err(error) if error == EAGAIN => return Ok(Some(false)), - result => result?, + let (mut pages, mut ring) = (Some(pages), Some(ring)); + let (descriptor, mut vacated) = match firmware.queues.rearm_compute(qid, self.owner, &mut pages, &mut ring) { + Ok(rearmed) => rearmed, + Err(error) => { + // The set goes back to its owner for the retry; what it does not keep is + // freed after the device guard. + let unused = firmware.queues.put_back(self.owner, pages, ring, None); + drop(state); + drop(unused); + return if error == EAGAIN { Ok(Some(false)) } else { Err(error) }; + } }; // A ring the queue still held goes back to its owner; the rest is dropped after the // device guard. @@ -2206,12 +2215,13 @@ impl Backend { firmware.queues.keep_returned(vacated); } // The firmware consumed this slot's release before the backing - // was dropped; the row is rewritten before the queue is kicked. - firmware.init.install_compute_pool(descriptor)?; - firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?; + // was dropped; the row is rewritten before the queue is kicked. Should either fail, + // the queue keeps the owner's set, tagged for it to recall. + let bound = firmware.init.install_compute_pool(descriptor) + .and_then(|()| firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)); drop(state); drop(vacated); - Ok(Some(true)) + bound.map(|()| Some(true)) } fn build_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index 5308731aa0173..d828144fbbd01 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -226,8 +226,9 @@ def build(mutation=None): '&& (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' ' == Some(channel_index));', 'firmware.queues.take_set(self.owner, required)', - 'firmware.queues.rearm_compute(qid, self.owner, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', - 'firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?;'), + 'firmware.queues.rearm_compute(qid, self.owner, &mut pages, &mut ring)', + 'firmware.queues.put_back(self.owner, pages, ring, None)', 'firmware.init.install_compute_pool(descriptor)', + 'firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)'), 'the primary re-arms channel 0': 'self.rearm_vacant(qid, 0, required,' in build_compute, 'the primary gives back other VMs\' queues through the same helper': ordered_ok( rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant()\n && (!queue.pool_serves(vm) || !queue.backing_free_for(owner)))', @@ -247,6 +248,7 @@ def build(mutation=None): const EIO: i32 = -5; const EAGAIN: i32 = -11; const EBUSY: i32 = -16; +const EINVAL: i32 = -22; const EPERM: i32 = -1; const ENOSPC: i32 = -28; type Result = std::result::Result; @@ -318,7 +320,7 @@ def build(mutation=None): impl Pool { @@POOL@@ fn fits_capacity(&self, required: ComputeCapacity) -> bool { self.pages.is_some() && self.cap >= required.0 } - fn rearm(&mut self, pages: Pages) -> Result { if self.pages.is_some() { return Err(EBUSY); } self.pages = Some(pages); Ok(()) } + fn rearm(&mut self, pages: &mut Option) -> Result { if self.pages.is_some() { return Err(EBUSY); } self.pages = Some(pages.take().ok_or(EINVAL)?); Ok(()) } fn descriptor(&self) -> Result { Ok(PoolDescriptor(u32::from(self.id))) } fn release_record(&self, _generation: u64) -> FreeListRelease { FreeListRelease } } @@ -460,7 +462,7 @@ def build(mutation=None): reg.release_rearm(qid, owner); return Ok(false); } - let (descriptor, _vacated) = reg.rearm_compute(qid, owner, Pages(2), DescriptorRing)?; + let (descriptor, _vacated) = reg.rearm_compute(qid, owner, &mut Some(Pages(2)), &mut Some(DescriptorRing))?; assert_eq!(descriptor, PoolDescriptor(u32::from(qid)), "the re-armed queue's row is written"); reg.bind_rearmed(qid, owner, context, channel_index)?; Ok(true) From 57b26c262717ebb611e6264e074e3646f43a8920 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:15:55 -0300 Subject: [PATCH 08/13] drm/asahi: g17: reclaim idle pools for a compute SUBMIT short of lower range Moving a compute queue's backing allocation from publication into SUBMIT (provision_backing()) dropped what #4512 gave that allocation: when the lower range is short (ENOSPC), give idle pools back (reclaim_capacity() with reclaim_backing) and retry once the firmware consumed their releases. A SUBMIT failed instead while warm idle compute and render pools held the range, on multi-cluster G17 parts most of all. provision_backing() now retries its allocation (try_provision_backing()) after the same wait_channels(.., reclaim_backing = true, min_span) a publication used, for at most PROVISION_RECLAIM_NS (1 s) and interruptibly, before failing with ENOSPC. It also allocates under a preparation lease, as provision_shared() does, so stop_queues() waits for it, and stocks only for the firmware it allocated for: after a recovery it provisions again, and the stale allocation is dropped off the device mutex. Two related fixes: - reclaim_capacity() and reclaim_render_capacity() counted every vacated entry as freed backing, so backing that goes back to its owner, or a vacated entry holding client views only, ended a capacity wait at once as if lower range had been freed. Only entries whose dropping frees pages or a ring count now. - A re-arm whose owner had no spare set returned to wait, recalling nothing: with the owner's ring on an idle queue whose pages are too small (recall_backing() asked only queues whose pages fit), it waited out its admission. rearm_vacant() now recalls the owner's backing, including a ring held with smaller pages while the owner has no spare ring. g17-compute-reserve-tests checks the SUBMIT reclaim, the lease, the progress count and the recall, with a submit-no-reclaim mutation. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/runtime.rs | 73 +++++++++++++++---- .../drm/asahi/g17/runtime/render/submit.rs | 5 +- .../g17-compute-growth-deadline-tests.py | 2 +- tools/asahi/g17-compute-reserve-tests.py | 21 +++++- tools/asahi/g17-queue-object-charge-tests.py | 6 +- tools/asahi/run-host-tests.py | 2 +- 6 files changed, 86 insertions(+), 23 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index a300adac07883..204ca92f5a38a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -33,6 +33,10 @@ use kernel::{prelude::*, sync::Arc}; const QIDS: usize = 128; const FIRST_COMPUTE_QID: u8 = 4; const WORK_RING_WAIT_NS: u64 = super::job::TIMEOUT_MS as u64 * 1_000_000; +/// Bound for a compute SUBMIT whose backing found the lower range short: idle pools are given +/// back, and the firmware consumes their releases, well within it; then the SUBMIT fails with +/// ENOSPC. +const PROVISION_RECLAIM_NS: u64 = 1_000_000_000; /// Pending admission keeps exactly retired compute backing available for reuse. /// The guard spans retries and disappears on publication, cancellation or error. @@ -753,14 +757,17 @@ impl Registry { keep_backing(&self.reserves, vacated); } - /// Asks the idle queues holding `owner`'s backing that serves `required` to give it back: a - /// pool pass releases them, and the owner keeps the backing. Whether any does. - fn recall_backing(&mut self, owner: u64, required: super::freelist::ComputeCapacity) -> bool { + /// Asks the idle queues holding `owner`'s backing that serves `required` to give it back, + /// and with `ring`, while the owner has no spare ring, any that holds one of its rings, + /// smaller pages too: a pool pass releases them, and the owner keeps the backing. Whether + /// any does. + fn recall_backing(&mut self, owner: u64, required: super::freelist::ComputeCapacity, ring: bool) -> bool { + let ring = ring && !self.spares(owner).is_some_and(|spares| spares.has_ring()); let mut recalled = false; for mut queue in self.compute.iter_mut().flatten() .filter_map(|entry| entry.queue.as_deref_mut()) .filter(|queue| queue.backing_owner() == Some(owner) && queue.reusable() - && !queue.pool_vacant() && queue.backing_fits(required)) + && !queue.pool_vacant() && (queue.backing_fits(required) || (ring && queue.has_ring()))) { queue.require_fresh_backing(); recalled = true; @@ -2087,7 +2094,7 @@ impl Backend { pages = firmware.queues.take_pages(self.owner, required); if pages.is_none() { // An idle queue holds them: the next pool pass gives them back. - firmware.queues.recall_backing(self.owner, required); + firmware.queues.recall_backing(self.owner, required, false); return Err(EAGAIN); } } @@ -2194,6 +2201,10 @@ impl Backend { let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else { if channel_index != 0 { firmware.queues.want_sibling(self.owner); + } else { + // Its set may sit on an idle queue, its ring on one with smaller pages: there it + // would wait out the admission. + firmware.queues.recall_backing(self.owner, required, true); } return Ok(None); }; @@ -3654,7 +3665,34 @@ impl Backend { /// queues hold some ([`Registry::compute_lacks`]): pool pages and a descriptor ring charged /// to its client, and for an owner without a queue of its own a kit of device memory. A /// sibling channel that found none gets a set too, if it can be allocated. + /// + /// Short of lower range (ENOSPC), it gives idle pools back as a publication's capacity + /// wait does and tries again, for at most [`PROVISION_RECLAIM_NS`]; a recovery that + /// replaced the firmware meanwhile provisions again for the new one. fn provision_backing(&self, required: super::freelist::ComputeCapacity) -> Result { + let check = || if kernel::current!().signal_pending() { Err(ERESTARTSYS) } else { Ok(()) }; + let admission = Admission::new(now_ns().saturating_add(PROVISION_RECLAIM_NS), &check); + let min_span = self.compute_lower_span(required); + loop { + // Sampled before this attempt's allocation. + let observed = self.shared.channels.observe(); + let error = match self.try_provision_backing(required) { + Err(error) if error == ENOSPC || error == EAGAIN => error, + result => return result, + }; + if error == ENOSPC { + match self.wait_channels(observed, &admission, true, min_span) { + Err(error) if error == EBUSY => return Err(ENOSPC), + Err(error) if error != EAGAIN => return Err(error), + _ => {} + } + } + } + } + + fn try_provision_backing(&self, required: super::freelist::ComputeCapacity) -> Result { + // Recovery joins this lease before replacing the firmware or tearing down its roots. + let lease = self.shared.preparations.enter(true)?; let (uat, objects, lacks, reserved) = { let state = self.shared.state.lock(); let firmware = state.as_deref().ok_or(ENODEV)?; @@ -3690,17 +3728,25 @@ impl Backend { kit = kit.or_else(|| new_kit().ok()); } let mut state = self.shared.state.lock(); - let firmware = state.as_deref_mut().ok_or(ENODEV)?; - // A queue that closed meanwhile keeps nothing. + // A queue that closed meanwhile keeps nothing, nor does firmware a recovery replaced. let closed = self.closed.load(Ordering::Acquire); - let (unused, reserve) = if closed { - (compute::Vacated::spares(pages, ring, kit), reserve) - } else { - firmware.queues.stock(self.owner, reserve, pages, ring, kit) + let current = lease.is_current(); + let (unused, reserve, stocked) = match state.as_deref_mut() { + Some(firmware) if !closed && current => { + let (unused, reserve) = firmware.queues.stock(self.owner, reserve, pages, ring, kit); + (unused, reserve, firmware.queues.reserves.iter().any(|reserve| reserve.owner == self.owner)) + } + _ => (compute::Vacated::spares(pages, ring, kit), reserve, closed), }; - let stocked = closed || firmware.queues.reserves.iter().any(|reserve| reserve.owner == self.owner); + let lost = state.is_none(); drop(state); drop((unused, reserve)); + if lost { + return Err(ENODEV); + } + if !current && !closed { + return Err(EAGAIN); + } // Every logical queue has room for a reserve; without one, the command must not be queued. if !stocked { return Err(ENOSPC); @@ -5255,8 +5301,9 @@ impl Backend { } Ok(()) })(); + // Backing that goes back to its owner, or client views alone, free no lower range. let freed = !deferred.render.is_empty() - || !deferred.vacated.is_empty() + || deferred.vacated.iter().any(|vacated| vacated.frees_backing()) || !deferred.bindings.is_empty(); deferred.finish(); if freed { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 2ef51ab4aa183..832435f0268bd 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -416,11 +416,12 @@ impl Backend { } Ok(published != 0 || !deferred.render.is_empty() - || !deferred.vacated.is_empty() + || deferred.vacated.iter().any(|vacated| vacated.frees_backing()) || !deferred.bindings.is_empty()) })(); + // Backing that goes back to its owner, or client views alone, free nothing for others. let freed = !deferred.render.is_empty() - || !deferred.vacated.is_empty() + || deferred.vacated.iter().any(|vacated| vacated.frees_backing()) || !deferred.bindings.is_empty(); deferred.finish(); if freed { diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index 9f7d6aafbb3eb..11b239461ccbf 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -123,7 +123,7 @@ def fixture(): fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} // The owner's spare pages: a SUBMIT provisioned them. fn take_pages(&mut self,_:u64,_:ComputeCapacity)->Option{PAGES.store(true,Ordering::SeqCst);Some(Pages)} - fn recall_backing(&mut self,_:u64,_:ComputeCapacity)->bool{false} + fn recall_backing(&mut self,_:u64,_:ComputeCapacity,_:bool)->bool{false} fn keep_returned(&mut self,_:&mut Vacated){} fn put_back(&mut self,_:u64,pages:Option,_:Option<()>,_:Option<()>)->Vacated{ if let Some(pages)=pages{std::mem::forget(pages);PAGES.store(false,Ordering::SeqCst);RETURNED.store(true,Ordering::SeqCst);}Vacated} diff --git a/tools/asahi/g17-compute-reserve-tests.py b/tools/asahi/g17-compute-reserve-tests.py index b9626c6a16bca..fb40c318a1407 100644 --- a/tools/asahi/g17-compute-reserve-tests.py +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -29,7 +29,7 @@ --mutation allocating-bind / allocating-graph / publication-allocates / claim-after-provision / free-returned / bind-other-owner / kit-needs-qid / -keep-idle / return-before-unmap inject a fault and must be caught. +keep-idle / return-before-unmap / submit-no-reclaim inject a fault and must be caught. """ import os import subprocess @@ -100,6 +100,9 @@ def sources(mutation): elif mutation == 'return-before-unmap': files['queue/compute.rs'] = files['queue/compute.rs'].replace( ' self.drop_aliases();\n reserve.give_back(', ' reserve.give_back(', 1) + elif mutation == 'submit-no-reclaim': + files['runtime.rs'] = files['runtime.rs'].replace( + 'self.wait_channels(observed, &admission, true, min_span)', 'Err::<(), _>(EBUSY)', 1) elif mutation == 'keep-idle': files['runtime.rs'] = files['runtime.rs'].replace( ' if !reserve.context.compute_claimed() {\n return;\n }\n', '', 1) @@ -140,7 +143,7 @@ def structure(files): failures.append(f'FAIL line {runtime.count(chr(10), 0, runtime.index(signature)) + 1}: runtime.rs: ' f'publication {signature.strip()} allocates ({m.group(0)})') backend = files['runtime/backend.rs'] - provision = item(runtime, ' fn provision_backing(') + provision = item(runtime, ' fn try_provision_backing(') channel = item(files['queue/compute.rs'], 'pub(crate) fn new_channel(') fresh = item(runtime, ' fn install_fresh(') checks = { @@ -182,6 +185,17 @@ def structure(files): # Else a QID freed after SUBMIT would find the owner with no kit and no queue to share. 'a queue-less owner always gets a kit': 'compute_qid_fits' not in item(runtime, ' pub(super) fn compute_lacks('), 'a queue refuses another open owner\'s backing': '!self.backing_free_for(owner)' in item(files['queue/compute.rs'], ' fn bind_owner_channel('), + # #4512: idle pools hold the lower range a SUBMIT allocates from. + 'a SUBMIT short of lower range gives idle pools back before refusing': ordered( + item(runtime, ' fn provision_backing('), 'let observed = self.shared.channels.observe();', + 'self.try_provision_backing(required)', 'self.wait_channels(observed, &admission, true, min_span)', + 'return Err(ENOSPC)'), + 'SUBMIT provisions under a preparation lease and stocks only for current firmware': ordered( + provision, 'self.shared.preparations.enter(true)?', 'lease.is_current()', 'firmware.queues.stock('), + 'only backing that is freed counts as reclaim progress': + 'vacated.frees_backing()' in item(runtime, ' fn reclaim_capacity('), + 'a re-arm without its set recalls it, its ring from smaller pages too': + 'recall_backing(self.owner, required, true)' in item(runtime, ' fn rearm_vacant('), } failures += [f'FAIL line 0: {name}' for name, ok in checks.items() if not ok] return failures @@ -380,7 +394,8 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument('--mutation', choices=['allocating-bind', 'allocating-graph', 'publication-allocates', 'claim-after-provision', 'free-returned', 'bind-other-owner', - 'kit-needs-qid', 'keep-idle', 'return-before-unmap']) + 'kit-needs-qid', 'keep-idle', 'return-before-unmap', + 'submit-no-reclaim']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: diff --git a/tools/asahi/g17-queue-object-charge-tests.py b/tools/asahi/g17-queue-object-charge-tests.py index 6001e601d08e9..f919088ce9eb5 100644 --- a/tools/asahi/g17-queue-object-charge-tests.py +++ b/tools/asahi/g17-queue-object-charge-tests.py @@ -9,7 +9,7 @@ - QUEUE_CREATE builds the context (scheduler storage, work state) in `Backend::new`; - a compute SUBMIT builds its queue's compute backing (pool pages, descriptor - ring) in `Backend::provision_backing`. + ring) in `Backend::try_provision_backing`. Everything else is built at publication, after SUBMIT accepted the job, or is device memory: render pairs, rings, generations, tiler heaps, timestamps, and @@ -125,10 +125,10 @@ def check(files): or charged.count('with_object(') != 1: failures.append('FAIL line 0: object.rs: charged() populates outside client.charging()') # QUEUE_CREATE's context and a compute SUBMIT's backing are the allocators that name a client. - if sorted(named) != [('runtime.rs', 'new'), ('runtime.rs', 'provision_backing')]: + if sorted(named) != [('runtime.rs', 'new'), ('runtime.rs', 'try_provision_backing')]: failures.append(f'FAIL line 0: allocators naming a client {named}, expected only ' "QUEUE_CREATE's context (Backend::new) and SUBMIT's compute backing " - '(Backend::provision_backing)') + '(Backend::try_provision_backing)') if literals < 10: failures.append(f'FAIL line 0: only {literals} Allocator literals found; the scan is broken') return failures diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 6d40ff748fc68..836dd3532f74a 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -506,7 +506,7 @@ def mutations(flag, names, base, expect=KILL): 'g17-compute-reserve-tests.py': [([], PASS)] + mutations( '--mutation', ['allocating-bind', 'allocating-graph', 'publication-allocates', 'claim-after-provision', 'free-returned', 'bind-other-owner', 'kit-needs-qid', - 'keep-idle', 'return-before-unmap'], []), + 'keep-idle', 'return-before-unmap', 'submit-no-reclaim'], []), 'g17-compute-owed-stamp-tests.py': [([], PASS)] + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', From 8f12a31e9228e166b20d1a1eb4ee88f159638fdb Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:16:21 -0300 Subject: [PATCH 09/13] drm/asahi: g17: drop the unreachable backing tag at compute bind bind_owner_channel() binds only an owner the queue's backing is already tagged for (backing_free_for()), so tagging the binding owner there again never changed anything. Its comment also no longer held: backing whose owner closed is untagged and given back (vacated) before another owner binds the queue, not adopted. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/queue/compute.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 0806ebe2416f9..599a8a1db61c0 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -2284,10 +2284,6 @@ impl Queue { if same_vm { 2 } else { 1 }, ); self.owner = Some(owner); - // A closed owner's backing is the binding owner's from now on. - if self.pool.populated() { - self.backing_owner.get_or_insert(owner); - } self.channel_index = channel_index; self.heavy_run = 0; self.rearm_for = None; From e196537de6bb15153b874e02f502ba20874b5c25 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:30:28 -0300 Subject: [PATCH 10/13] drm/asahi: g17: never restart a SUBMIT after its outputs were published A compute command's SUBMIT-time provisioning runs in enqueue(), after earlier commands of the same submission may have been queued and its outputs published. It can wait there: for a recovery to reopen preparations (interruptible), and for idle pools to be reclaimed (bounded and interruptible). A signal then returned ERESTARTSYS, and an EAGAIN could come back as well; the ioctl was called again and queued the earlier commands a second time. submit_result() turned only ENOMEM and ENOSPC into EIO after publication. Turn ERESTARTSYS and EAGAIN into EIO after publication too: the outputs carry the failure, as for a refusal. Before publication both keep their meaning. KUnit enomem_and_enospc_after_publication_become_eio covers them. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/fence.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index bd7f0d45ea104..4b3470568dff3 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -707,9 +707,14 @@ mod tests { fn enomem_and_enospc_after_publication_become_eio() { assert_eq!(submit_result(true, Err(ENOMEM)), Err(EIO)); assert_eq!(submit_result(true, Err(ENOSPC)), Err(EIO)); + // A restart after publication would queue the published commands again. + assert_eq!(submit_result(true, Err(ERESTARTSYS)), Err(EIO)); + assert_eq!(submit_result(true, Err(EAGAIN)), Err(EIO)); // Before publication they keep their meaning: nothing changed. assert_eq!(submit_result(false, Err(ENOMEM)), Err(ENOMEM)); assert_eq!(submit_result(false, Err(ENOSPC)), Err(ENOSPC)); + assert_eq!(submit_result(false, Err(ERESTARTSYS)), Err(ERESTARTSYS)); + assert_eq!(submit_result(false, Err(EAGAIN)), Err(EAGAIN)); // Other results are never rewritten. assert_eq!(submit_result(true, Err(EINVAL)), Err(EINVAL)); assert_eq!(submit_result(true, Ok(())), Ok(())); @@ -1394,11 +1399,14 @@ pub(crate) fn untouched_refusal(published: bool, result: &Result) -> bool { !published && matches!(result, Err(error) if *error == ENOMEM || *error == ENOSPC) } -/// The result a submission returns. ENOMEM and ENOSPC promise that nothing changed, so the same -/// failures after its outputs were published are returned as EIO: the outputs carry the failure. +/// The result a submission returns. ENOMEM and ENOSPC promise that nothing changed, and +/// ERESTARTSYS and EAGAIN have the ioctl called again as it is, so the same results after its +/// outputs were published are returned as EIO: the outputs carry the failure, and a restart would +/// queue the commands already queued a second time. A compute command's SUBMIT-time provisioning +/// can wait for a recovery or for reclaim after earlier commands of the submission were queued. pub(crate) fn submit_result(published: bool, result: Result) -> Result { match result { - Err(error) if published && (error == ENOMEM || error == ENOSPC) => Err(EIO), + Err(error) if published && [ENOMEM, ENOSPC, ERESTARTSYS, EAGAIN].contains(&error) => Err(EIO), result => result, } } From 049dfdcd9bff944f9a678d78d1b6e8bdabf36d44 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:31:06 -0300 Subject: [PATCH 11/13] tools/asahi: g17: run the SUBMIT compute provisioning loop provision_backing() retries a SUBMIT's compute allocation after reclaiming idle pools, until a deadline, and again after a recovery; only its call order was checked. g17-compute-reserve-tests now compiles the production loop against scripted allocation results: short of lower range it reclaims and retries, refuses with ENOSPC at its deadline, provisions again at once after a stale lease, passes other failures through and stops on a signal. The reclaim-unbounded mutation must be caught. Signed-off-by: Jonathan Goyvaerts --- tools/asahi/g17-compute-reserve-tests.py | 82 +++++++++++++++++++++++- tools/asahi/run-host-tests.py | 3 +- 2 files changed, 81 insertions(+), 4 deletions(-) diff --git a/tools/asahi/g17-compute-reserve-tests.py b/tools/asahi/g17-compute-reserve-tests.py index fb40c318a1407..5e4be5450ee1d 100644 --- a/tools/asahi/g17-compute-reserve-tests.py +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -29,7 +29,8 @@ --mutation allocating-bind / allocating-graph / publication-allocates / claim-after-provision / free-returned / bind-other-owner / kit-needs-qid / -keep-idle / return-before-unmap / submit-no-reclaim inject a fault and must be caught. +keep-idle / return-before-unmap / submit-no-reclaim / reclaim-unbounded inject a fault and +must be caught. """ import os import subprocess @@ -103,6 +104,9 @@ def sources(mutation): elif mutation == 'submit-no-reclaim': files['runtime.rs'] = files['runtime.rs'].replace( 'self.wait_channels(observed, &admission, true, min_span)', 'Err::<(), _>(EBUSY)', 1) + elif mutation == 'reclaim-unbounded': + files['runtime.rs'] = files['runtime.rs'].replace( + 'Err(error) if error == EBUSY => return Err(ENOSPC),', 'Err(error) if error == EBUSY => {}', 1) elif mutation == 'keep-idle': files['runtime.rs'] = files['runtime.rs'].replace( ' if !reserve.context.compute_claimed() {\n return;\n }\n', '', 1) @@ -373,8 +377,80 @@ def compiled(files): return [] +def provision_loop(files): + """Runs the production SUBMIT provisioning loop against scripted allocation results.""" + loop = item(files['runtime.rs'], ' fn provision_backing(') + loop = loop.replace('kernel::current!().signal_pending()', 'SIGNAL.load(Ordering::SeqCst)') + source = r''' +#![allow(dead_code)] +use std::{cell::{Cell, RefCell}, collections::VecDeque, sync::atomic::{AtomicBool, AtomicU64, Ordering}}; +type Result = std::result::Result; +const ENOMEM: i32 = -12; const EAGAIN: i32 = -11; const EBUSY: i32 = -16; const ENOSPC: i32 = -28; +const ERESTARTSYS: i32 = -512; +const PROVISION_RECLAIM_NS: u64 = 1_000_000_000; +static NOW: AtomicU64 = AtomicU64::new(0); +static SIGNAL: AtomicBool = AtomicBool::new(false); +fn now_ns() -> u64 { NOW.load(Ordering::SeqCst) } +mod super_ { pub mod freelist { #[derive(Clone, Copy)] pub enum ComputeCapacity { Blocks(usize) } } } +use super_ as sup; +struct Admission<'a> { deadline: u64, check: &'a dyn Fn() -> Result } +impl<'a> Admission<'a> { + fn new(deadline: u64, check: &'a dyn Fn() -> Result) -> Self { Self { deadline, check } } + fn check(&self) -> Result { (self.check)()?; if now_ns() >= self.deadline { Err(EBUSY) } else { Ok(()) } } +} +struct Channels; +impl Channels { fn observe(&self) -> u64 { 0 } } +struct Shared { channels: Channels } +struct Backend { shared: Shared, tries: RefCell>, waits: Cell } +impl Backend { + fn compute_lower_span(&self, _: sup::freelist::ComputeCapacity) -> u64 { 0 } + fn try_provision_backing(&self, _: sup::freelist::ComputeCapacity) -> Result { + self.tries.borrow_mut().pop_front().unwrap_or(Err(ENOSPC)) + } + /// The production wait checks its admission (deadline, signal) before reclaiming. + fn wait_channels(&self, _: u64, admission: &Admission<'_>, reclaim_backing: bool, _: u64) -> Result { + assert!(reclaim_backing, "a SUBMIT short of lower range must reclaim idle pools"); + self.waits.set(self.waits.get() + 1); + assert!(self.waits.get() < 100, "the reclaim must end at its deadline"); + NOW.fetch_add(300_000_000, Ordering::SeqCst); + admission.check() + } +''' + loop.replace('super::freelist::', 'sup::freelist::') + r''' +} +fn run(tries: &[Result]) -> (Result, usize) { + let backend = Backend { shared: Shared { channels: Channels }, tries: RefCell::new(tries.iter().copied().collect()), + waits: Cell::new(0) }; + let result = backend.provision_backing(sup::freelist::ComputeCapacity::Blocks(21)); + (result, backend.waits.get()) +} +fn main() { + assert_eq!(run(&[Err(ENOSPC), Ok(())]), (Ok(()), 1), "a SUBMIT short of lower range must retry after reclaim"); + let (result, waits) = run(&[]); + assert_eq!(result, Err(ENOSPC), "a range that stays short must refuse with ENOSPC"); + assert!(waits <= 4, "the reclaim must end at its deadline"); + assert_eq!(run(&[Err(EAGAIN), Ok(())]), (Ok(()), 0), "a stale lease must provision again at once"); + assert_eq!(run(&[Err(ENOMEM)]), (Err(ENOMEM), 0), "other failures are the SUBMIT's own"); + SIGNAL.store(true, Ordering::SeqCst); + assert_eq!(run(&[]).0, Err(ERESTARTSYS), "a signal ends the reclaim wait"); + println!("PASS SUBMIT provisioning: reclaims and retries when short of lower range, refuses with ENOSPC at its deadline, provisions again after a recovery, and stops on a signal"); +} +''' + with tempfile.TemporaryDirectory(prefix='g17-provision-loop-') as tmp: + path = Path(tmp) / 'loop.rs' + path.write_text(source) + build = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-Awarnings', str(path), + '-o', str(path.with_suffix(''))], capture_output=True, text=True) + if build.returncode != 0: + return [f'FAIL line 0: compiled provisioning loop does not build:\n{build.stderr}'] + run = subprocess.run([str(path.with_suffix(''))], capture_output=True, text=True, timeout=30) + if run.returncode != 0: + return [f'FAIL line 0: compiled provisioning loop: {run.stderr.strip()}'] + print(run.stdout.strip()) + return [] + + def check(files): - failures = structure(files) + compiled(files) + failures = structure(files) + compiled(files) + provision_loop(files) for name, signature, why in BINDS: text = files[name] if signature not in text: @@ -395,7 +471,7 @@ def main(): parser.add_argument('--mutation', choices=['allocating-bind', 'allocating-graph', 'publication-allocates', 'claim-after-provision', 'free-returned', 'bind-other-owner', 'kit-needs-qid', 'keep-idle', 'return-before-unmap', - 'submit-no-reclaim']) + 'submit-no-reclaim', 'reclaim-unbounded']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 836dd3532f74a..1ea488b7e0743 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -506,7 +506,8 @@ def mutations(flag, names, base, expect=KILL): 'g17-compute-reserve-tests.py': [([], PASS)] + mutations( '--mutation', ['allocating-bind', 'allocating-graph', 'publication-allocates', 'claim-after-provision', 'free-returned', 'bind-other-owner', 'kit-needs-qid', - 'keep-idle', 'return-before-unmap', 'submit-no-reclaim'], []), + 'keep-idle', 'return-before-unmap', 'submit-no-reclaim', + 'reclaim-unbounded'], []), 'g17-compute-owed-stamp-tests.py': [([], PASS)] + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', From d0294c230f97aec0692a0f2df161659a3f7bf504 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 01:34:54 -0300 Subject: [PATCH 12/13] tools/asahi: g17: follow #3704 in #4576's and #4522's rebind tests g17-channel-wait-vacate-tests (#4576) and g17-primary-sibling-livelock-tests (#4522) compile the production rebind_compute() and reclaim_capacity() against host stubs. Since the merge of main they also call this branch's backing_free_for(), has_kit() and Vacated::frees_backing(); the stubs say every queue's backing is the requester's, every owner has a kit and a vacated pool frees its backing, which is what the tests assume. #4576's test pinned the two backing-allocation ENOSPC waits with reclaim_backing in build_compute(). This branch allocates a queue's backing in SUBMIT, so that wait is provision_backing()'s now, and a publication waits only for channels and givebacks: the test checks both. Its strand-stolen-undersized-same-vm mutation targets the steal check with this branch's owner check in it. Signed-off-by: Jonathan Goyvaerts --- tools/asahi/g17-channel-wait-vacate-tests.py | 19 +++++++++++++++---- .../g17-primary-sibling-livelock-tests.py | 4 ++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/tools/asahi/g17-channel-wait-vacate-tests.py b/tools/asahi/g17-channel-wait-vacate-tests.py index e78a0aa6b1e83..e8fe51fc17488 100755 --- a/tools/asahi/g17-channel-wait-vacate-tests.py +++ b/tools/asahi/g17-channel-wait-vacate-tests.py @@ -82,8 +82,8 @@ def item(source, signature): ' let _ = undersized;', ), 'strand-stolen-undersized-same-vm': ( - ' if !queue.pool_serves(vm) || !queue.pool_fits(required) {', - ' if !queue.pool_serves(vm) {', + ' if !queue.pool_serves(vm) || !queue.backing_free_for(owner) || !queue.pool_fits(required) {', + ' if !queue.pool_serves(vm) || !queue.backing_free_for(owner) {', ), 'undersized-before-foreign': ( ' if let Some(qid) = foreign {\n' @@ -156,7 +156,11 @@ def render(mutation): build_fn = item(runtime, ' fn build_compute(') rebind_branch = build_fn[build_fn.index('rebind_compute('):build_fn.index('match rebound')] rebind_passes_false = 'self.wait_channels(observed, admission, false, min_span)?;' in rebind_branch - backing_sites_pass_true = build_fn.count('self.wait_channels(observed, admission, true, min_span)?;') == 2 + # #3704 allocates a queue's backing in SUBMIT: its ENOSPC reclaims there, and a publication + # (build_compute()) waits only for channels and givebacks. + backing_sites_pass_true = ('admission, true, min_span)' not in build_fn + and 'self.wait_channels(observed, &admission, true, min_span)' + in item(runtime, ' fn provision_backing(')) return (TEMPLATE .replace('@@REGISTRY_FNS@@', reg_fns) @@ -260,6 +264,8 @@ def render(mutation): fn pool_fits(&self, req: ComputeCapacity) -> bool { self.capacity >= req.0 } fn pool_vacant(&self) -> bool { self.vacant } fn pool_serves(&self, vm: Vm) -> bool { self.vm == vm } + // Every queue's backing is the requesting owner's (#3704's backing_free_for()). + fn backing_free_for(&self, _owner: u64) -> bool { true } fn needs_fresh_backing(&self) -> bool { self.needs_fresh } fn require_fresh_backing(&mut self) { self.needs_fresh = true; } fn reusable(&self) -> bool { @@ -327,6 +333,9 @@ def render(mutation): fn releasing(&self, _ctx: &Arc) -> bool { false } } +// A vacated pool here frees its backing (#3704's Vacated::frees_backing()). +trait FreesBacking { fn frees_backing(&self) -> bool; } +impl FreesBacking for u32 { fn frees_backing(&self) -> bool { true } } struct DeferredBatch { render: Vec, vacated: Vec, @@ -347,6 +356,8 @@ def render(mutation): impl Registry { const POOL_RETRY_NS: u64 = 100_000_000; fn compute_qid_fits(&self) -> bool { self.fresh_fits } + // Every owner's SUBMIT provisioned a kit (#3704's has_kit()). + fn has_kit(&self, _owner: u64) -> bool { true } fn observe_pool_releases(&mut self, _init: &InitData, _deferred: &mut DeferredBatch) -> Result { Ok(0) } @@ -437,7 +448,7 @@ def render(mutation): assert!(@@REBIND_PASSES_FALSE@@, "build_compute() rebind_compute()==ENOSPC must call wait_channels(..., false, min_span)"); assert!(@@BACKING_SITES_PASS_TRUE@@, - "build_compute() backing-allocation ENOSPC paths must call wait_channels(..., true, min_span)"); + "a backing-allocation ENOSPC (SUBMIT's provision_backing()) must call wait_channels(..., true, min_span), and build_compute() never"); let adm = Admission(&()); diff --git a/tools/asahi/g17-primary-sibling-livelock-tests.py b/tools/asahi/g17-primary-sibling-livelock-tests.py index 04932b285231a..f8346d83f233e 100755 --- a/tools/asahi/g17-primary-sibling-livelock-tests.py +++ b/tools/asahi/g17-primary-sibling-livelock-tests.py @@ -226,6 +226,8 @@ def render(mutation): } fn pool_fits(&self, req: ComputeCapacity) -> bool { self.pool_cap >= req.0 } fn pool_serves(&self, vm: Vm) -> bool { self.pool_vm == vm } + // Every queue's backing is the requesting owner's (#3704's backing_free_for()). + fn backing_free_for(&self, _owner: u64) -> bool { true } fn pool_vacant(&self) -> bool { self.pool_vacant } fn vacancy_pending(&self) -> bool { self.vacancy_pending } fn reusable(&self) -> bool { self.reusable } @@ -304,6 +306,8 @@ def render(mutation): } } fn compute_qid_fits(&self) -> bool { self.qid_fits } + // Every owner's SUBMIT provisioned a kit (#3704's has_kit()). + fn has_kit(&self, _owner: u64) -> bool { true } fn give_back_foreign(&mut self, qid: u8) -> Result { self.compute.iter_mut().flatten().filter_map(|e| e.queue.as_deref_mut()) .find(|q| q.qid() == qid).ok_or(EIO)?.require_fresh_backing(); From 000722571a38cbbd711d71ec5a10d02e72b7bc49 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Sun, 6 Dec 2026 12:44:14 -0300 Subject: [PATCH 13/13] drm/asahi: g17: leave outputs untouched by a restart before the first command Since main's deferred output installation (#3701), a SUBMIT prepares its submission fence before its commands and installs it in the outputs after the queueing loop, unless nothing was queued and the result is a refusal (ENOMEM, ENOSPC). A compute command's SUBMIT-time provisioning waits interruptibly (preparations, and the lower-range reclaim), so the first command can fail with ERESTARTSYS. The outputs then got the submission's fence anyway, submit_result() turned the result into EIO because the outputs were now published, and Outputs::drop() signalled -EIO into every output: libdrm did not restart, and a cumulative timeline kept the error. untouched() is the install gate now: nothing queued, and a refusal or a result the ioctl is to be called again with (retried(): ERESTARTSYS, EAGAIN, which libdrm's drmIoctl() restarts). SUBMIT, its trace and Outputs::drop() use it; the fallback path and output_fence() use retried() too, so an unpublished EAGAIN is left alone as ERESTARTSYS was. KUnit: a_restart_before_the_first_command_leaves_outputs_untouched prepares the submission, fails the first command with ERESTARTSYS or EAGAIN, and checks that the result stays as it is and that binary, timeline and cumulative outputs are untouched, then that the restarted SUBMIT publishes point 2 without error; nothing_queued_and_restarted_leaves_outputs_untouched covers the gate. g17-submit-refusal-untouched-tests follows the gate's name. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/fence.rs | 94 ++++++++++++++++++- drivers/gpu/drm/asahi/g17/queue/mod.rs | 9 +- .../g17-submit-refusal-untouched-tests.py | 8 +- 3 files changed, 100 insertions(+), 11 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index 744b761cf3d2a..80647f7c5e560 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -703,6 +703,17 @@ mod tests { assert!(!untouched_refusal(false, &Ok(()))); } + #[test] + fn nothing_queued_and_restarted_leaves_outputs_untouched() { + for error in [ERESTARTSYS, EAGAIN, ENOMEM, ENOSPC] { + assert!(untouched(false, &Err(error))); + assert!(!untouched(true, &Err(error))); + } + assert!(!untouched(false, &Err(EIO))); + assert!(!untouched(false, &Err(EBUSY))); + assert!(!untouched(false, &Ok(()))); + } + #[test] fn enomem_and_enospc_after_publication_become_eio() { assert_eq!(submit_result(true, Err(ENOMEM)), Err(EIO)); @@ -927,6 +938,68 @@ mod tests { } } + #[test] + fn a_restart_before_the_first_command_leaves_outputs_untouched() -> Result { + let contexts = contexts(); + let allocation_failure = allocation_failure(&contexts)?; + // A binary syncobj with a completed fence, and timelines at point 1. + let binary = kernel::drm::syncobj::SyncObj::new_kunit()?; + let previous = independent(&contexts)?; + binary.replace_fence(Some(&Fence::from_fence(&previous))); + previous.signal(); + let timeline = kernel::drm::syncobj::SyncObj::new_kunit()?; + let anchor = kernel::drm::syncobj::SyncObj::new_kunit()?; + for syncobj in [&timeline, &anchor] { + let point1 = independent(&contexts)?; + syncobj.add_point(kernel::dma_fence::FenceChain::new()?, &Fence::from_fence(&point1), 1); + point1.signal(); + } + let cumulative = || -> Result> { + let mut syncs = KVVec::with_capacity(3, GFP_KERNEL)?; + syncs.push(cumulative_item(anchor.clone(), 2), GFP_KERNEL)?; + syncs.push(timeline_item(timeline.clone(), 2)?, GFP_KERNEL)?; + let bundle = super::super::sync_output::SignalBundle::new(&syncs, 0)?; + syncs[0].cumulative = Some(bundle); + Ok(syncs) + }; + let mut syncs = KVVec::with_capacity(2, GFP_KERNEL)?; + syncs.push(SyncItem { syncobj: binary.clone(), fence: None, chain_fence: None, timeline_value: 0, + cumulative: None, timeline: false }, GFP_KERNEL)?; + syncs.push(timeline_item(timeline.clone(), 2)?, GFP_KERNEL)?; + // The submission's fence is prepared before the first command, whose compute provisioning + // is interrupted: SUBMIT's install gate (queue/mod.rs) keeps the outputs as they were. + for (syncs, error) in [(syncs, ERESTARTSYS), (cumulative()?, ERESTARTSYS), (cumulative()?, EAGAIN)] { + let mut outputs = Outputs::new(&contexts, syncs, 0, &allocation_failure)?; + let aggregate = outputs.publish_with(None, false, false)?; + if !untouched(false, &Err(error)) { + outputs.install(); + } + let result = submit_result(outputs.published(), Err(error)); + assert_eq!(result, Err(error)); + outputs.set_result(result); + drop(outputs); + drop(aggregate); + } + let kept = binary.fence_get().unwrap(); + assert_eq!(kept.raw(), Fence::from_fence(&previous).raw()); + assert_eq!(timeline.fence_get().unwrap().chain_find_seqno(2).err(), Some(EINVAL)); + assert_eq!(anchor.fence_get().unwrap().chain_find_seqno(2).err(), Some(EINVAL)); + // The restarted SUBMIT publishes point 2 once, chained on point 1, without error. + let mut retry = Outputs::new(&contexts, cumulative()?, 0, &allocation_failure)?; + let aggregate = retry.publish_with(None, false, false)?; + let member = aggregate.member(); + retry.install(); + retry.set_result(Ok(())); + drop(retry); + member.complete(Ok(())); + drop(member); + for syncobj in [&anchor, &timeline] { + let point2 = syncobj.fence_get().unwrap().chain_find_seqno(2)?.unwrap(); + assert!(super::super::job::fence_status(&point2) > 0); + } + Ok(()) + } + #[test] fn full_window_signal_leaves_timeline_untouched_for_restart() -> Result { unsafe extern "C" { @@ -1413,6 +1486,21 @@ pub(crate) fn untouched_refusal(published: bool, result: &Result) -> bool { !published && matches!(result, Err(error) if *error == ENOMEM || *error == ENOSPC) } +/// Whether the ioctl returns `result` to be called again as it is: interrupted (ERESTARTSYS), or +/// to retry (EAGAIN). libdrm's drmIoctl() restarts both. +pub(crate) fn retried(result: &Result) -> bool { + matches!(result, Err(error) if *error == ERESTARTSYS || *error == EAGAIN) +} + +/// Whether a submission's outputs stay untouched: none of its commands was queued (`queued` +/// false), and it was refused ([`untouched_refusal`]) or is to be called again as it is +/// ([`retried`]). A compute command's SUBMIT-time provisioning can wait interruptibly before the +/// first command is queued; its fence in the outputs would carry an error for a submission the +/// restart then queues, and be the previous point a cumulative timeline chains on. +pub(crate) fn untouched(queued: bool, result: &Result) -> bool { + !queued && (untouched_refusal(false, result) || retried(result)) +} + /// The result a submission returns. ENOMEM and ENOSPC promise that nothing changed, and /// ERESTARTSYS and EAGAIN have the ioctl called again as it is, so the same results after its /// outputs were published are returned as EIO: the outputs carry the failure, and a restart would @@ -1498,7 +1586,7 @@ impl Outputs { } /// The fence installed, or about to be installed on error, in every output sync. pub(crate) fn output_fence(&self) -> Option { - if self.submission.is_none() && self.result == Err(ERESTARTSYS) { + if self.submission.is_none() && retried(&self.result) { return None; } self.submission @@ -1556,7 +1644,7 @@ impl Drop for Outputs { chunk.finish_enqueue(self.result); } if self.submission.is_some() { - if !self.installed && !untouched_refusal(false, &self.result) { + if !self.installed && !untouched(false, &self.result) { self.install(); } let Some(submission) = self.submission.take() else { @@ -1575,7 +1663,7 @@ impl Drop for Outputs { if let Some(fallback) = self.fallback.take() { // No work was accepted and no fence was published; leave output // syncobjs untouched so a restarted ioctl can publish them once. - if self.result == Err(ERESTARTSYS) { + if retried(&self.result) { return; } if let Err(error) = self.result { diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index a1cd940f8c0f5..b2907a5615426 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -813,9 +813,10 @@ impl crate::queue::Queue for Queue { } Ok(()) })(); - // Queued commands need their outputs to carry the submission's fence. A refusal before - // the first one was queued leaves them untouched. - if !super::fence::untouched_refusal(enqueued != 0, &result) { + // Queued commands need their outputs to carry the submission's fence. A refusal, or a + // restart (a compute command's provisioning waits interruptibly), before the first one was + // queued leaves them untouched. + if !super::fence::untouched(enqueued != 0, &result) { outputs.install(); if outputs.published() { let output_fence = outputs.output_fence(); @@ -844,7 +845,7 @@ impl crate::queue::Queue for Queue { } let result = super::fence::submit_result(outputs.published(), result); outputs.set_result(result); - let output_fence = if super::fence::untouched_refusal(outputs.published(), &result) { + let output_fence = if super::fence::untouched(outputs.published(), &result) { None } else { outputs.output_fence() diff --git a/tools/asahi/g17-submit-refusal-untouched-tests.py b/tools/asahi/g17-submit-refusal-untouched-tests.py index d6b8f8deca47c..d74381302e069 100644 --- a/tools/asahi/g17-submit-refusal-untouched-tests.py +++ b/tools/asahi/g17-submit-refusal-untouched-tests.py @@ -60,7 +60,7 @@ def sources(mutation): 'bundle.prepare(&submission.fence(), compute_only)?;\n }\n self.install();\n Ok(submission)', 1) elif mutation == 'ignore-queued': files['g17/queue/mod.rs'] = files['g17/queue/mod.rs'].replace( - 'untouched_refusal(enqueued != 0, &result)', 'untouched_refusal(false, &result)', 1) + 'untouched(enqueued != 0, &result)', 'untouched(false, &result)', 1) elif mutation == 'queued-enomem': files['g17/queue/mod.rs'] = files['g17/queue/mod.rs'].replace( '.push_within_capacity(order.sequence, fences).map_err(|_| EIO)?;', @@ -91,9 +91,9 @@ def check(files): state = item(fence, 'pub(crate) fn published(') if ('self.installed' not in state or 'bundle.prepare(' not in publish or 'self.installed = true;' in publish - or 'if !self.installed && !untouched_refusal(false, &self.result)' not in drop): + or 'if !self.installed && !untouched(false, &self.result)' not in drop): failures.append('FAIL: cumulative allocation failure publishes the private aggregate') - if 'if super::fence::untouched_refusal(outputs.published(), &result)' not in submit: + if 'if super::fence::untouched(outputs.published(), &result)' not in submit: failures.append('FAIL: refusal trace exposes a private fence') scope = files['g17/sync_scope.c'] create = item(scope, 'struct dma_fence *asahi_g17_scope_create(') @@ -113,7 +113,7 @@ def check(files): if 'install(' in publish or 'commit(' in publish: failures.append('FAIL line 7: creating the submission stores it in the outputs') loop_end = submit.find('enqueued += 1;') - gate = submit.find('if !super::fence::untouched_refusal(enqueued != 0, &result) {\n outputs.install();') + gate = submit.find('if !super::fence::untouched(enqueued != 0, &result) {\n outputs.install();') if loop_end < 0 or gate < loop_end: failures.append('FAIL line 8: the outputs are not installed after the loop, gated on queued commands') install_trace = re.compile(r'super::trace::submit\(\s*1,')