From 2dc7fb52d56de679e70124fdf491c817d4862258 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 01:01:20 -0300 Subject: [PATCH 01/10] drm/asahi: g17: charge a client's queue context to that client The firmware objects of a G17 client's queues were kernel memory: counted towards the device total (kernel_resident in gpu_memory) but owned by no client, and owned by no memory cgroup when a kernel thread populated them. Under a dq-fast timeline-cases load on an M4 Pro, kernel_resident peaked at 2.4 GB. This charges the objects that QUEUE_CREATE builds, the context's scheduler storage and work state, to the client that creates the queue: - **Driver accounting:** they count as the client's held memory (fdinfo drm-resident-system, its limits) instead of kernel memory. - **Memory cgroup:** their pages are charged to the client's memory cgroup. That is the cgroup of the task that opened the DRM file, made the active memory cgroup while the pages are populated. - **Failure:** QUEUE_CREATE builds them in the client's ioctl, so a failed allocation comes back from it as ENOMEM, which Borealis reports as VK_ERROR_OUT_OF_HOST_MEMORY. - **Lifetime:** the charge belongs to the object. It is released when the object is freed, also after the client's file is gone while the firmware still holds the object. The rest of a queue's objects stay uncharged, as before: render pairs, kick rings, generations, tiler heaps, compute state and timestamps. G17 builds them when a submission is published, after SUBMIT accepted it. A memory cgroup at its limit would fail them there, and a failure there costs the client its device: a test kernel with all of them charged lost 4 devices with ENOMEM when its cgroup filled. - They are charged once they are built in QUEUE_CREATE or SUBMIT. - The Allocator now names its client: QUEUE_CREATE's names it, the publication paths say None. - `KernelObject::queue_backing()` and `Allocator::backing()`/`object()` are the way in for both. Device-global objects stay uncharged kernel memory: the boot-time firmware structures and heaps (initdata.rs, initdata/m5.rs), the crash buffer, the PM metrics and the M5 metrics in mod.rs, and the shared compute pool. Tests: - **KUnit:** a queue charge is taken past both limits, counts against the client's and the device's next objects, outlives the client's file and is released once with its object. A memory-cgroup scope restores what it replaced. - **Host test** (g17-queue-object-charge-tests.py): - only QUEUE_CREATE's Allocator names a client, and every other one says None; - uncharged kernel objects appear only in the global boot files and in the three publication files that build objects outside an Allocator (buffer.rs, buffer/target.rs, completion.rs); - three injected faults are caught. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/Makefile | 2 +- drivers/gpu/drm/asahi/g17/object.rs | 70 ++++++++++-- .../drm/asahi/g17/queue/render/generation.rs | 3 +- .../gpu/drm/asahi/g17/queue/render/memory.rs | 10 +- drivers/gpu/drm/asahi/g17/runtime.rs | 8 +- .../drm/asahi/g17/runtime/render/direct.rs | 1 + .../drm/asahi/g17/runtime/render/prepare.rs | 5 + .../drm/asahi/g17/runtime/render/replay.rs | 1 + drivers/gpu/drm/asahi/memacct.rs | 107 +++++++++++++++++- drivers/gpu/drm/asahi/memcg_scope.c | 35 ++++++ drivers/gpu/drm/asahi/memcg_scope.h | 13 +++ tools/asahi/g17-compute-constructor-tests.py | 4 +- .../g17-compute-growth-deadline-tests.py | 2 +- tools/asahi/g17-queue-object-charge-tests.py | 101 +++++++++++++++++ tools/asahi/g17-resource-tests.py | 1 + tools/asahi/run-host-tests.py | 2 + 16 files changed, 339 insertions(+), 26 deletions(-) create mode 100644 drivers/gpu/drm/asahi/memcg_scope.c create mode 100644 drivers/gpu/drm/asahi/memcg_scope.h create mode 100644 tools/asahi/g17-queue-object-charge-tests.py diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index 238ea2207db79..963749d525b43 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -9,6 +9,6 @@ aurora-$(CONFIG_DRM_ASAHI_UAT_ADOPTION) += g15/uat_glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o -aurora-y += retain.o sleep_pd.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o rtkit_dump.o +aurora-y += memcg_scope.o retain.o sleep_pd.o cpu_capacity.o g17/mesh_tvb_floor.o g17/mesh_exclusion.o rtkit_dump.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/sync_input.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/demand.o diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index af6fe96731158..e243e7ad9d56a 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -134,6 +134,42 @@ impl KernelObject { Ok(object) } + /// [`Self::backing`] that `client`'s queues need, charged to it whatever the limits: counted + /// as its held memory instead of kernel memory, and its pages charged to the client's memory + /// cgroup, until the object is dropped, also after the client is gone. Without a client it is + /// kernel memory, as [`Self::backing`]. + pub(crate) fn queue_backing( + dev: &AsahiDrmDevice, + size: usize, + cpu: CpuMap, + client: Option<&kernel::sync::Arc>, + ) -> Result { + let Some(client) = client else { + return Self::backing(dev, size, cpu); + }; + let bytes = gem::checked_object_size(size)? as u64; + Self::charged(dev, size, cpu, client, crate::memacct::LEDGER.commit(client, bytes)) + } + + fn charged( + dev: &AsahiDrmDevice, + size: usize, + cpu: CpuMap, + client: &kernel::sync::Arc, + commit: crate::memacct::Commit, + ) -> Result { + let obj = match cpu { + CpuMap::WriteBack => gem::new_kernel_object_user_charged(dev, size)?, + CpuMap::WriteCombined => gem::new_kernel_object_wc_user_charged(dev, size)?, + }; + // `with_object()` populates the pages. + let mut object = client.charging(|| Self::with_object(obj, size))?; + let charge = crate::memacct::Charge::user(commit, None); + charge.set_held(true); + object.charge = Some(charge); + Ok(object) + } + fn with_object(mut obj: gem::ObjectRef, size: usize) -> Result { let vmap = obj.vmap()?; let ptr = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; @@ -385,12 +421,32 @@ impl KernelObject { /// Allocation domains shared by the G17 resource builders. Dynamic objects /// retain a guard page; aliases keep the existing backing and its exact VA. +/// `client`, if there is one, is the client whose queues the objects are for; they are charged +/// to it ([`KernelObject::queue_backing`]). pub(crate) struct Allocator<'a> { pub(crate) dev: &'a AsahiDrmDevice, pub(crate) uat: &'a mmu::Uat, + pub(crate) client: Option<&'a kernel::sync::Arc>, } impl Allocator<'_> { + /// Allocates fresh backing, charged to the allocator's client. + pub(crate) fn backing(&self, size: usize, cpu: CpuMap) -> Result { + KernelObject::queue_backing(self.dev, size, cpu, self.client) + } + + /// [`KernelObject::new`] with backing charged to the allocator's client. + pub(crate) fn object( + &self, + vm: &mmu::Vm, + placement: Placement, + size: usize, + prot: mmu::Prot, + cpu: CpuMap, + ) -> Result { + self.backing(size, cpu)?.placed(vm, placement, prot) + } + /// Allocates in the dynamic part of the firmware's upper address space. pub(crate) fn kernel( &self, @@ -400,14 +456,7 @@ impl Allocator<'_> { cpu: CpuMap, ) -> Result { let range = self.uat.kernel_dynamic_range(); - KernelObject::new( - self.dev, - self.uat.kernel_vm(), - Placement::In(range, align), - size, - prot, - cpu, - ) + self.object(self.uat.kernel_vm(), Placement::In(range, align), size, prot, cpu) } /// Allocates a canonical low mapping, which can be aliased at the same @@ -419,8 +468,7 @@ impl Allocator<'_> { prot: mmu::Prot, cpu: CpuMap, ) -> Result { - KernelObject::new( - self.dev, + self.object( self.uat.kernel_lower_vm(), Placement::In(self.uat.kernel_lower_dynamic_range(), align), size, @@ -459,7 +507,7 @@ impl Allocator<'_> { if size == 0 || size % mmu::UAT_PGSZ != 0 { return Err(EINVAL); } - let mut object = KernelObject::backing(self.dev, size, cpu)?; + let mut object = self.backing(size, cpu)?; let mut range = self.uat.kernel_lower_dynamic_range(); let mut searching = false; loop { diff --git a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs index b2848b35b418b..33ef37d497f03 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs @@ -104,8 +104,7 @@ impl Generation { let (placement, layout) = if alloc.uat.is_m5() { (PairObject::SlotState.placement()?, Layout::m5(board.ok_or(EINVAL)?)) } else { (Placement::In(vm.client_private_range(), cfg::TVB_PAGE), Layout::NEO) }; - KernelObject::new(alloc.dev, vm, placement, layout.bytes, - mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined) + alloc.object(vm, placement, layout.bytes, mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined) } #[inline(never)] diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index ee973609ad3d3..c009ad4c5f8f1 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -327,7 +327,7 @@ impl Compact { /// M5: a shared-RW object of `size` bytes mapped in the client's compact window as `object`. fn m5(alloc: &Allocator<'_>, vm: &mmu::Vm, object: PairObject, size: usize) -> Result { let size = size.checked_next_multiple_of(mmu::UAT_PGSZ).ok_or(EOVERFLOW)?; - let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; + let backing = alloc.backing(size, CpuMap::WriteCombined)?; let mapping = object.map(&backing, vm, 0..size, mmu::PROT_GPU_SHARED_RW)?; Ok(Self { address: mapping.iova(), mapping: Some(mapping), _backing: backing }) } @@ -336,7 +336,7 @@ impl Compact { if alloc.uat.is_m5() { return Err(EINVAL); } - let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; + let backing = alloc.backing(size, CpuMap::WriteCombined)?; let mapping = buffer::compact_alias( &backing, vm, @@ -413,8 +413,7 @@ pub(super) struct NeoGeneration { } impl NeoGeneration { fn allocate_state(alloc: &Allocator<'_>, vm: &mmu::Vm) -> Result { - KernelObject::new( - alloc.dev, + alloc.object( vm, crate::g17::object::Placement::In(vm.client_private_range(), cfg::TVB_PAGE), storage::STATE_SIZE, @@ -617,8 +616,7 @@ impl Memory { ) })?; } - let registers = if m5 { None } else { Some(KernelObject::new( - alloc.dev, + let registers = if m5 { None } else { Some(alloc.object( vm, crate::g17::object::Placement::In(vm.client_private_range(), mmu::UAT_PGSZ as u64), mmu::UAT_PGSZ, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index b79ee66cfa63b..c11fdbac73040 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1508,9 +1508,12 @@ impl Backend { } }; let dev = shared.drm()?; + // QUEUE_CREATE builds the context here, in the client's ioctl: a failure comes back from + // it, so the context's objects are charged to the client. let alloc = super::object::Allocator { dev: &dev, uat: &uat, + client: vm.memory_client(), }; let owner_pid = u32::try_from(kernel::current!().group_leader().pid()).map_err(|_| EOVERFLOW)?; @@ -1622,6 +1625,7 @@ impl Backend { let alloc = super::object::Allocator { dev: &dev, uat: &uat, + client: None, }; let mut built = Some(super::initdata::ComputeShared::new(&alloc)); let result = { @@ -1760,7 +1764,7 @@ 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 }; + 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())?); @@ -1972,6 +1976,7 @@ impl Backend { let alloc = super::object::Allocator { dev: &dev, uat: &uat, + client: None, }; let reservation = match reservation { Ok(reservation) => reservation, @@ -2151,6 +2156,7 @@ impl Backend { let alloc = super::object::Allocator { dev: &dev, uat: &uat, + client: None, }; let reservation = match source { Ok(reservation) => reservation, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index ed6d477891cc8..1831b17811927 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -479,6 +479,7 @@ impl Backend { let alloc = Allocator { dev: &dev, uat: &loan.uat, + client: None, }; pair.prepare(&alloc, packet, loan.addresses)?; let render = port.render_lock(); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 1c57ed12adcef..9cc27d0e5aca5 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -134,6 +134,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; let pool = match existing { Some(pool) => pool, @@ -239,6 +240,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; pool.ensure_backing(&alloc, &resources.global, client) } @@ -315,6 +317,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; if resources.uat.is_m5() { return self.prepare_pool_backing( @@ -397,6 +400,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; let fresh_graph = match &build { Build::Fresh(..) | Build::Parked { .. } => true, @@ -936,6 +940,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &uat, + client: None, }; let mut growth = None; let busy = matches!(growth_target, Some((_, None))); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs b/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs index a37ad6b2c8ab8..bcd1efea2ae34 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs @@ -127,6 +127,7 @@ impl Firmware { let alloc = Allocator { dev: &dev, uat: &uat, + client: None, }; pair.prepare(&alloc, &packet, addresses) }); diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index c6fc7202292ab..e24babe3b3e04 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -32,8 +32,12 @@ //! 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 (firmware structures, per-queue buffers and the global heaps) -//! count towards the device total and its limit, but are attributed to no process. +//! 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. use core::sync::atomic::{ AtomicBool, @@ -51,6 +55,15 @@ use kernel::{ sync::{aref::ARef, Arc}, }; +use core::ffi::c_void; + +unsafe extern "C" { + fn asahi_memcg_get() -> *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); +} + use crate::module_parameters; /// Device-wide GPU memory totals, in bytes. @@ -217,6 +230,19 @@ impl Ledger { }) } + /// Commits `bytes` of kernel memory that `client`'s queues need, whatever the limits: the + /// bytes count against both limits for the client's later objects, and are given back + /// when the returned [`Commit`] is dropped. + pub(crate) fn commit(&'static self, client: &Arc, bytes: u64) -> Commit { + client.committed.fetch_add(bytes, Ordering::AcqRel); + self.user_committed.fetch_add(bytes, Ordering::AcqRel); + Commit { + ledger: self, + client: client.clone(), + bytes, + } + } + /// Adds `bytes` to `client`'s and the device's committed totals if both stay within their /// limits; otherwise counts a refusal and fails with `ENOMEM`, adding nothing. fn reserve(&self, client: &Client, bytes: u64) -> Result { @@ -316,6 +342,22 @@ pub(crate) struct Client { resident: AtomicU64, /// Bytes of the device's firmware timestamp window this client's bound buffers hold. timestamp_window: AtomicU64, + /// The memory cgroup of the task that opened the client, referenced (NULL without memory + /// cgroups). + memcg: *mut c_void, +} + +// SAFETY: `memcg` is a counted reference, which may be used and dropped on any thread; the +// rest are atomics. +unsafe impl Send for Client {} +// SAFETY: See `Send`; shared access never changes `memcg`. +unsafe impl Sync for Client {} + +impl Drop for Client { + fn drop(&mut self) { + // SAFETY: Drops the reference `asahi_memcg_get()` took in `Client::new()`. + unsafe { asahi_memcg_put(self.memcg) }; + } } impl Client { @@ -325,11 +367,26 @@ impl Client { committed: AtomicU64::new(0), resident: AtomicU64::new(0), timestamp_window: AtomicU64::new(0), + // SAFETY: Takes a reference to the current task's memory cgroup, which + // `Drop` gives back. + memcg: unsafe { asahi_memcg_get() }, }, GFP_KERNEL, )?) } + /// Runs `f` with the client's memory cgroup as the one that pages populated in it are + /// charged to, from any task. + pub(crate) fn charging(&self, f: impl FnOnce() -> T) -> T { + // SAFETY: `memcg` stays referenced while `self` exists, and the previous cgroup is + // restored before returning. + let old = unsafe { asahi_memcg_enter(self.memcg) }; + let result = f(); + // SAFETY: Restores what `asahi_memcg_enter()` replaced. + unsafe { asahi_memcg_leave(old) }; + result + } + pub(crate) fn committed(&self) -> u64 { self.committed.load(Ordering::Relaxed) } @@ -633,6 +690,52 @@ mod tests { Ok(()) } + static QUEUE: Ledger = Ledger::new(); + + #[test] + fn queue_objects_are_charged_to_their_client_and_released_once() -> Result { + QUEUE.set_limits(Limits { device: 64 * MIB, client: 32 * MIB }); + let a = Client::new()?; + let b = Client::new()?; + // A queue's kernel objects are charged whatever the limits, like memory that already + // exists. a is past its own limit afterwards. + let ring = Charge::user(QUEUE.commit(&a, 24 * MIB), None); + ring.set_held(true); + let state = Charge::user(QUEUE.commit(&a, 16 * MIB), None); + state.set_held(true); + assert_eq!((a.committed(), a.resident()), (40 * MIB, 40 * MIB)); + assert_eq!(QUEUE.kernel_resident.load(Ordering::Relaxed), 0); + // They count against the client's and the device's limits for its next objects. + assert_eq!(QUEUE.admit(&a, MIB).err(), Some(ENOMEM)); + assert_eq!(QUEUE.admit(&b, 32 * MIB).err(), Some(ENOMEM)); + let b1 = QUEUE.admit(&b, 24 * MIB)?; + // The client's file goes while the firmware still holds the objects: the charges stay + // until the objects are freed, and each is released once. + drop(a); + assert_eq!(QUEUE.user_resident.load(Ordering::Relaxed), 40 * MIB); + drop(ring); + assert_eq!(QUEUE.user_committed.load(Ordering::Relaxed), 40 * MIB); + drop(state); + drop(b1); + assert_eq!(QUEUE.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(QUEUE.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } + + #[test] + fn charging_restores_the_memory_cgroup() -> Result { + let a = Client::new()?; + // Nested scopes restore what they replaced; a kernel thread's is none. + let inner = a.charging(|| a.charging(|| 7)); + assert_eq!(inner, 7); + // SAFETY: Replaces and at once restores the current task's active memory cgroup. + let old = unsafe { asahi_memcg_enter(core::ptr::null_mut()) }; + // SAFETY: Restores it. + unsafe { asahi_memcg_leave(old) }; + assert!(old.is_null()); + Ok(()) + } + static KERNEL: Ledger = Ledger::new(); #[test] diff --git a/drivers/gpu/drm/asahi/memcg_scope.c b/drivers/gpu/drm/asahi/memcg_scope.c new file mode 100644 index 0000000000000..c7af8e96f083e --- /dev/null +++ b/drivers/gpu/drm/asahi/memcg_scope.c @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The memory cgroup of a GPU client, for kernel objects allocated on its + * behalf (memacct.rs). Their pages are charged to the active memory cgroup + * wherever they are populated, an ioctl of another process or a kernel + * thread among them. + */ + +#include +#include +#include + +#include "memcg_scope.h" + +/* The current task's memory cgroup, referenced; NULL without memory cgroups. */ +struct mem_cgroup *asahi_memcg_get(void) +{ + return get_mem_cgroup_from_mm(current->mm); +} + +void asahi_memcg_put(struct mem_cgroup *memcg) +{ + mem_cgroup_put(memcg); +} + +/* Makes @memcg the one new pages are charged to; returns the previous one. */ +struct mem_cgroup *asahi_memcg_enter(struct mem_cgroup *memcg) +{ + return set_active_memcg(memcg); +} + +void asahi_memcg_leave(struct mem_cgroup *old) +{ + set_active_memcg(old); +} diff --git a/drivers/gpu/drm/asahi/memcg_scope.h b/drivers/gpu/drm/asahi/memcg_scope.h new file mode 100644 index 0000000000000..87434556bfe2e --- /dev/null +++ b/drivers/gpu/drm/asahi/memcg_scope.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ASAHI_MEMCG_SCOPE_H +#define _ASAHI_MEMCG_SCOPE_H + +struct mem_cgroup; + +/* Called from memacct.rs. */ +struct mem_cgroup *asahi_memcg_get(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); + +#endif diff --git a/tools/asahi/g17-compute-constructor-tests.py b/tools/asahi/g17-compute-constructor-tests.py index d5a3bbdeb44d2..4bd2999fc1882 100644 --- a/tools/asahi/g17-compute-constructor-tests.py +++ b/tools/asahi/g17-compute-constructor-tests.py @@ -59,7 +59,7 @@ def fixture(): impl Shared{fn drm(&self)->Result<()>{Ok(())} fn note_changed(&self){self.changed.notify_all();}} struct Context{m5:bool}impl Context{fn vm(&self)->&(){&()} fn is_m5(&self)->bool{self.m5}} struct Backend{shared:Shared,context:Context} -struct Allocator<'a>{dev:&'a (),uat:&'a ()} +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)}} @@ -83,7 +83,7 @@ def fixture(): 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:&()}; + 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}); diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index 7ed4ca5c95277..0877ed9afdcd7 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -70,7 +70,7 @@ def fixture(): // A G17P compute pool is sized in blocks; the sizes only flow through here. type ComputeCapacity=usize; struct Backend{shared:Shared,context:Context,owner:u64} -struct Allocator<'a>{dev:&'a (),uat:&'a ()} +struct Allocator<'a>{dev:&'a (),uat:&'a (),client:Option<&'a ()>} struct Pages;struct Alias; impl Pages{ fn for_compute(_:&Allocator<'_>,_:ComputeCapacity,_:Option<&()>)->Result{PAGES.store(true,Ordering::SeqCst);Ok(Self)} diff --git a/tools/asahi/g17-queue-object-charge-tests.py b/tools/asahi/g17-queue-object-charge-tests.py new file mode 100644 index 0000000000000..fa4ad66de9a12 --- /dev/null +++ b/tools/asahi/g17-queue-object-charge-tests.py @@ -0,0 +1,101 @@ +#!/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. + +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. + +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: + +- every `Allocator { .. }` literal sets `client`, exactly one (QUEUE_CREATE's, + in `Backend::new`) names 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. +""" +import argparse +import re +import sys +from pathlib import Path + +G17 = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' +GLOBAL = {'object.rs', 'initdata.rs', 'initdata/m5.rs', 'mod.rs'} +# Built at publication; uncharged until they are built at QUEUE_CREATE or SUBMIT. +PUBLICATION = {'buffer.rs', 'buffer/target.rs', 'completion.rs'} +UNCHARGED = re.compile(r'KernelObject::(backing|new)\(|gem::new_kernel_object(_wc)?\(') +LITERAL = re.compile(r'Allocator\s*\{(?P[^{}]*)\}', re.S) + + +def sources(mutation): + files = {str(p.relative_to(G17)): p.read_text() for p in sorted(G17.rglob('*.rs'))} + if mutation == 'drop-client': + k = 'runtime.rs' + files[k] = files[k].replace('client: vm.memory_client(),', '', 1) + elif mutation == 'uncharged-backing': + k = 'queue/render/memory.rs' + files[k] = files[k].replace('alloc.backing(size, CpuMap::WriteCombined)', + 'KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)', 1) + elif mutation == 'none-client': + k = 'runtime.rs' + files[k] = files[k].replace('client: vm.memory_client(),', 'client: None,', 1) + return files + + +def line(text, pos): + return text.count('\n', 0, pos) + 1 + + +def check(files): + failures = [] + named = [] + literals = 0 + for name, text in files.items(): + code = '\n'.join(l.split('//')[0] for l in text.split('\n')) + for m in LITERAL.finditer(code): + body = m.group('body') + if 'dev' not in body or 'uat' not in body: + continue # the struct definition or an unrelated type + if name == 'object.rs' and 'pub(crate) dev' in body: + continue + literals += 1 + 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])) + 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)") + if literals < 10: + failures.append(f'FAIL line 0: only {literals} Allocator literals found; the scan is broken') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['drop-client', 'uncharged-backing', 'none-client']) + 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") + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index 31d24d19afee2..dabfe40fbe655 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -392,6 +392,7 @@ def shared_alias_tests(root, source): } struct Allocator<'a> {dev:&'a Device,uat:&'a Uat} impl Allocator<'_> { + fn backing(&self,size:usize,cpu:CpuMap)->Result {KernelObject::backing(self.dev,size,cpu)} '''+method+''' } fn case(obstacles:&[(usize,u64,u64)],fault:Option,size:usize,expected:std::result::Result,attempts:usize) { diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index e829bcd9434dc..da9196faf2e54 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -445,6 +445,8 @@ def mutations(flag, names, base, expect=KILL): 'wrong-j813-pipe'), []), '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'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)], From 7ff8f5a440624d134cbe56854d413d3840cabce0 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 14:48:39 -0300 Subject: [PATCH 02/10] 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 03/10] 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 04/10] 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 da65b3f1562c1b56b2bb9047cdea1f366a67c37c Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 16:18:03 -0500 Subject: [PATCH 05/10] drm/asahi: retire client-owned queue backing at its release fence Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/g17/object.rs | 22 ++++++++++++-- drivers/gpu/drm/asahi/g17/runtime.rs | 10 ++++++- tools/asahi/g17-object-fence-tests.py | 41 ++++++++++++++++++++------- 3 files changed, 59 insertions(+), 14 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index e243e7ad9d56a..a3aed32cad412 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -872,6 +872,8 @@ impl Pool { for (index, entry) in inner.returned[begin..begin + POOL_SLOTS].iter().enumerate() { let Some(entry) = entry.as_ref().filter(|entry| { !entry.poisoned + && alloc.client.is_none() + && entry.object.charge.is_none() && entry.object.size() == size && entry.prefix == prefix && entry.cpu == cpu @@ -942,7 +944,10 @@ impl Pool { result.defer = Some(self.clone()); return Ok(result); } - if prefix == 0 { + // Converted mappings can retain firmware cache state until processor stop. + // Keep client pages uncached so a release witness suffices to unmap them + // and drop both their ledger charge and their physical memcg charge. + if prefix == 0 || alloc.client.is_some() { return Ok(result); } let (proof, mutated) = match result.mapping.as_ref() { @@ -1016,6 +1021,8 @@ impl Pool { order, fence, }); + drop(inner); + self.reap_deferred(super::channel::control_witnessed()); return; } } @@ -1086,7 +1093,18 @@ impl Pool { } /// Unmaps the deferred objects whose fence the firmware has met. - fn reap_deferred(&self, witnessed: u64) { + pub(super) fn reap_deferred(&self, witnessed: u64) { + loop { + let mut inner = self.inner.lock(); + let Some(index) = inner.returned.iter().position(|slot| { + slot.as_ref().is_some_and(|entry| entry.object.charge.is_some() && entry.fence <= witnessed) + }) else { break }; + let entry = inner.returned[index].take().unwrap(); + inner.reserved[index / POOL_SLOTS] -= 1; + inner.bytes -= entry.object.size(); + drop(inner); + drop(entry); + } loop { let entry = { let mut inner = self.inner.lock(); diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index c11fdbac73040..30c91db366493 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -2251,6 +2251,7 @@ impl Backend { /// The physical namespace bounds the batch independently of open logical queues. /// Collection failure leaves the engine's Active owner intact for a stopped retry. pub(super) struct DeferredBatch { + object_pool: Option>, has_source_completions: bool, values: KVVec, /// Exited owners detached from idle retained compute queues and the backing @@ -2291,6 +2292,7 @@ impl DeferredBatch { /// No room at all: allocates nothing. fn empty() -> Self { Self { + object_pool: None, has_source_completions: false, values: KVVec::new(), bindings: KVVec::new(), @@ -2301,7 +2303,8 @@ impl DeferredBatch { } /// Holds nothing: finished, or never used. fn is_idle(&self) -> bool { - !self.has_source_completions + self.object_pool.is_none() + && !self.has_source_completions && self.values.is_empty() && self.bindings.is_empty() && self.vacated.is_empty() @@ -2315,6 +2318,7 @@ impl DeferredBatch { 0 }; Ok(Self { + object_pool: None, has_source_completions: false, values: KVVec::with_capacity(capacity, GFP_KERNEL)?, bindings: KVVec::with_capacity(detached, GFP_KERNEL)?, @@ -2441,6 +2445,9 @@ impl DeferredBatch { for release in self.tvb.drain_all() { drop(release); } + if let Some(pool) = self.object_pool.take() { + pool.reap_deferred(super::channel::control_witnessed()); + } } } @@ -4345,6 +4352,7 @@ impl super::Firmware { freed |= busy && queue.channel_free(); releasing |= queue.pool_release_pending(); } + deferred.object_pool = Some(self.pool.clone()); freed |= self.queues.observe_pool_releases(&self.init, deferred)? != 0; let shared = &self.primary.state.shared; // Edge notifications cover the transitions this driver makes; every diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 681aaac2860e9..e33610df930db 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -200,7 +200,7 @@ def context_source(text): } /// A firmware object: `id` is unique per allocation, the mapping is its address. -pub struct KernelObject { pub id: u64, pub mapping: Option, bytes: Vec } +pub struct KernelObject { pub charge: Option, pub id: u64, pub mapping: Option, bytes: Vec } impl KernelObject { pub fn size(&self) -> usize { self.bytes.len() } pub fn bytes_mut(&mut self) -> &mut [u8] { &mut self.bytes } @@ -221,12 +221,12 @@ def context_source(text): /// The control-ring witness when `id` was unmapped. pub fn unmapped_at(id: u64) -> Option { UNMAPPED_AT.with(|u| u.borrow().get(&id).copied()) } -pub struct Allocator<'a> { pub next: &'a Cell } +pub struct Allocator<'a> { pub client: Option, pub next: &'a Cell } impl Allocator<'_> { pub fn kernel(&self, size: usize, _align: u64, _prot: mmu::Prot, _cpu: impl Sized) -> Result { let id = self.next.get(); self.next.set(id + 1); - Ok(KernelObject { id, mapping: Some(mmu::KernelMapping { iova: id << 20 }), bytes: vec![0xa5; size] }) + Ok(KernelObject { charge: self.client, id, mapping: Some(mmu::KernelMapping { iova: id << 20 }), bytes: vec![0xa5; size] }) } } @@ -330,7 +330,7 @@ def context_source(text): pub fn differential(ops: &[crate::Op], after_release: bool) -> Vec { crate::channel::set(0, 0); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = $new(after_release); let mut live: Vec> = (0..5).map(|_| Vec::new()).collect(); let mut trace = Vec::new(); @@ -409,10 +409,28 @@ def context_source(text): /// Uncached pooled objects (`prefix == 0`) skip `set_fw_cached_prefix` while keeping /// their pool lease, fence, return mark, reuse zeroing and retention until stop. + pub fn client_pool_retirement() { + let next = Cell::new(1); + let a = Allocator { client: Some(1), next: &next }; + let b = Allocator { client: Some(2), next: &next }; + let pool = Pool::new(false).unwrap(); + crate::forget_unmapped(); + crate::channel::set(3, 3); + let original = work_state(&pool, &a); + let id = original.id; + drop(original); + assert!(!unmapped(id)); + crate::channel::set(4, 4); + let new = work_state(&pool, &b); + assert_eq!(new.charge, b.client); + assert_ne!(new.id, id); + assert!(unmapped(id)); + } + pub fn uncached_pooled() { for after_release in [true, false] { let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(5, 3); @@ -458,7 +476,7 @@ def context_source(text): /// Each return class decides the fence; reuse never waits on a met fence. pub fn return_classes() { let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(true).unwrap(); // Three records published, two of them consumed. crate::channel::set(3, 1); @@ -546,7 +564,7 @@ def context_source(text): let what = format!("{family:?}, after_release {after_release}"); let line = format!("cached_objects_{} ", family as usize); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); let get = || match family { Family::WorkState => work_state(&pool, &alloc), @@ -620,7 +638,7 @@ def context_source(text): // An uncached object kept until stop leaves the deferred list alone. let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(10, 7); @@ -653,7 +671,7 @@ def context_source(text): pub fn model(seed: u64, steps: usize) { crate::channel::set(0, 0); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(true).unwrap(); crate::forget_unmapped(); let mut rng = crate::Rng(seed); @@ -812,7 +830,7 @@ def context_source(text): pub fn accessors() { for after_release in [true, false] { let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(6, 4); @@ -879,7 +897,7 @@ def context_source(text): for after_release in [true, false] { let what = format!("after_release {after_release}"); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(10, 7); @@ -931,6 +949,7 @@ def context_source(text): } fn main() { + now::client_pool_retirement(); now::uncached_pooled(); now::return_classes(); now::full_family(); From 936c70c9dbddd7b67d5d7c5ebb0de50bb167e031 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 16:23:48 -0500 Subject: [PATCH 06/10] 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 3ad4260f756db8a1229a8b5f1a77805039bfd102 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 4 Dec 2026 15:08:25 -0300 Subject: [PATCH 07/10] drm/asahi: g17: give each render pool its own window of lower VA On a NEO GPU every render pool, every compute pool and the small canonical objects of hardware queues share one lower dynamic range of the kernel lower VM: 1984 MiB on the M4 Pro, which uses the narrow split. A base render pool takes 46 MiB of it. Pools were placed first come, first served, and a pool vacated under pressure gave its addresses back, so a client whose pool had been vacated needed a fresh hole to re-arm it. On m4.230 a capped dEQP-VK load filled the range; reclaim_idle_render_pools() then handed the compositor's idle pool to a waiting client, and the compositor's next frame found no hole for its re-armed pool: its SUBMIT got ENOSPC and Hyprland aborted. One client's use of a device-wide range failed another client. Split the range once at boot (Uat::split_lower_window()). Windows (Uat::reserve_lower_window(), drm_mm nodes that map nothing) are placed lowest hole first from its start; the small canonical lower objects go to a band at its end, which only grows. Nothing is set aside for queues that do not exist yet: every reservation is made by the client that needs it, the first time it needs it, and kept until it goes. - The band starts with the objects bound to hardware queue identities, which stay with their QID until the firmware stops, past the queue that made them: the render pairs the QIDs allow, each with two kick rings and a current and a prepared graph; the 128 retired bindings; and the compute QIDs render leaves (kick::render_reserve()) with their kits. Its size depends on the QIDs, not on how many queues exist. Probe fails if not even one base render pool window fits beside it, and logs the split. - A computing owner takes its own budget of the band (its descriptor ring and spares, and a spare kit) at its first compute SUBMIT, in provision_backing(), before allocating them, and keeps it until it goes (Uat::reserve_lower_budget()). The band grows down only into space no window holds; a closed owner's budget stays in the band for the next. - A context reserves its render pool window, sized for its blocks (the base pool from the GPU's cores and clusters, or more after reserve_render_scs()), at its first render SUBMIT, before any command of that submission is queued. Only its pool places backing there, the first time and at every re-arm, so a context that has rendered never needs lower VA again, and no other client can take its window. The window goes back when the pool and every backing placed in it are gone. - A compute pool reserves a window of its own before any of its pages are allocated, in its client's SUBMIT, and gives it back with them. A refused window no longer costs a populated backing. - A refusal is the requesting client's own ENOSPC at its SUBMIT, when the range is used up or no hole of the size it needs is left; the capacity snapshot counts the latter (refused_fragmented) with the band's state. Queue admission and QUEUE_LIMITS keep the variant's limit. reclaim_idle_render_pools() existed to free shared lower VA for a waiting publisher; a vacated pool now frees none, so it and its trigger go. Vacating evicted clients' pools under memory pressure is unchanged. The compile-time check that WIDE_LOWER holds a base pool per execution context, which the narrow split never met, becomes a KUnit test of the split on both ranges. The capacity snapshot names each render context's owner pid and window size. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/capacity.rs | 5 + drivers/gpu/drm/asahi/g17/context.rs | 54 ++++- drivers/gpu/drm/asahi/g17/freelist.rs | 200 ++++++++++++++---- drivers/gpu/drm/asahi/g17/job.rs | 2 + drivers/gpu/drm/asahi/g17/kick.rs | 2 +- drivers/gpu/drm/asahi/g17/mod.rs | 18 ++ drivers/gpu/drm/asahi/g17/object.rs | 27 ++- drivers/gpu/drm/asahi/g17/queue/admission.rs | 7 - drivers/gpu/drm/asahi/g17/queue/compute.rs | 8 +- .../drm/asahi/g17/queue/compute/reserve.rs | 2 +- drivers/gpu/drm/asahi/g17/queue/mod.rs | 5 + drivers/gpu/drm/asahi/g17/queue/render.rs | 3 + .../gpu/drm/asahi/g17/queue/render/memory.rs | 2 +- drivers/gpu/drm/asahi/g17/runtime.rs | 41 +--- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 9 + drivers/gpu/drm/asahi/g17/runtime/render.rs | 43 +--- .../drm/asahi/g17/runtime/render/submit.rs | 9 +- drivers/gpu/drm/asahi/mmu.rs | 142 +++++++++++++ tools/asahi/g17-lower-window-tests.py | 191 +++++++++++++++++ tools/asahi/g17-resource-tests.py | 4 +- tools/asahi/g17-shared-pool-tests.py | 158 -------------- tools/asahi/run-host-tests.py | 6 +- 22 files changed, 631 insertions(+), 307 deletions(-) create mode 100755 tools/asahi/g17-lower-window-tests.py delete mode 100644 tools/asahi/g17-shared-pool-tests.py diff --git a/drivers/gpu/drm/asahi/g17/capacity.rs b/drivers/gpu/drm/asahi/g17/capacity.rs index 421e0bb598840..9961ebae98614 100644 --- a/drivers/gpu/drm/asahi/g17/capacity.rs +++ b/drivers/gpu/drm/asahi/g17/capacity.rs @@ -83,6 +83,11 @@ impl kernel::debugfs::Writer for View { "g17_render_template full={} patched={} verified={} mismatched={} unmapped={}", t_full, t_patched, t_verified, t_mismatched, t_unmapped )?; + if let Some((floor, spare, windows, fragmented)) = uat.lower_ledger() { + let range = uat.kernel_lower_dynamic_range(); + writeln!(f, "lower_band bytes={} spare={} window_bytes={} refused_fragmented={}", + range.end - floor, spare, windows, fragmented)?; + } let upper = uat.kernel_dynamic_range(); for (name, vm, range) in [ ("dynamic_lower_bytes", uat.kernel_lower_vm(), uat.kernel_lower_dynamic_range()), diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index adbca7864df25..02fa70868320d 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -8,7 +8,7 @@ mod identity; use super::{ - freelist::{RenderId, RenderIds, RenderPool}, + freelist::{RenderId, RenderIds, RenderPool, Window}, fw::{context as fw, queue::Policy}, object::{Allocator, CpuMap, Exposure, Family, KernelObject, Pool, PooledObject, ReturnMark}, status::VmStatus, @@ -280,6 +280,13 @@ pub(crate) struct Context { /// ([`super::fw::Variant::render_id_at_create`]), until its render pool takes it over or /// the closed context is reclaimed. render_id: Arc>>, + /// The NEO render pool's span of lower VA for `render_blocks`, reserved by the context's first + /// render SUBMIT ([`Self::reserve_render_window`]) and kept until the context goes: the pool + /// places every backing there ([`RenderPool::new`]). `None` before that, and on M5. + render_window: Arc>>>, + /// The NEO owner's share of the lower band for its compute objects, taken at its first compute + /// SUBMIT ([`Self::reserve_compute_budget`]) and kept until it goes. + compute_budget: Arc>>, render_blocks: AtomicUsize, /// Timestamp pages of retired compute commands, mapped in this context's VM. compute_timestamps: Arc, @@ -388,6 +395,8 @@ impl Context { GFP_KERNEL, )?; let render = Arc::pin_init(new_mutex!(None, "G17 context private memory"), GFP_KERNEL)?; + let render_window = Arc::pin_init(new_mutex!(None, "G17 context render window"), GFP_KERNEL)?; + let compute_budget = Arc::pin_init(new_mutex!(None, "G17 context compute budget"), GFP_KERNEL)?; let render_id = Arc::pin_init(new_mutex!(render_id, "G17 context render pool identity"), GFP_KERNEL)?; let order = @@ -427,6 +436,8 @@ impl Context { exposure, render, render_id, + render_window, + compute_budget, render_blocks: AtomicUsize::new(super::fw::freelist::RENDER_BLOCKS), compute_timestamps: super::completion::ComputeTimestampCache::new()?, policy, @@ -703,11 +714,38 @@ impl Context { } Ok(result) } + /// Sizes the render pool before its window exists. pub(crate) fn reserve_render_blocks(&self, blocks: usize) -> Result { - if self.is_published() || self.render.lock().is_some() { return Err(EBUSY); } + if self.is_published() || self.render.lock().is_some() || self.render_window.lock().is_some() { + return Err(EBUSY); + } self.render_blocks.store(blocks, Ordering::Release); Ok(()) } + /// Takes this NEO owner's lower band budget of `bytes` at its first compute SUBMIT; an owner + /// that holds one keeps it. A full range refuses this SUBMIT (ENOSPC). + pub(crate) fn reserve_compute_budget(&self, uat: &mmu::Uat, bytes: u64) -> Result { + let mut budget = self.compute_budget.lock(); + if budget.is_none() { + *budget = Some(uat.reserve_lower_budget(bytes).map_err(|error| { + if error == ENOSPC { super::capacity::refused(super::capacity::Site::LowerVa) } else { error } + })?); + } + Ok(()) + } + pub(crate) fn has_render_window(&self) -> bool { + self.render_window.lock().is_some() + } + /// Reserves this NEO context's render pool window at its first render SUBMIT; a context that + /// holds one keeps it, so no later SUBMIT or re-arm needs lower VA. A full pool region refuses + /// this SUBMIT (ENOSPC). + pub(crate) fn reserve_render_window(&self, uat: &mmu::Uat) -> Result { + let mut window = self.render_window.lock(); + if window.is_none() { + *window = Some(Arc::new(Window::render(uat, self.render_blocks())?, GFP_KERNEL)?); + } + Ok(()) + } pub(crate) fn render_blocks(&self) -> usize { self.render_blocks.load(Ordering::Acquire) } @@ -737,6 +775,7 @@ impl Context { // M5: existing pairs retain the old pool through their rebind and // its release acknowledgement. Allocation failure leaves it installed. } + let window = if plan.is_none() { self.render_window.lock().clone() } else { None }; let pool = Arc::new( match plan { Some(plan) => RenderPool::m5( @@ -752,6 +791,7 @@ impl Context { self.vm(), self.render_blocks(), Some(&self.render_id), + &window.ok_or(EINVAL)?, )?, }, GFP_KERNEL, @@ -1211,7 +1251,13 @@ mod capacity_tests { impl Context { pub(crate) fn write_capacity(&self, f: &mut kernel::fmt::Formatter<'_>, scope: &str, index: usize) -> kernel::fmt::Result { - writeln!(f, "context scope={} index={} id={} work_used={} work_total={} render_used={} render_total=2", - scope, index, self.id(), self.states.used(), STATE_COUNT, self.work.lock().render.used()) + // The owner's pid names its cgroup (/proc//cgroup) for whoever attributes lower VA. + let window = self.render_window.lock().as_ref().map_or(0, |window| { + let range = window.range(); + range.end - range.start + }); + writeln!(f, "context scope={} index={} id={} work_used={} work_total={} render_used={} render_total=2 pid={} lower_window={}", + scope, index, self.id(), self.states.used(), STATE_COUNT, self.work.lock().render.used(), + self.owner_pid, window) } } diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index 91dac5a0131be..184f89e3cd0fe 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -268,6 +268,89 @@ enum PageLayout { M5(super::fw::m5::pool::PoolGeometry), } +/// A span of the lower pool region that one free-list backing is placed in +/// ([`mmu::Uat::reserve_lower_window`]). Giving one back may let a refused +/// placement fit ([`lower_pressure`]). +pub(crate) struct Window(mmu::LowerWindow); + +impl Window { + /// The span for backing of `size` bytes and its guard page. + pub(crate) fn reserve(uat: &mmu::Uat, size: usize) -> Result { + let span = size.checked_add(mmu::UAT_PGSZ).ok_or(EOVERFLOW)? as u64; + uat.reserve_lower_window(span).map(Self).map_err(|error| { + if error == ENOSPC { super::capacity::refused(super::capacity::Site::LowerVa) } else { error } + }) + } + /// A render pool's window for `blocks`. + pub(crate) fn render(uat: &mmu::Uat, blocks: usize) -> Result { + Self::reserve(uat, Self::render_bytes(blocks)?) + } + fn render_bytes(blocks: usize) -> Result { + blocks.checked_mul(FREE_LIST_BLOCK_SIZE).and_then(|bytes| bytes.checked_add(TABLE_SIZE)).ok_or(EOVERFLOW) + } + pub(crate) fn range(&self) -> core::ops::Range { + self.0.range() + } +} + +impl Drop for Window { + fn drop(&mut self) { + LOWER_FREED.fetch_add(1, Ordering::AcqRel); + } +} + +/// How a NEO GPU's lower dynamic range is split at boot ([`mmu::Uat::split_lower_window`]). +#[derive(Debug, PartialEq, Eq)] +pub(super) struct LowerSplit { + /// The band at the end of the range for the small lower objects bound to queue identities. + pub(super) fixed_bytes: u64, + /// Base render pool windows the rest holds while no owner computes. + pub(super) windows: u64, +} + +/// The small canonical lower objects that belong to hardware queue identities stay with them until +/// the firmware stops, past the queue that made them, so their band is the bound of what the QIDs +/// allow: the render pairs, each with two kick rings and a current and a prepared graph; the +/// retired bindings; and the compute QIDs render leaves (`kick::render_reserve`) with their kits. +/// Nothing in it depends on how many queues exist. The rest of `range` bytes is shared as it is +/// used: render windows at a context's first render, compute windows, and computing owners' +/// budgets ([`owner_lower_bytes`]). ENOSPC if not even one base render pool window (from the +/// GPU's cores and clusters) fits beside the band. +pub(super) fn split_lower( + range: u64, + qid_floor: usize, + active_cores: u32, + clusters: u32, + operand_bytes: usize, +) -> Result { + use super::queue::compute::KIT_LOWER_BYTES; + let qids = super::kick::QID_COUNT.checked_sub(qid_floor).ok_or(EINVAL)?; + let pairs = qids / 2; + let compute_qids = qids.saturating_sub(super::kick::render_reserve(0)); + let kit = KIT_LOWER_BYTES + operand_bytes + mmu::UAT_PGSZ; + // A written render kick ring stays with its published QID until the firmware stops, so the + // pairs bound those. shortcut: storage of a ring retired before it published is reused only by + // its VM or a closed one (`kick::RenderRings::take`), so each open VM may keep its own peak of + // it, which is not counted here; count it once that stock has a device-wide bound. + let fixed_bytes = (pairs * 2 * super::fw::kick::KICK_RING_SIZE + + (2 * pairs + super::runtime::RETIRED_BINDINGS) * super::queue::render::GRAPH_LOWER_BYTES + + compute_qids * kit) as u64; + let blocks = super::fw::render_rt::base_blocks(active_cores, clusters)?; + let window = (TABLE_SIZE + blocks * FREE_LIST_BLOCK_SIZE + mmu::UAT_PGSZ) as u64; + let windows = range.checked_sub(fixed_bytes).ok_or(ENOSPC)? / window; + if windows == 0 { + return Err(ENOSPC); + } + Ok(LowerSplit { fixed_bytes, windows }) +} + +/// A computing owner's small lower objects at most: its descriptor ring and spares, and a spare +/// kit. Taken from the band at its first compute SUBMIT and held until it closes. +pub(super) fn owner_lower_bytes(operand_bytes: usize) -> u64 { + use super::queue::compute::{reserve::RINGS, DESCRIPTOR_RING_LOWER_BYTES, KIT_LOWER_BYTES}; + ((1 + RINGS) * DESCRIPTOR_RING_LOWER_BYTES + KIT_LOWER_BYTES + operand_bytes + mmu::UAT_PGSZ) as u64 +} + /// Free-list backing is by far the largest user of the shared lower GPU VA /// window, and placing it populates every page before the window is searched. /// After a refused placement, builders waiting for capacity would allocate and @@ -328,11 +411,9 @@ pub(crate) struct Pages { /// The charge of an M5 backing sized by a client's request, released with it. It is the /// backing's only count: the backing itself is not counted as kernel memory. charge: Option, -} -impl Drop for Pages { - fn drop(&mut self) { - LOWER_FREED.fetch_add(1, Ordering::AcqRel); - } + /// A NEO compute backing's own window, given back after the backing is unmapped. A render + /// backing is placed in its pool's window instead ([`RenderPool`]). + _window: Option, } impl super::queue::compute::reserve::Capacity for Pages { fn fits(&self, required: ComputeCapacity) -> bool { @@ -349,25 +430,28 @@ impl super::queue::compute::reserve::Capacity for Pages { } impl Pages { + /// Compute backing in a window of its own, reserved before any page is allocated. fn new(alloc: &Allocator<'_>, blocks: usize, runs: RunLayout) -> Result { let size = TABLE_SIZE + blocks * FREE_LIST_BLOCK_SIZE; - let backing = place_lower(size, || { - alloc.lower( - size, - mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_SHARED_RW, - CpuMap::WriteCombined, - ) - })?; - Self::from_backing(backing, blocks, runs) + let window = place_lower(size, || Window::reserve(alloc.uat, size))?; + let backing = alloc.lower_in( + window.range(), + size, + mmu::UAT_PGSZ as u64, + mmu::PROT_GPU_SHARED_RW, + CpuMap::WriteCombined, + )?; + Self::from_backing(backing, blocks, runs, Some(window)) } - fn from_backing(mut backing: KernelObject, blocks: usize, runs: RunLayout) -> Result { + fn from_backing(mut backing: KernelObject, blocks: usize, runs: RunLayout, + window: Option) -> Result { let base = backing.gpu_va(); backing.initialize::(0, |tables| tables.init(base, blocks, runs))?; Ok(Self { backing, layout: PageLayout::Neo { blocks, runs }, charge: None, + _window: window, }) } /// Fresh compute backing at the admitted capacity, built off-lock, in the @@ -418,7 +502,7 @@ impl Pages { None => (alloc.lower(size, mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, CpuMap::WriteCombined)?, None), }; - let mut pages = Self { backing, layout: PageLayout::M5(geometry), charge }; + let mut pages = Self { backing, layout: PageLayout::M5(geometry), charge, _window: None }; pages.populate_m5()?; Ok(pages) } @@ -525,16 +609,6 @@ impl Pages { } } -/// What one render pool of the smallest size takes of the shared lower -/// window, with its guard. -pub(crate) const RENDER_POOL_SPAN: u64 = - (TABLE_SIZE + RENDER_BLOCKS * FREE_LIST_BLOCK_SIZE + mmu::UAT_PGSZ) as u64; - -// The A18 Pro's shared pool window holds the smallest render pool for every execution context. -const _: () = assert!( - crate::hw::t8140::dynamic::WIDE_LOWER.end - crate::hw::t8140::dynamic::WIDE_LOWER.start - >= crate::mmu::MAX_EXECUTION_CONTEXTS as u64 * RENDER_POOL_SPAN -); /// Pool-object identities are independent of recycled firmware IDs and VAs. static RENDER_POOL_SERIAL: AtomicU64 = AtomicU64::new(0); @@ -545,40 +619,44 @@ pub(crate) struct RenderBacking { _client: mmu::KernelMapping, _global: Option, pages: Pages, + /// A NEO pool's window, kept until this backing, also a vacated one still to be dropped, is + /// unmapped from it. + _window: Option>, } impl RenderBacking { fn into_pages(self) -> Pages { - let Self { _client, _global, pages } = self; + let Self { _client, _global, pages, _window } = self; drop(_client); drop(_global); pages } - /// Fresh populated backing, built without the device mutex. + /// Fresh populated backing in the pool's `window`, built without the device mutex. pub(crate) fn new( alloc: &Allocator<'_>, render_global: &mmu::Vm, client: &mmu::Vm, blocks: usize, + window: &Arc, ) -> Result { if blocks < RENDER_BLOCKS || blocks > PAGE_LIST_SIZE / (FREE_LIST_BLOCK_PAGES as usize * 8) { return Err(EINVAL); } let size = TABLE_SIZE + blocks * FREE_LIST_BLOCK_SIZE; - let (backing, [global, client]) = place_lower(size, || { - alloc.lower_with_aliases( - size, - mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_SHARED_RW, - CpuMap::WriteCombined, - [render_global, client], - ) - })?; - let pages = Pages::from_backing(backing, blocks, RunLayout::Render)?; + let (backing, [global, client]) = alloc.lower_with_aliases( + window.range(), + size, + mmu::UAT_PGSZ as u64, + mmu::PROT_GPU_SHARED_RW, + CpuMap::WriteCombined, + [render_global, client], + )?; + let pages = Pages::from_backing(backing, blocks, RunLayout::Render, None)?; Ok(Self { _client: client, _global: Some(global), pages, + _window: Some(window.clone()), }) } /// Fresh M5 backing, aliased into the client VM only: M5 firmware uses @@ -587,7 +665,7 @@ impl RenderBacking { geometry: super::fw::m5::pool::PoolGeometry) -> Result { let mut pages = Pages::m5(alloc, geometry, client.memory_client())?; let client = pages.map_client(client)?; - Ok(Self { _client: client, _global: None, pages }) + Ok(Self { _client: client, _global: None, pages, _window: None }) } } @@ -630,6 +708,9 @@ pub(crate) struct RenderPool { serial: u64, id: RenderId, layout: PageLayout, + /// The NEO pool's span of lower VA, reserved with its context: every backing, the first and + /// each re-armed one, is placed there, so arming never competes for VA. + window: Option>, } /// Keeps both a physical identity and its logical pool alive during use. @@ -660,17 +741,18 @@ impl RenderPool { client: &mmu::Vm, blocks: usize, reserved: Option<&Mutex>>, + window: &Arc, ) -> Result { let fresh = match reserved { Some(reserved) if reserved.lock().is_some() => None, _ => Some(RenderId::new(ids)?), }; - let backing = RenderBacking::new(alloc, render_global, client, blocks)?; + let backing = RenderBacking::new(alloc, render_global, client, blocks, window)?; let id = match fresh.or_else(|| reserved.and_then(|reserved| reserved.lock().take())) { Some(id) => id, None => RenderId::new(ids)?, }; - Self::with_backing(alloc, id, client, backing) + Self::with_backing(alloc, id, client, backing, window.clone()) } /// Explicit initial geometry; allocation policy remains with the caller. @@ -690,11 +772,11 @@ impl RenderPool { Ok(Self { storage, epoch: AtomicU64::new(0), client_residency: client.residency_gate(), client_vm: client.id(), control, state, served: AtomicBool::new(true), serial, id, - layout: PageLayout::M5(geometry) }) + layout: PageLayout::M5(geometry), window: None }) } fn with_backing(alloc: &Allocator<'_>, id: RenderId, client: &mmu::Vm, - backing: RenderBacking) -> Result { + backing: RenderBacking, window: Arc) -> Result { let layout = backing.pages.layout; let address = backing.pages.page_list_va(); let run_list_va = backing.pages.run_list_va(); @@ -746,6 +828,7 @@ impl RenderPool { serial, id, layout, + window: Some(window), }) } @@ -821,7 +904,8 @@ impl RenderPool { if !self.vacant() { return Ok(()); } - return self.rearm(RenderBacking::new(alloc, render_global, client, blocks)?); + let window = self.window.as_ref().ok_or(EINVAL)?; + return self.rearm(RenderBacking::new(alloc, render_global, client, blocks, window)?); } }; let mut backing = self.storage.backing.lock(); @@ -830,7 +914,7 @@ impl RenderPool { let fresh = if let Some(mut pages) = spare { pages.reset_for_client()?; let alias = pages.map_client(client)?; - RenderBacking { _client: alias, _global: None, pages } + RenderBacking { _client: alias, _global: None, pages, _window: None } } else { RenderBacking::m5(alloc, client, geometry)? }; @@ -1517,6 +1601,32 @@ impl RenderIds { mod capacity_tests { use super::*; + /// Each split of the lower dynamic range keeps the band for the queue-identity objects and room + /// for base render pool windows beside it, for GPU shapes that use it. + #[test] + fn lower_split_keeps_room_for_windows() { + use crate::hw::t8140::dynamic::{LOWER, WIDE_LOWER}; + // (range, QID floor, active cores, clusters, operand state bytes, band bytes, base windows) + for (range, floor, cores, clusters, operand, band, windows) in [ + (LOWER, 32, 20, 2, 0x44000, 124_125_184, 40), + (LOWER, 0, 20, 2, 0x44000, 159_252_480, 39), + (WIDE_LOWER, 0, 6, 1, 0x14000, 143_917_056, 67), + (WIDE_LOWER, 32, 40, 4, 0x80000, 135_430_144, 25), + ] { + let bytes = range.end - range.start; + let split = split_lower(bytes, floor, cores, clusters, operand).unwrap(); + assert_eq!(split, LowerSplit { fixed_bytes: band, windows }); + let blocks = super::super::fw::render_rt::base_blocks(cores, clusters).unwrap(); + let window = (TABLE_SIZE + blocks * FREE_LIST_BLOCK_SIZE + mmu::UAT_PGSZ) as u64; + assert!(split.windows * window + split.fixed_bytes <= bytes); + assert!((split.windows + 1) * window + split.fixed_bytes > bytes); + } + // A range without room for one window beside the band refuses the probe. + assert_eq!(split_lower(64 << 20, 32, 20, 2, 0x44000), Err(ENOSPC)); + // An M4 Pro owner: four descriptor rings and a kit. + assert_eq!(owner_lower_bytes(0x44000), 2_686_976); + } + #[test] fn rejected_pool_construction_returns_all_render_ids() { let ids = RenderIds::new().unwrap(); diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 520d0ef9077aa..3c99a1170c044 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -423,6 +423,8 @@ pub(crate) trait Backend: Send + Sync { /// Validate compute sizing without reserving a physical channel. Queued /// commands may wait on a host signal submitted after this ioctl returns. fn ensure_compute(&self, command: &super::command::Validated) -> Result; + /// Reserve the render pool window of a context that has none, at its render SUBMIT. + fn reserve_render_window(&self) -> Result { Ok(()) } fn render_scs_blocks(&self, pages: [u16; 2]) -> Result { if pages != [0; 2] { return Err(EINVAL); } Ok(super::fw::freelist::RENDER_BLOCKS) diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 9f51096513da0..ab86297b40966 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -714,7 +714,7 @@ impl Queue { mmu::PROT_FW_SHARED_RW, CpuMap::WriteCombined, )?; - let mut range = alloc.uat.kernel_lower_dynamic_range(); + let mut range = alloc.uat.kernel_lower_misc_range(); let (low, client) = loop { let low = high.alias_in( alloc.uat.kernel_lower_vm(), diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index ef929c124721f..50aa760a1cf49 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -2773,6 +2773,24 @@ impl Gpu { )?, GFP_KERNEL, )?; + let lower = uat.kernel_lower_dynamic_range(); + let split = freelist::split_lower( + lower.end - lower.start, + shared.variant.qid_floor, + shared.active_cores, + shared.clusters, + shared.operand_state.size, + )?; + uat.split_lower_window(split.fixed_bytes)?; + dev_info!( + dev.as_ref(), + "lower VA: {} MiB, {} MiB for queue-identity objects, room for {} base render pool windows \ + ({} KiB less per computing owner)\n", + (lower.end - lower.start) >> 20, + split.fixed_bytes >> 20, + split.windows, + freelist::owner_lower_bytes(shared.operand_state.size) >> 10, + ); // The firmware only samples the kernel lower root's top-level entries when it starts, so // everything it uses there must be mapped first. diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index 7904feb9d8569..9e162269be05f 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -468,13 +468,19 @@ impl Allocator<'_> { prot: mmu::Prot, cpu: CpuMap, ) -> Result { - self.object( - self.uat.kernel_lower_vm(), - Placement::In(self.uat.kernel_lower_dynamic_range(), align), - size, - prot, - cpu, - ) + self.lower_in(self.uat.kernel_lower_misc_range(), size, align, prot, cpu) + } + + /// [`Self::lower`] within `range`, such as a free-list backing's own window. + pub(crate) fn lower_in( + &self, + range: core::ops::Range, + size: usize, + align: u64, + prot: mmu::Prot, + cpu: CpuMap, + ) -> Result { + self.object(self.uat.kernel_lower_vm(), Placement::In(range, align), size, prot, cpu) } /// [`Self::lower`] write-combined backing that is not counted as kernel memory: the @@ -488,16 +494,17 @@ impl Allocator<'_> { KernelObject::with_object(gem::new_kernel_object_wc_user_charged(self.dev, size)?, size)? .placed( self.uat.kernel_lower_vm(), - Placement::In(self.uat.kernel_lower_dynamic_range(), align), + Placement::In(self.uat.kernel_lower_misc_range(), align), prot, ) } - /// Place fresh backing at one address in the canonical and both alias VMs. + /// Place fresh backing at one address within `range` in the canonical and both alias VMs. /// A client may retain mappings after their canonical reservation is freed. /// Retry only address collisions, keeping the same backing throughout. pub(crate) fn lower_with_aliases( &self, + range: core::ops::Range, size: usize, align: u64, prot: mmu::Prot, @@ -508,7 +515,7 @@ impl Allocator<'_> { return Err(EINVAL); } let mut object = self.backing(size, cpu)?; - let mut range = self.uat.kernel_lower_dynamic_range(); + let mut range = range; let mut searching = false; loop { // Keep ordinary best-fit placement on the uncontended path. A diff --git a/drivers/gpu/drm/asahi/g17/queue/admission.rs b/drivers/gpu/drm/asahi/g17/queue/admission.rs index d7900139886b8..04e135aa5b962 100644 --- a/drivers/gpu/drm/asahi/g17/queue/admission.rs +++ b/drivers/gpu/drm/asahi/g17/queue/admission.rs @@ -2114,13 +2114,6 @@ mod fault_capacity_tests { } } -impl Pool { - pub(crate) fn owner_active(&self, owner: u64) -> bool { - let state = self.state.lock(); - state.owners.iter().zip(state.refs.iter()).any(|(id, refs)| *id == owner && *refs != 0) - } -} - #[kunit_tests(asahi_g17_shared_render_depth)] mod shared_depth_tests { use super::*; diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 5c2ffbfd0d9b6..4b9bf6b489650 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -36,6 +36,12 @@ const _: () = assert!(retirement::IN_FLIGHT <= DESCRIPTORS && retirement::IN_FLIGHT <= RECORD_SLOTS); const GRAPH_SIZE: usize = 0x8000; const CONTEXT_SIZE: usize = 0x20000; +/// Lower VA of one compute queue's kit besides its operand state: the kick ring and the +/// context's low copy, each with its guard page. +pub(crate) const KIT_LOWER_BYTES: usize = + crate::g17::fw::kick::KICK_RING_SIZE + mmu::UAT_PGSZ + CONTEXT_SIZE + mmu::UAT_PGSZ; +/// Lower VA of one descriptor ring's alias ([`DescriptorRing`]). +pub(crate) const DESCRIPTOR_RING_LOWER_BYTES: usize = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; const RECORD_STRIDE: usize = 0x1000; const NATIVE_WAIT_OFFSET: usize = 0x900; const NATIVE_WAIT_STRIDE: usize = 0x60; @@ -156,7 +162,7 @@ impl DescriptorRing { )?; let low = object.alias_in( alloc.uat.kernel_lower_vm(), - alloc.uat.kernel_lower_dynamic_range(), + alloc.uat.kernel_lower_misc_range(), mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, )?; diff --git a/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs index c0b323b35aec2..ed1f45a15bfc5 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs @@ -16,7 +16,7 @@ use kernel::prelude::*; /// 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; +pub(crate) const RINGS: usize = crate::g17::pairs::COMPUTE_CHANNELS_MAX; /// Pool pages as a spare: what they can serve. pub(crate) trait Capacity { diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 2e0ce042ff18a..2b94b3c5bc8fc 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -670,6 +670,11 @@ impl crate::queue::Queue for Queue { for (publishers, room) in self.publishers.iter_mut().zip(room) { publishers.reserve(room)?; } + // The context's lower VA from its first render on, reserved before any command of the + // submission is queued: a full range refuses the submission, not a publication. + if room[Engine::Render.index()] != 0 { + self.backend.reserve_render_window()?; + } let mut guards = guards.drain_all(); let mut work_states = KVec::new(); let aggregate = if pending.len() > 1 { diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 0c92c7cab4e27..d9c785320f8d0 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -9,6 +9,9 @@ mod observation; pub(crate) use observation::Observed; mod dependencies; mod memory; + +/// Lower VA of one render graph's descriptor aliases ([`memory`]). +pub(crate) const GRAPH_LOWER_BYTES: usize = memory::TA_BYTES + memory::FRAGMENT_BYTES; pub(crate) mod parked; pub(super) mod publication; pub(crate) mod retirement; diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index 5a9392651614a..ac0abfda530ed 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -59,7 +59,7 @@ impl Aliases { vm: &mmu::Vm, source: core::ops::Range, ) -> Result { - let mut range = alloc.uat.kernel_lower_dynamic_range(); + let mut range = alloc.uat.kernel_lower_misc_range(); let size = (source.end - source.start) as u64; loop { // Descriptor aliases are read-only to GPU consumers; the canonical diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index ee4dd581eda10..56658581bc5f7 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -15,6 +15,7 @@ mod compute_exit; mod events; mod feed; mod render; +pub(super) use render::RETIRED_BINDINGS; pub(super) mod teardown; pub(super) mod traversal; @@ -259,10 +260,11 @@ impl Drop for ComputeSlot { /// 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, + /// Dropped after the spares: the context's lower band budget covers them until they are unmapped. + context: Arc, } impl OwnerReserve { @@ -3326,6 +3328,11 @@ impl Backend { if !lacks.any() && reserved { return Ok(()); } + // The owner's rings and kits come from its own share of the lower band, from its first + // compute SUBMIT on: refused here, never once it computes. + if !self.context.is_m5() { + self.context.reserve_compute_budget(&uat, super::freelist::owner_lower_bytes(self.shared.operand_state.size))?; + } let dev = self.shared.drm()?; let client = self.context.vm().memory_client(); let charged = super::object::Allocator { dev: &dev, uat: &uat, client }; @@ -4762,35 +4769,11 @@ impl Backend { admission.check() } - /// The shared lower window refuses free-list backing, or has no room for one - /// more render pool: idle render pools are worth giving back. Never on M5, - /// which places and reclaims its pools by identity. - fn lower_window_short(&self) -> bool { - if self.context.is_m5() { - return false; - } - if super::freelist::lower_pressure() { - return true; - } - let uat = { - let state = self.shared.state.lock(); - match (*state).as_deref() { - Some(firmware) => firmware.uat.clone(), - None => return false, - } - }; - // Off the device mutex: this takes the address space's lock. - uat.kernel_lower_vm() - .capacity(uat.kernel_lower_dynamic_range()) - .is_ok_and(|(_, largest)| largest < super::freelist::RENDER_POOL_SPAN) - } - /// Reclaim steps of a capacity wait that never sleep: observe consumed pool releases and, - /// under backing pressure, give idle pools back. + /// under backing pressure, give idle compute pools back. fn reclaim_capacity(&self, admission: &Admission<'_>, reclaim_backing: bool) -> Result { admission.check()?; let mut deferred = DeferredBatch::reclaim()?; - let pools = reclaim_backing && self.lower_window_short(); let result: Result = (|| { // A short reclaim transaction obeys the same session/epoch gate as // publication. Never keep this lease while sleeping for capacity. @@ -4807,10 +4790,8 @@ impl Backend { firmware.queues.observe_pool_releases(&firmware.init, &mut deferred)?; // Pool eviction addresses backing allocation pressure, not channel // occupancy. Normal idle expiry and the retained-pool cap still run - // in the event worker for either kind of admission wait. - if pools { - firmware.queues.reclaim_idle_render_pools(&firmware.init, &mut deferred)?; - } + // in the event worker for either kind of admission wait. A render pool's + // backing is placed in its own window, so vacating one frees no VA for others. if reclaim_backing && !firmware.render_control_backpressured() { let (published, _) = firmware.queues.vacate_idle_pools(&firmware.init, 0, now_ns(), 0)?; if published != 0 { firmware.primary.notify(super::MSG_CONTROL_NOTIFY)?; } diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 527f08debbeb9..9695aecb8899c 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -279,6 +279,15 @@ impl job::Backend for Backend { Ok(()) } + fn reserve_render_window(&self) -> Result { + // Every render SUBMIT asks: only a context without its window takes the device mutex. + if self.context.is_m5() || self.context.has_render_window() { + return Ok(()); + } + let uat = (*self.shared.state.lock()).as_deref().ok_or(ENODEV)?.uat.clone(); + self.context.reserve_render_window(&uat) + } + fn render_scs_blocks(&self, pages: [u16; 2]) -> Result { crate::g17::fw::render_rt::required_blocks( self.shared.active_cores, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render.rs b/drivers/gpu/drm/asahi/g17/runtime/render.rs index bd01806853549..4ffbcbe20f1f1 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render.rs @@ -72,6 +72,9 @@ pub(super) struct UnusedRenderSpare { _binding: Option, } +/// Displaced render bindings kept until their release; a rebind past them is refused. +pub(in crate::g17) const RETIRED_BINDINGS: usize = 128; + pub(super) struct RenderState { config: Config, entries: KVec>, @@ -109,7 +112,7 @@ impl RenderState { entries, pools: pools::Pools::new()?, grow: grow::Grow::new()?, - retired: KVec::with_capacity(128, GFP_KERNEL)?, + retired: KVec::with_capacity(RETIRED_BINDINGS, GFP_KERNEL)?, kept_graphs: KVec::new(), kept_pairs: KVec::new(), next_pm_generation: 1, @@ -1779,42 +1782,4 @@ impl Registry { views.iter().any(Option::is_some).then_some(views) }) } - - /// Give idle private backing to another ready client under capacity pressure. - /// Keep graph/QID/context ownership; the next use rearms the same pool after - /// its consumed release, exactly as eviction-driven reclaim does. - pub(super) fn reclaim_idle_render_pools( - &mut self, init: &crate::g17::initdata::InitData, deferred: &mut DeferredBatch, - ) -> Result { - let render = &mut self.render; - render.pools.observe(init)?; - for entry in render.entries.iter().flatten() { - if !deferred.render_backing_room() { break; } - let Some(pool) = entry.pool.as_ref() else { continue; }; - // None means this pool never acquired a firmware registration; - // otherwise require its exact final release to have been consumed. - if pool.vacant() || !render.pools.released(u32::from(pool.id()), pool.control_va()) - || self.admission.owner_active(entry.reservation.owner) { continue; } - // A sibling or replacement may be building off-lock before it has - // installed its pool reference. Its logical owner also excludes us. - let mut idle = true; - for other in render.entries.iter().flatten().filter(|other| { - other.reservation.owner == entry.reservation.owner - || other.pool.as_ref().is_some_and(|bound| Arc::ptr_eq(bound, pool)) - }) { - if other.constructing || other.growing || other.preparing.is_some() - || other.pending_error.is_some() || other.pending_timeout { - idle = false; - break; - } - if let Some(pair) = other.pair.as_ref() { - if !pair.idle_for_context(pair.context())? { idle = false; break; } - } - } - if idle { - if let Some(backing) = pool.vacate() { deferred.defer_render_backing(backing); } - } - } - Ok(()) - } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index d2ecfa19d7253..48bb70fa24483 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -373,12 +373,10 @@ impl Backend { Ok(()) } - /// Gives idle render backing back under capacity pressure. Returns whether - /// anything was returned, in which case the caller retries at once. + /// Observes consumed pool releases and gives idle compute pools back under capacity + /// pressure. Returns whether anything was returned, in which case the caller retries at once. fn reclaim_render_capacity(&self) -> Result { let mut deferred = DeferredBatch::reclaim()?; - // Idle pools go back only while the shared window is short. - let pools = self.lower_window_short(); let result: Result = (|| { let lease = self.shared.preparations.try_enter()?; let mut state = self.shared.state.lock(); @@ -392,9 +390,6 @@ impl Backend { return Ok(false); } firmware.queues.observe_pool_releases(&firmware.init, &mut deferred)?; - if pools { - firmware.queues.reclaim_idle_render_pools(&firmware.init, &mut deferred)?; - } let mut published = 0; if !firmware.render_control_backpressured() { (published, _) = firmware.queues.vacate_idle_pools( diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 279538b848e9c..14c6d9b7f95ff 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -1741,6 +1741,51 @@ impl TimestampMapping { /// An object mapping into a [`Vm`], which reserves the address range from use by other mappings. pub(crate) struct KernelMapping(ManuallyDrop>); +/// A NEO GPU's lower dynamic range once split ([`Uat::split_lower_window`]). Pool windows are +/// placed from its start upward; the small canonical lower objects from its end downward, in a +/// band that only grows: by the queue-identity objects at boot and by each computing owner's +/// budget ([`Uat::reserve_lower_budget`]). No window enters the band. +struct LowerLedger { + windows: mm::Allocator<(), ()>, + /// Where the band starts: windows end at or below it. + floor: u64, + /// Band bytes no budget holds (given back by closed owners), used before the band grows. + spare: u64, + window_bytes: u64, + /// Requests refused for lack of a contiguous hole while enough bytes were free. + refused_fragmented: u64, +} + +/// A span of the lower range below the band ([`Uat::reserve_lower_window`]) that only its owner +/// places into, in the kernel lower VM and at the same addresses in its aliases' VMs. Dropping it +/// gives the span back; the owner drops its mappings there first. +pub(crate) struct LowerWindow(mm::Node<(), ()>, Arc); + +impl LowerWindow { + pub(crate) fn range(&self) -> Range { + self.0.start()..self.0.start() + self.0.size() + } +} + +impl Drop for LowerWindow { + fn drop(&mut self) { + if let Some(ledger) = Option::as_mut(&mut *self.1.lower.lock()) { + ledger.window_bytes -= self.0.size(); + } + } +} + +/// A computing owner's share of the band ([`Uat::reserve_lower_budget`]), held until it closes. +pub(crate) struct LowerBudget(u64, Arc); + +impl Drop for LowerBudget { + fn drop(&mut self) { + if let Some(ledger) = Option::as_mut(&mut *self.1.lower.lock()) { + ledger.spare += self.0; + } + } +} + impl KernelMapping { /// Returns the IOVA base of this mapping pub(crate) fn iova(&self) -> u64 { @@ -2297,6 +2342,11 @@ struct UatInner { quirks: UatQuirks, /// No-map reserved regions holding firmware tables (`UatQuirks::reserved_tables`). reserved: Option>, + /// The lower dynamic range once split ([`Uat::split_lower_window`]). + #[pin] + lower: Mutex>, + /// Where its band of small objects starts ([`LowerLedger::floor`]); zero before the split. + lower_floor: AtomicU64, #[pin] shared: Mutex, #[pin] @@ -3909,6 +3959,8 @@ impl Uat { clean_poc: true, reserved: None, quirks: UatQuirks::DEFAULT, + lower <- new_mutex!(None, "lower_ledger"), + lower_floor: AtomicU64::new(0), handoff_flush <- pin_init::pin_init_array_from_fn(|i| { new_mutex!(HandoffFlush(&handoff.flush[i]), "handoff_flush") }), @@ -4373,6 +4425,94 @@ impl Uat { pool_window(self.is_m5(), self.inner.quirks.narrow_pool_window) } + /// Splits the lower dynamic range once, before any client: a band of `fixed_bytes` at its end + /// takes the small canonical lower objects bound to queue identities + /// ([`Self::kernel_lower_misc_range`]); windows ([`Self::reserve_lower_window`]) and computing + /// owners' budgets ([`Self::reserve_lower_budget`]) share the rest as they come. + pub(crate) fn split_lower_window(&self, fixed_bytes: u64) -> Result { + let range = self.kernel_lower_dynamic_range(); + let floor = range.end.checked_sub(fixed_bytes).filter(|&floor| floor > range.start).ok_or(EINVAL)?; + let mut lower = self.inner.lower.lock(); + if lower.is_some() { + return Err(EBUSY); + } + *lower = Some(LowerLedger { + windows: mm::Allocator::new(range.start, range.end - range.start, ())?, + floor, + spare: 0, + window_bytes: 0, + refused_fragmented: 0, + }); + self.inner.lower_floor.store(floor, Ordering::Release); + Ok(()) + } + + /// Where the small canonical lower objects go: the band at the end of the lower dynamic range + /// once it is split ([`Self::split_lower_window`]), all of it before. The band only grows. + pub(crate) fn kernel_lower_misc_range(&self) -> Range { + let range = self.kernel_lower_dynamic_range(); + match self.inner.lower_floor.load(Ordering::Acquire) { + 0 => range, + floor => floor..range.end, + } + } + + /// Reserves `size` bytes below the band for one owner, lowest hole first, without mapping + /// anything: ENOSPC when no hole is left. Nothing else is placed there while the window lives. + pub(crate) fn reserve_lower_window(&self, size: u64) -> Result { + if size == 0 || size % UAT_PGSZ as u64 != 0 { + return Err(EINVAL); + } + let start = self.kernel_lower_dynamic_range().start; + let mut lower = self.inner.lower.lock(); + let ledger = Option::as_mut(&mut *lower).ok_or(ENODEV)?; + let floor = ledger.floor; + match ledger.windows.insert_node_in_range((), size, UAT_PGSZ as u64, 0, start, floor, mm::InsertMode::Low) { + Ok(node) => { + ledger.window_bytes += size; + Ok(LowerWindow(node, self.inner.clone())) + } + Err(error) => { + if floor - start - ledger.window_bytes >= size { + ledger.refused_fragmented += 1; + } + Err(error) + } + } + } + + /// Takes `bytes` of the band for a computing owner's small objects, growing the band down into + /// space no window holds: ENOSPC when a window sits there or the range is used up. Given back + /// to the band (not to windows) when dropped. + pub(crate) fn reserve_lower_budget(&self, bytes: u64) -> Result { + let start = self.kernel_lower_dynamic_range().start; + let mut lower = self.inner.lower.lock(); + let ledger = Option::as_mut(&mut *lower).ok_or(ENODEV)?; + if ledger.spare >= bytes { + ledger.spare -= bytes; + return Ok(LowerBudget(bytes, self.inner.clone())); + } + let floor = ledger.floor.checked_sub(bytes - ledger.spare).filter(|&floor| floor >= start).ok_or(ENOSPC)?; + if ledger.windows.first_overlap(floor..ledger.floor)?.is_some() { + if floor - start >= ledger.window_bytes { + ledger.refused_fragmented += 1; + } + return Err(ENOSPC); + } + ledger.spare = 0; + ledger.floor = floor; + self.inner.lower_floor.store(floor, Ordering::Release); + Ok(LowerBudget(bytes, self.inner.clone())) + } + + /// The split's state for the capacity snapshot: band start, spare band bytes, window bytes and + /// fragmentation refusals. + pub(crate) fn lower_ledger(&self) -> Option<(u64, u64, u64, u64)> { + self.inner.lower.lock().as_ref().map(|ledger| { + (ledger.floor, ledger.spare, ledger.window_bytes, ledger.refused_fragmented) + }) + } + /// Where client VMs of this UAT place their private aliases ([`Vm::client_private_range`]). pub(crate) fn client_private_range(&self) -> Range { client_private_range(self.is_m5(), self.inner.quirks.narrow_pool_window) @@ -4539,6 +4679,8 @@ impl Uat { clean_poc: quirks.clean_tables, quirks, reserved, + lower <- new_mutex!(None, "lower_ledger"), + lower_floor: AtomicU64::new(0), handoff_flush <- pin_init::pin_init_array_from_fn(|i| { new_mutex!(HandoffFlush(&handoff.flush[i]), "handoff_flush") }), diff --git a/tools/asahi/g17-lower-window-tests.py b/tools/asahi/g17-lower-window-tests.py new file mode 100755 index 0000000000000..c6fbf359bcd92 --- /dev/null +++ b/tools/asahi/g17-lower-window-tests.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""A NEO render pool owns a window of the lower dynamic range from its context's first render on. + +- G17 boot splits the range (`Uat::split_lower_window`) by `freelist::split_lower` into a band for the + queue-identity objects at its end and windows below; admission and QUEUE_LIMITS keep the variant's + queue limit (no count derived from windows); +- windows are placed lowest first below the band's floor, never in it; a computing owner's budget + grows the band only into space no window holds; +- QUEUE_CREATE reserves nothing; a computing owner takes its band budget at its first compute + provisioning (`provision_backing`) and keeps it; +- QUEUE_CREATE reserves no window; the first render SUBMIT does (`Backend::reserve_render_window`, + before anything is queued), and a context that holds one keeps it: it is never replaced, and the + pool size cannot change once it exists; +- every NEO render backing, the first and each re-armed one, is placed in its pool's window, and the + backing keeps the window until it is unmapped; +- a compute pool reserves its window before allocating pages; +- the small canonical lower objects are placed in `kernel_lower_misc_range`, never the whole range. + +--mutation submit-unreserved / late-reserve / window-replaced / blocks-after-window / count-cap / +rearm-anywhere / pool-drops-window / pages-before-window / misc-in-pools inject each fault and must +be caught. +""" +import argparse +import re +import sys +from pathlib import Path + +ASAHI = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi' +FILES = ['g17/mod.rs', 'g17/runtime.rs', 'g17/freelist.rs', 'g17/object.rs', 'g17/context.rs', 'g17/kick.rs', + 'g17/queue/mod.rs', 'g17/queue/compute.rs', 'g17/queue/render/memory.rs', 'g17/runtime/backend.rs', 'mmu.rs'] +MUTATIONS = ['submit-unreserved', 'late-reserve', 'window-replaced', 'blocks-after-window', 'count-cap', + 'rearm-anywhere', 'pool-drops-window', 'pages-before-window', 'misc-in-pools', 'window-in-band', + 'band-over-window', 'create-reserves', 'unbudgeted-owner', 'budget-replaced'] +RESERVE = 'self.backend.reserve_render_window()?;' + + +def sources(mutation): + files = {name: (ASAHI / name).read_text() for name in FILES} + + def sub(name, old, new): + assert old in files[name], (mutation, name, old) + files[name] = files[name].replace(old, new, 1) + + if mutation == 'submit-unreserved': + sub('g17/queue/mod.rs', RESERVE, '') + elif mutation == 'late-reserve': + sub('g17/queue/mod.rs', RESERVE, '') + sub('g17/queue/mod.rs', ' self.prune_frontier(other);\n', + ' self.prune_frontier(other);\n if engine == Engine::Render { self.backend.reserve_render_window()?; }\n') + elif mutation == 'window-replaced': + sub('g17/context.rs', ' if window.is_none() {\n *window = Some(', + ' if true {\n *window = Some(') + elif mutation == 'blocks-after-window': + sub('g17/context.rs', ' || self.render_window.lock().is_some() {', ' {') + elif mutation == 'count-cap': + sub('g17/mod.rs', ' max_queues: kick::queue_limit(self.shared.variant.qid_floor),', + ' max_queues: split_windows(&self.shared),') + elif mutation == 'rearm-anywhere': + sub('g17/freelist.rs', ' let (backing, [global, client]) = alloc.lower_with_aliases(\n window.range(),', + ' let (backing, [global, client]) = alloc.lower_with_aliases(\n alloc.uat.kernel_lower_dynamic_range(),') + elif mutation == 'pool-drops-window': + sub('g17/freelist.rs', ' _window: Some(window.clone()),', ' _window: None,') + elif mutation == 'pages-before-window': + sub('g17/freelist.rs', ' let window = place_lower(size, || Window::reserve(alloc.uat, size))?;\n' + ' let backing = alloc.lower_in(\n window.range(),', + ' let backing = alloc.lower_in(\n alloc.uat.kernel_lower_dynamic_range(),') + elif mutation == 'window-in-band': + sub('mmu.rs', '(), size, UAT_PGSZ as u64, 0, start, floor, mm::InsertMode::Low)', + '(), size, UAT_PGSZ as u64, 0, start, self.kernel_lower_dynamic_range().end, mm::InsertMode::Low)') + elif mutation == 'band-over-window': + sub('mmu.rs', ' if ledger.windows.first_overlap(floor..ledger.floor)?.is_some() {', ' if false {') + elif mutation == 'create-reserves': + sub('g17/runtime.rs', ' let context = Arc::new(\n Context::new(', + ' let _budget = uat.reserve_lower_budget(1)?;\n let context = Arc::new(\n Context::new(') + elif mutation == 'unbudgeted-owner': + sub('g17/runtime.rs', ' self.context.reserve_compute_budget(', ' let _ = (') + elif mutation == 'budget-replaced': + sub('g17/context.rs', ' if budget.is_none() {\n *budget = Some(', ' if true {\n *budget = Some(') + elif mutation == 'misc-in-pools': + sub('g17/kick.rs', 'alloc.uat.kernel_lower_misc_range()', 'alloc.uat.kernel_lower_dynamic_range()') + return files + + +def strip(text): + return '\n'.join(line.split('//')[0] for line in text.split('\n')) + + +def fn_body(code, name): + """The text of `fn name` up to the next `fn` at the same indent.""" + m = re.search(r'\n([ \t]*)(pub(\([^)]*\))? )?fn ' + name + r'\b', code) + if not m: + return None + end = re.search(r'\n' + m.group(1) + r'(pub(\([^)]*\))? )?(const )?fn ', code[m.end():]) + return code[m.end():m.end() + end.start()] if end else code[m.end():] + + +def check(files): + failures = [] + code = {name: strip(text) for name, text in files.items()} + + def fail(name, what): + failures.append(f'FAIL line 0: {name}: {what}') + + boot = code['g17/mod.rs'] + if 'freelist::split_lower(' not in boot or 'uat.split_lower_window(split.fixed_bytes)?' not in boot: + fail('g17/mod.rs', 'boot does not split the lower range by split_lower') + if 'max_queues: kick::queue_limit(self.shared.variant.qid_floor),' not in (fn_body(boot, 'queue_limits') or ''): + fail('g17/mod.rs', 'QUEUE_LIMITS is not the variant\'s queue limit') + if 'kick::queue_limit(variant.qid_floor), queues, renders' not in code['g17/runtime.rs']: + fail('g17/runtime.rs', 'admission is not the variant\'s queue limit') + + runtime = code['g17/runtime.rs'] + create = runtime[runtime.find('pub(super) fn new('):] + create = create[:create.find('Context::new(')] + if 'Window::render(' in create or 'reserve_lower_budget(' in create or 'reserve_compute_budget(' in create: + fail('g17/runtime.rs', 'QUEUE_CREATE reserves lower VA') + backing = fn_body(runtime, 'provision_backing') or '' + budget, ring = backing.find('self.context.reserve_compute_budget('), backing.find('DescriptorRing::new(') + if budget < 0 or ring < 0 or budget > ring: + fail('g17/runtime.rs', 'an owner\'s compute objects are allocated without its band budget') + if runtime.count('reserve_compute_budget(') != 1: + fail('g17/runtime.rs', 'a band budget is taken outside the first compute provisioning') + budget_fn = fn_body(code['g17/context.rs'], 'reserve_compute_budget') or '' + guard, take = budget_fn.find('if budget.is_none()'), budget_fn.find('reserve_lower_budget(') + if guard < 0 or take < 0 or guard > take: + fail('g17/context.rs', 'an owner\'s band budget can be replaced') + window_fn = fn_body(code['mmu.rs'], 'reserve_lower_window') or '' + if 'start, floor, mm::InsertMode::Low' not in window_fn: + fail('mmu.rs', 'a window can be placed in the band of small objects') + band_fn = fn_body(code['mmu.rs'], 'reserve_lower_budget') or '' + if 'ledger.windows.first_overlap(floor..ledger.floor)?.is_some()' not in band_fn: + fail('mmu.rs', 'the band can grow over a window') + + submit = fn_body(code['g17/queue/mod.rs'], 'submit') or '' + call, first = submit.find('self.backend.reserve_render_window()?'), submit.find('self.enqueue(') + if call < 0 or 'room[Engine::Render.index()] != 0' not in submit: + fail('g17/queue/mod.rs', 'a render SUBMIT does not reserve its context\'s window') + elif first < 0 or call > first: + fail('g17/queue/mod.rs', 'the window is reserved after the SUBMIT started to queue') + if 'reserve_render_window' in (fn_body(code['g17/queue/mod.rs'], 'enqueue') or ''): + fail('g17/queue/mod.rs', 'the window is reserved per command, after earlier ones were queued') + backend = fn_body(code['g17/runtime/backend.rs'], 'reserve_render_window') or '' + if 'self.context.reserve_render_window(' not in backend: + fail('g17/runtime/backend.rs', 'the G17 backend does not reserve the window') + + context = code['g17/context.rs'] + reserve = fn_body(context, 'reserve_render_window') or '' + guard, store = reserve.find('if window.is_none()'), reserve.find('Window::render(') + if guard < 0 or store < 0 or guard > store: + fail('g17/context.rs', 'a context\'s window can be replaced') + if 'self.render_window.lock().is_some()' not in (fn_body(context, 'reserve_render_blocks') or ''): + fail('g17/context.rs', 'the pool size can change after its window is reserved') + + freelist = code['g17/freelist.rs'] + render_new = fn_body(freelist[freelist.find('impl RenderBacking'):], 'new') or '' + if 'lower_with_aliases(\n window.range(),' not in render_new: + fail('g17/freelist.rs', 'a render backing is not placed in its pool\'s window') + if '_window: Some(window.clone()),' not in render_new: + fail('g17/freelist.rs', 'a render backing does not keep its window until it is unmapped') + if 'self.window.as_ref()' not in (fn_body(freelist, 'ensure_backing') or ''): + fail('g17/freelist.rs', 'a re-arm does not place in the pool\'s window') + pages = fn_body(freelist[freelist.find('impl Pages {'):], 'new') or '' + window, alloc = pages.find('Window::reserve('), pages.find('alloc.lower_in(') + if window < 0 or alloc < 0 or window > alloc or 'window.range()' not in pages: + fail('g17/freelist.rs', 'a compute pool allocates pages before, or outside, its window') + + for name in ('g17/kick.rs', 'g17/queue/compute.rs', 'g17/queue/render/memory.rs'): + if 'kernel_lower_dynamic_range()' in code[name]: + fail(name, 'a small lower object is placed over the whole range, pool windows included') + if 'kernel_lower_misc_range()' not in (fn_body(code['g17/object.rs'], 'lower') or ''): + fail('g17/object.rs', 'Allocator::lower places over the whole range') + if 'lower_floor' not in (fn_body(code['mmu.rs'], 'kernel_lower_misc_range') or ''): + fail('mmu.rs', 'the misc range does not follow the split') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=MUTATIONS) + args = parser.parse_args() + failures = check(sources(args.mutation)) + for f in failures: + print(f) + if failures: + sys.exit(1) + print('ok: a NEO render pool places every backing in its context\'s window, reserved at the first render SUBMIT and kept') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index dabfe40fbe655..e4022f3d95e99 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -402,7 +402,7 @@ def shared_alias_tests(root, source): let dev=Device {state:state.clone()};let uat=Uat {lower:Vm {id:0,state:state.clone()}}; let first=Vm {id:1,state:state.clone()};let second=Vm {id:2,state:state.clone()}; let alloc=Allocator {dev:&dev,uat:&uat}; - let result=alloc.lower_with_aliases(size,16,3,CpuMap::WriteCombined,[&first,&second]); + let result=alloc.lower_with_aliases(uat.kernel_lower_dynamic_range(),size,16,3,CpuMap::WriteCombined,[&first,&second]); match (expected,result) { (Ok(address),Ok((object,aliases)))=>{ assert_eq!(object.mapping.as_ref().unwrap().iova(),address); @@ -430,7 +430,7 @@ def shared_alias_tests(root, source): let dev=Device {state:state.clone()};let uat=Uat {lower:Vm {id:0,state:state.clone()}}; let first=Vm {id:1,state:state.clone()};let second=Vm {id:2,state:state.clone()}; let alloc=Allocator {dev:&dev,uat:&uat}; - match alloc.lower_with_aliases(32,16,3,CpuMap::WriteCombined,[&first,&second]) { + match alloc.lower_with_aliases(uat.kernel_lower_dynamic_range(),32,16,3,CpuMap::WriteCombined,[&first,&second]) { Ok((object,aliases))=>{ assert!(available,"allocator found a false common hole"); let address=object.mapping.as_ref().unwrap().iova();assert_eq!(address%16,0);let page=address/16;assert!(page<4); diff --git a/tools/asahi/g17-shared-pool-tests.py b/tools/asahi/g17-shared-pool-tests.py deleted file mode 100644 index 64181543ea5bc..0000000000000 --- a/tools/asahi/g17-shared-pool-tests.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python3 -# SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Compile production pressure reclaim with mock firmware/mapping boundaries. - -The production eligibility loop must retain backing until release consumption, -exclude every borrower and defer mapping destruction until outside the lock. -""" -from pathlib import Path -import os -import subprocess -import tempfile - -ROOT = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' - - -def item(source, signature): - start = source.index(signature) - begin = source.index('{', start) - depth, end = 1, begin + 1 - while depth: - depth += (source[end] == '{') - (source[end] == '}') - end += 1 - return source[start:end] - - -def fixture(): - method = item((ROOT / 'runtime/render.rs').read_text(), 'pub(super) fn reclaim_idle_render_pools(').replace('pub(super) ', '') - return r''' -#![allow(dead_code)] -use std::sync::{Arc, Mutex, atomic::{AtomicUsize, Ordering}}; -type Result = std::result::Result; -const EIO:i32=-5; -mod g17 {pub mod initdata {pub struct InitData;}} -struct Backing(Arc); -impl Backing {fn new(used:&Arc)->Self {used.fetch_add(1,Ordering::SeqCst);Self(used.clone())}} -impl Drop for Backing {fn drop(&mut self) {self.0.fetch_sub(1,Ordering::SeqCst);}} -struct Pool {id:u16, backing:Mutex>} -impl Pool { - fn id(&self)->u16 {self.id} - fn control_va(&self)->u64 {0} - fn vacant(&self)->bool {self.backing.lock().unwrap().is_none()} - fn vacate(&self)->Option {self.backing.lock().unwrap().take()} -} -struct Context; -struct Pair {idle:Result} -impl Pair {fn context(&self)->&Context {&Context} fn idle_for_context(&self,_:&Context)->Result{self.idle}} -struct Reservation {owner:u64} -struct Entry {reservation:Reservation,pool:Option>,pair:Option,constructing:bool,growing:bool,preparing:Option<()>,pending_error:Option<()>,pending_timeout:bool} -struct Pools {consumed:bool,registered:bool} -impl Pools {fn observe(&mut self,_:&g17::initdata::InitData)->Result{Ok(())} fn released(&self,_:u32,_:u64)->bool{!self.registered||self.consumed}} -struct Render {entries:Vec>,pools:Pools} -struct Admission {active:bool} -impl Admission {fn owner_active(&self,_:u64)->bool {self.active}} -struct Registry {render:Render,admission:Admission} -struct DeferredBatch {backing:Vec,cap:usize} -impl DeferredBatch { - fn render_backing_room(&self)->bool{self.backing.len(),count:usize)->Registry { - let entries=(0..count).map(|id|Some(Entry { - reservation:Reservation{owner:id as u64+1}, - pool:Some(Arc::new(Pool{id:id as u16,backing:Mutex::new(Some(Backing::new(used)))})), - pair:Some(Pair{idle:Ok(true)}),constructing:false,growing:false,preparing:None,pending_error:None,pending_timeout:false, - })).collect(); - Registry {render:Render{entries,pools:Pools{consumed:true,registered:true}},admission:Admission{active:false}} -} -fn main(){ - let used=Arc::new(AtomicUsize::new(0)); - for guard in 0..10 { - let mut registry=state(&used,1); - let mut deferred=DeferredBatch{backing:vec![],cap:4}; - match guard { - 0=>registry.render.pools.consumed=false, - 1=>registry.admission.active=true, - 2=>registry.render.entries[0].as_mut().unwrap().constructing=true, - 3=>registry.render.entries[0].as_mut().unwrap().growing=true, - 4=>registry.render.entries[0].as_mut().unwrap().preparing=Some(()), - 5=>registry.render.entries[0].as_mut().unwrap().pending_error=Some(()), - 6=>registry.render.entries[0].as_mut().unwrap().pending_timeout=true, - 7=>registry.render.entries[0].as_mut().unwrap().pair.as_mut().unwrap().idle=Ok(false), - 8=>deferred.cap=0, - 9=>registry.render.entries.push(Some(Entry{reservation:Reservation{owner:1},pool:None,pair:None,constructing:true,growing:false,preparing:None,pending_error:None,pending_timeout:false})), - _=>unreachable!(), - } - registry.reclaim_idle_render_pools(&g17::initdata::InitData,&mut deferred).unwrap(); - assert!(deferred.backing.is_empty(),"guard {} must retain pool backing",guard); - assert!(!registry.render.entries[0].as_ref().unwrap().pool.as_ref().unwrap().vacant()); - assert_eq!(used.load(Ordering::SeqCst),1); - drop(registry);assert_eq!(used.load(Ordering::SeqCst),0); - } - for _ in 0..512 { - let mut registry=state(&used,4); - let mut deferred=DeferredBatch{backing:vec![],cap:4}; - registry.reclaim_idle_render_pools(&g17::initdata::InitData,&mut deferred).unwrap(); - assert_eq!(deferred.backing.len(),4); - assert_eq!(used.load(Ordering::SeqCst),4,"mapping destruction must remain off-lock"); - registry.reclaim_idle_render_pools(&g17::initdata::InitData,&mut deferred).unwrap(); - assert_eq!(deferred.backing.len(),4,"vacant pools cannot double-return"); - deferred.finish();assert_eq!(used.load(Ordering::SeqCst),0); - } - let mut unregistered=state(&used,1); - unregistered.render.pools.registered=false;unregistered.render.pools.consumed=false; - let mut deferred=DeferredBatch{backing:vec![],cap:4}; - unregistered.reclaim_idle_render_pools(&g17::initdata::InitData,&mut deferred).unwrap(); - assert_eq!(deferred.backing.len(),1,"never-registered backing has no firmware reference"); - deferred.finish();assert_eq!(used.load(Ordering::SeqCst),0); - println!("PASS 512 four-client pool-sharing cycles and ten witness/borrower/collector guards; backing returns to baseline off-lock"); -} -''' - - -def callers(): - """The reclaim only returns backing its batch has room for: both capacity - waits must hand it the batch that has that room.""" - runtime = (ROOT / 'runtime.rs').read_text() - submit = (ROOT / 'runtime/render/submit.rs').read_text() - room = item(runtime, ' fn reclaim() -> Result') - assert 'batch.render = KVVec::with_capacity(crate::hw::t8140::queues::RENDER_SLOTS' in room, room - for text, signature in [(runtime, ' fn reclaim_capacity('), (submit, ' fn reclaim_render_capacity(')]: - body = item(text, signature) - assert 'reclaim_idle_render_pools(' in body, signature - assert 'DeferredBatch::reclaim()?' in body and 'DeferredBatch::publication()' not in body, signature - assert 'self.lower_window_short()' in body and 'if pools {' in body, signature - assert 'self.render.len() < self.render.capacity()' in item(runtime, ' pub(super) fn render_backing_room('), 'room rule' - short = item(runtime, ' fn lower_window_short(') - assert 'lower_pressure()' in short and 'RENDER_POOL_SPAN' in short and 'is_m5()' in short, short - print('PASS both capacity waits give the reclaim a batch with room for render pool backing, while the window is short') - - -def main(): - callers() - source = fixture() - mutations = [('fixed', source), - ('ignore-release-consumption', source.replace('!render.pools.released(u32::from(pool.id()), pool.control_va())', 'false')), - ('ignore-admission-borrower', source.replace('self.admission.owner_active(entry.reservation.owner)', 'false')), - ('ignore-constructor', source.replace('other.constructing', 'false'))] - with tempfile.TemporaryDirectory(prefix='g17-shared-pools-') as tmp: - for name, code in mutations: - path = Path(tmp) / (name + '.rs') - binary = path.with_suffix('') - path.write_text(code) - subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), '-o', str(binary)], check=True) - result = subprocess.run([str(binary)], capture_output=True, text=True) - if name == 'fixed': - assert result.returncode == 0, result.stderr - print(result.stdout.strip()) - else: - assert result.returncode != 0 and 'must retain pool backing' in result.stderr, result.stderr - print('PASS negative control:', name) - - -if __name__ == '__main__': - main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index bf0885209d9e6..dc406d576bfa3 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -610,10 +610,14 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('recovery-state-eio', 'drop-generation-check', 'wrong-j813-pipe'), []), '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', 'uncharged-compute', 'charged-kit'], []), + 'g17-lower-window-tests.py': [([], PASS)] + mutations( + '--mutation', ['submit-unreserved', 'late-reserve', 'window-replaced', 'blocks-after-window', 'count-cap', + 'rearm-anywhere', 'pool-drops-window', 'pages-before-window', 'misc-in-pools', + 'window-in-band', 'band-over-window', 'create-reserves', 'unbudgeted-owner', + 'budget-replaced'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)], From b83c328b85c290db4b41e93cb76e45822eb793f7 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Wed, 2 Dec 2026 14:47:21 -0300 Subject: [PATCH 08/10] drm/asahi: g17: re-arm a vacated render pool at SUBMIT, not at publication Under memory pressure, vacate_evicted_render_pools() gives back the render pool backing of a client whose VM pressure reclaim evicted while idle (b138b1c78a0e). On NEO, the next publication that needed the pool re-armed it with fresh backing, in the scheduler's worker. A worker has no memory cgroup, so those pages were charged to the root cgroup: a client's MemoryMax did not bound them, and the OOM killer and systemd-oomd could not see them in the client's cgroup. Evict, vacate and re-arm repeated under pressure, filling backing in the worker far faster than the vacated backing was freed. Re-arm in the client's SUBMIT instead. Queue::enqueue() calls the new Backend::provision_render() for every render command before it queues anything; on G17 it re-arms the context's pool if it is vacant, under client.charging() and with a preparation lease, so the pages go to the client's cgroup and a refusal (ENOMEM at the cgroup's limit) is this SUBMIT's. The backing goes in the context's own window of lower VA, so the re-arm takes no VA from other clients; while the vacated backing is still being unmapped from that window, the re-arm returns EAGAIN and libdrm retries. The command's VmJobGuard holds the VM's residency lease from before enqueue until the job is dropped. While a lease is held, pressure reclaim does not evict the VM and the residency gate does not report it evicted, so vacate_evicted_render_pools() cannot vacate the pool again before the job is published. Its other loop vacates only the pools of kept graphs, which are graphs of torn-down contexts. Publication (Context::render_pool(), build_render_pair()) therefore only takes the pool; a vacant one there is a broken invariant, logged once and failed with EIO, never re-armed in the worker. Unchanged: a context's first pool is still built at its first publication, and M5 pools are still armed by the pair that pins them. g17-render-rearm-submit-tests checks the SUBMIT call and its order, the charge and the lease check, and that publication no longer re-arms on NEO, with a mutation for each. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context.rs | 34 ++++- drivers/gpu/drm/asahi/g17/job.rs | 3 + drivers/gpu/drm/asahi/g17/queue/mod.rs | 3 + drivers/gpu/drm/asahi/g17/runtime/backend.rs | 5 + .../drm/asahi/g17/runtime/render/prepare.rs | 45 +++++- tools/asahi/g17-render-rearm-submit-tests.py | 137 ++++++++++++++++++ tools/asahi/run-host-tests.py | 3 + 7 files changed, 220 insertions(+), 10 deletions(-) create mode 100755 tools/asahi/g17-render-rearm-submit-tests.py diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 02fa70868320d..9e1d547aeca09 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -765,10 +765,13 @@ impl Context { let mut render = self.render.lock(); if let Some(pool) = &*render { if pool.fits(plan.as_ref().map(|p| p.geometry)) { - // A pool vacated under memory pressure is re-armed before reuse. - // M5 backing is installed by the pair that pins the pool. - if !alloc.uat.is_m5() { - pool.ensure_backing(alloc, render_global, self.vm())?; + // A pool vacated under memory pressure was re-armed by this context's SUBMIT + // ([`Self::rearm_render_pool`]), and the job's residency lease has kept it armed + // since: publication only takes it. M5 backing is installed by the pair that pins + // the pool. + if !alloc.uat.is_m5() && pool.vacant() { + kernel::pr_warn_once!("G17: render pool vacant at publication: not re-armed at SUBMIT\n"); + return Err(EIO); } return Ok(pool.clone()); } @@ -801,6 +804,29 @@ impl Context { drop(previous); Ok(pool) } + /// Re-arms this context's NEO render pool if pressure reclaim vacated it, for a SUBMIT of render + /// work: the caller runs this in the client's ioctl, under the client's memory cgroup, so a + /// refusal (ENOMEM at its limit, ENOSPC without lower kernel VA) is that SUBMIT's. It holds the + /// job's residency lease, which keeps the VM from being evicted, so + /// `vacate_evicted_render_pools` cannot vacate the pool again before the job is published. + /// A context without a pool yet gets one at its first publication ([`Self::render_pool`]); M5 + /// backing is installed by the pair that pins the pool. + pub(crate) fn rearm_render_pool(&self, alloc: &Allocator<'_>, render_global: &Vm) -> Result { + if alloc.uat.is_m5() { + return Ok(()); + } + let pool = self.render.lock().clone(); + match pool { + Some(pool) if pool.vacant() => pool.ensure_backing(alloc, render_global, self.vm()), + _ => Ok(()), + } + } + + /// Whether this context has a render pool that pressure reclaim vacated. + pub(crate) fn render_pool_vacant(&self) -> bool { + self.render.lock().as_ref().is_some_and(|pool| pool.vacant()) + } + /// Drops the pool once its free-list release is consumed and the closed /// scheduler is detached. Installed compute bindings may retain the /// context itself until replacement; they never use the render pool. diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 3c99a1170c044..972f7afccdfdf 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -425,6 +425,9 @@ pub(crate) trait Backend: Send + Sync { fn ensure_compute(&self, command: &super::command::Validated) -> Result; /// Reserve the render pool window of a context that has none, at its render SUBMIT. fn reserve_render_window(&self) -> Result { Ok(()) } + /// Allocate what a render command's publication would need and its client's earlier + /// publications gave back under memory pressure, so a refusal is this SUBMIT's. + fn provision_render(&self) -> Result { Ok(()) } fn render_scs_blocks(&self, pages: [u16; 2]) -> Result { if pages != [0; 2] { return Err(EINVAL); } Ok(super::fw::freelist::RENDER_BLOCKS) diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 2b94b3c5bc8fc..58203d1561b5f 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -264,6 +264,9 @@ impl Queue { if blocks > self.context.render_blocks() { return Err(EINVAL); } + // `guard` holds the VM's residency lease, so what this re-arms stays armed until + // the command is published, and a refusal comes back before anything is queued. + self.backend.provision_render()?; } self.prune_frontier(index); self.prune_frontier(other); diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 9695aecb8899c..070fb9c095621 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -305,6 +305,11 @@ impl job::Backend for Backend { self.compute_capacity(command).and_then(|required| self.provision_compute(required)) } + fn provision_render(&self) -> Result { + // A render pool that pressure reclaim vacated is re-armed here, not at publication. + self.provision_render_pool() + } + fn fail_vm(&self, error: Error) { self.context.status().record(error); let mut deferred = match DeferredBatch::worker() { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 83827ee24d175..0c81c132b6f84 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -205,6 +205,39 @@ impl super::super::Backend { } } + /// Re-arms this context's render pool for a SUBMIT of render work, if pressure reclaim + /// vacated it: in the client's ioctl and under its memory cgroup, so the backing's pages are + /// charged to the client and a refusal is this SUBMIT's (ENOMEM at the cgroup's limit), before + /// the command is queued. The caller holds the job's residency lease, so the pool stays armed + /// until publication ([`Context::rearm_render_pool`]). + /// + /// [`Context::rearm_render_pool`]: crate::g17::context::Context::rearm_render_pool + pub(in crate::g17::runtime) fn provision_render_pool(&self) -> Result { + if self.context.is_m5() || !self.context.render_pool_vacant() { + return Ok(()); + } + // Recovery joins this lease before it replaces the firmware whose VMs the backing maps into. + let lease = self.enter_preparation(true)?; + let resources = { + let state = self.shared.state.lock(); + let firmware = (*state).as_deref().ok_or(ENODEV)?; + if !lease.is_current() { + return Err(EAGAIN); + } + BuildResources::new(firmware)? + }; + let dev = self.shared.drm()?; + let alloc = Allocator { dev: &dev, uat: &resources.uat, client: None }; + let rearm = || self.context.rearm_render_pool(&alloc, &resources.global); + // The backing goes in the context's own window: it is full only while the vacated + // backing is still being unmapped from it, so that ENOSPC is a retry. + match self.context.vm().memory_client() { + Some(client) => client.charging(rearm), + None => rearm(), + } + .map_err(|error| if error == ENOSPC { EAGAIN } else { error }) + } + /// Arms an M5 pool's backing for the pair build. A pool without storage /// takes the physical storage of a released identity first, without /// evicting a metadata-only owner. The caller holds the pool's pin. @@ -314,11 +347,6 @@ impl super::super::Backend { } let pool = pair.pool().clone(); drop(state); - let alloc = Allocator { - dev: &dev, - uat: &resources.uat, - client: None, - }; if resources.uat.is_m5() { return self.prepare_pool_backing( &pool, @@ -327,7 +355,12 @@ impl super::super::Backend { self.context.vm(), ); } - return pool.ensure_backing(&alloc, &resources.global, self.context.vm()); + // The pool of a matching pair is this context's, which its SUBMIT + // re-armed (provision_render_pool) and the job's residency lease has + // kept armed: publication allocates no backing in the worker. + kernel::pr_warn_once!( + "G17: render pool vacant at publication: not re-armed at SUBMIT\n"); + return Err(EIO); } if !pair.bindable(self.owner, &self.context)? { return Err(EBUSY); diff --git a/tools/asahi/g17-render-rearm-submit-tests.py b/tools/asahi/g17-render-rearm-submit-tests.py new file mode 100755 index 0000000000000..0ec1232a7938a --- /dev/null +++ b/tools/asahi/g17-render-rearm-submit-tests.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""A render pool that pressure reclaim vacated is re-armed at SUBMIT, not at publication. + +`vacate_evicted_render_pools` gives back the backing of an idle evicted client's render pool. On +NEO the pool used to be re-armed by the first publication that needed it, in the scheduler's +worker, where the pages were charged to no memory cgroup. Now: + +- `Queue::enqueue` calls `Backend::provision_render` for every render command, before it prunes or + queues anything, while the command's `VmJobGuard` holds the VM's residency lease; +- the G17 backend re-arms the context's pool there (`provision_render_pool`), under + `client.charging(..)`, after checking its preparation lease; +- `Context::rearm_render_pool` is the only NEO caller of `ensure_backing`: publication + (`Context::render_pool`, `build_render_pair`) only takes the pool, and a vacant one there is EIO; +- the other `ensure_backing` callers are the M5 paths (`if alloc.uat.is_m5()` / `prepare_pool_backing`). + +--mutation no-submit-rearm / late-rearm / uncharged-rearm / no-lease-check / publication-rearms / +pair-rearms inject each fault 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' +FILES = ['queue/mod.rs', 'job.rs', 'runtime/backend.rs', 'runtime/render/prepare.rs', 'context.rs', + 'queue/render.rs', 'queue/render/parked.rs', 'freelist.rs'] +MUTATIONS = ['no-submit-rearm', 'late-rearm', 'uncharged-rearm', 'no-lease-check', 'publication-rearms', + 'pair-rearms'] + + +def sources(mutation): + files = {name: (G17 / name).read_text() for name in FILES} + + def sub(name, old, new): + assert old in files[name], (mutation, name, old) + files[name] = files[name].replace(old, new, 1) + + call = ' self.backend.provision_render()?;\n' + if mutation == 'no-submit-rearm': + sub('queue/mod.rs', call, '') + elif mutation == 'late-rearm': + sub('queue/mod.rs', call, '') + sub('queue/mod.rs', ' self.prune_frontier(other);\n', + ' self.prune_frontier(other);\n self.backend.provision_render()?;\n') + elif mutation == 'uncharged-rearm': + sub('runtime/render/prepare.rs', 'Some(client) => client.charging(rearm),', 'Some(_) => rearm(),') + elif mutation == 'no-lease-check': + sub('runtime/render/prepare.rs', + ' if !lease.is_current() {\n return Err(EAGAIN);\n }\n BuildResources::new(firmware)?', + ' BuildResources::new(firmware)?') + elif mutation == 'publication-rearms': + sub('context.rs', ' if !alloc.uat.is_m5() && pool.vacant() {', + ' if !alloc.uat.is_m5() {\n pool.ensure_backing(alloc, render_global, self.vm())?;\n }\n if false {') + elif mutation == 'pair-rearms': + sub('runtime/render/prepare.rs', ' return Err(EIO);', + ' return pool.ensure_backing(&Allocator { dev: &dev, uat: &resources.uat, ' + 'client: None }, &resources.global, self.context.vm());') + return files + + +def strip(text): + return '\n'.join(line.split('//')[0] for line in text.split('\n')) + + +def fn_body(code, name): + """The text of `fn name` up to the next `fn` at the same indent.""" + m = re.search(r'\n([ \t]*)(pub(\([^)]*\))? )?fn ' + name + r'\b', code) + if not m: + return None + end = re.search(r'\n' + m.group(1) + r'(pub(\([^)]*\))? )?fn ', code[m.end():]) + return code[m.end():m.end() + end.start()] if end else code[m.end():] + + +def check(files): + failures = [] + code = {name: strip(text) for name, text in files.items()} + + enqueue = fn_body(code['queue/mod.rs'], 'enqueue') or '' + render = enqueue.find('if let Validated::Render') + call = enqueue.find('self.backend.provision_render()?') + prune = enqueue.find('self.prune_frontier(index)') + if call < 0 or render < 0 or not render < call: + failures.append('FAIL line 0: queue/mod.rs: enqueue does not re-arm render pools for render commands') + elif prune < 0 or call > prune: + failures.append('FAIL line 0: queue/mod.rs: enqueue re-arms render pools after it has started to queue') + + if not re.search(r'fn provision_render\(&self\) -> Result \{ Ok\(\(\)\) \}', code['job.rs']): + failures.append('FAIL line 0: job.rs: Backend::provision_render has no harmless default') + backend = fn_body(code['runtime/backend.rs'], 'provision_render') or '' + if 'self.provision_render_pool()' not in backend: + failures.append('FAIL line 0: runtime/backend.rs: the G17 backend does not re-arm at SUBMIT') + + provision = fn_body(code['runtime/render/prepare.rs'], 'provision_render_pool') or '' + if 'client.charging(rearm)' not in provision or 'rearm_render_pool(' not in provision: + failures.append('FAIL line 0: runtime/render/prepare.rs: the SUBMIT re-arm is not charged to the client') + if 'enter_preparation(' not in provision or not re.search(r'if !lease\.is_current\(\) \{\s*return Err\(EAGAIN\);', provision): + failures.append('FAIL line 0: runtime/render/prepare.rs: the SUBMIT re-arm does not check its preparation lease') + + pool = fn_body(code['context.rs'], 'render_pool') or '' + if 'ensure_backing(' in pool or 'return Err(EIO);' not in pool: + failures.append('FAIL line 0: context.rs: render_pool() re-arms at publication instead of failing a vacant pool') + rearm = fn_body(code['context.rs'], 'rearm_render_pool') or '' + if 'ensure_backing(' not in rearm: + failures.append('FAIL line 0: context.rs: rearm_render_pool() does not re-arm') + + pair = fn_body(code['runtime/render/prepare.rs'], 'build_render_pair') or '' + if 'ensure_backing(' in pair: + failures.append('FAIL line 0: runtime/render/prepare.rs: build_render_pair re-arms at publication') + + # Every other caller is an M5 path. + for name in ('queue/render.rs', 'queue/render/parked.rs'): + for m in re.finditer(r'ensure_backing\(', code[name]): + before = code[name][max(0, m.start() - 120):m.start()] + if 'is_m5()' not in before: + failures.append(f'FAIL line 0: {name}: ensure_backing outside an M5 path') + prepare_callers = [m.start() for m in re.finditer(r'ensure_backing\(', code['runtime/render/prepare.rs'])] + m5_helper = fn_body(code['runtime/render/prepare.rs'], 'prepare_pool_backing') or '' + if len(prepare_callers) != m5_helper.count('ensure_backing('): + failures.append('FAIL line 0: runtime/render/prepare.rs: ensure_backing outside prepare_pool_backing') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=MUTATIONS) + args = parser.parse_args() + failures = check(sources(args.mutation)) + for f in failures: + print(f) + if failures: + sys.exit(1) + print('ok: vacated render pools are re-armed at SUBMIT under the client, publication only takes them') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index dc406d576bfa3..d0286516dfa41 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -610,6 +610,9 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('recovery-state-eio', 'drop-generation-check', 'wrong-j813-pipe'), []), 'g17-resource-tests.py': [([], PASS)], + 'g17-render-rearm-submit-tests.py': [([], PASS)] + mutations( + '--mutation', ['no-submit-rearm', 'late-rearm', 'uncharged-rearm', 'no-lease-check', + 'publication-rearms', 'pair-rearms'], []), 'g17-queue-object-charge-tests.py': [([], PASS)] + mutations( '--mutation', ['drop-client', 'uncharged-backing', 'none-client', 'uncharged-compute', 'charged-kit'], []), From 5b9b1512868268487373506b9a24490acf9a73c6 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 4 Dec 2026 14:31:25 -0300 Subject: [PATCH 09/10] drm/asahi: g17: keep a SUBMIT-armed render pool armed until publication The previous commit re-arms a vacated NEO render pool in the client's SUBMIT and lets publication only take it, trusting the command's residency lease to keep the pool armed in between. The lease only holds off vacate_evicted_render_pools(). On m4.230, before the pools had windows of their own, reclaim_idle_render_pools(), which checked only whether the owner was active, vacated a pool in that window: "render pool vacant at publication", and the clients behind it saw lost devices. That path is gone with the windows, but the invariant should not rest on which vacate paths exist and what each one checks. Make the hold explicit. SUBMIT takes a RenderClaim on the context's pool, counted under the pool's backing lock, before it checks whether the pool is vacant; the command's Packet holds it until the command is dropped. RenderPool::vacate() keeps the backing of a claimed pool, so no vacate path empties it before publication. The claim is counted under the same lock vacate checks it under: a vacate either finished first, and SUBMIT sees the pool vacant and re-arms it, or it leaves the pool alone. Context::rearm_render_pool and render_pool_vacant go away; the SUBMIT re-arms through the claim. The host test gains unclaimed-vacate, claim-unlocked and claim-dropped mutations. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/context.rs | 34 +++------- drivers/gpu/drm/asahi/g17/freelist.rs | 40 ++++++++++- drivers/gpu/drm/asahi/g17/job.rs | 7 +- drivers/gpu/drm/asahi/g17/queue/mod.rs | 13 ++-- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 2 +- .../drm/asahi/g17/runtime/render/prepare.rs | 32 +++++---- tools/asahi/g17-render-rearm-submit-tests.py | 68 +++++++++++++------ tools/asahi/run-host-tests.py | 3 +- 8 files changed, 128 insertions(+), 71 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 9e1d547aeca09..1f23ebc5cee89 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -8,7 +8,7 @@ mod identity; use super::{ - freelist::{RenderId, RenderIds, RenderPool, Window}, + freelist::{RenderClaim, RenderId, RenderIds, RenderPool, Window}, fw::{context as fw, queue::Policy}, object::{Allocator, CpuMap, Exposure, Family, KernelObject, Pool, PooledObject, ReturnMark}, status::VmStatus, @@ -765,10 +765,9 @@ impl Context { let mut render = self.render.lock(); if let Some(pool) = &*render { if pool.fits(plan.as_ref().map(|p| p.geometry)) { - // A pool vacated under memory pressure was re-armed by this context's SUBMIT - // ([`Self::rearm_render_pool`]), and the job's residency lease has kept it armed - // since: publication only takes it. M5 backing is installed by the pair that pins - // the pool. + // A pool vacated under pressure was re-armed by this command's SUBMIT, and its + // [`RenderClaim`] has kept it armed since: publication only takes it. M5 backing + // is installed by the pair that pins the pool. if !alloc.uat.is_m5() && pool.vacant() { kernel::pr_warn_once!("G17: render pool vacant at publication: not re-armed at SUBMIT\n"); return Err(EIO); @@ -804,27 +803,10 @@ impl Context { drop(previous); Ok(pool) } - /// Re-arms this context's NEO render pool if pressure reclaim vacated it, for a SUBMIT of render - /// work: the caller runs this in the client's ioctl, under the client's memory cgroup, so a - /// refusal (ENOMEM at its limit, ENOSPC without lower kernel VA) is that SUBMIT's. It holds the - /// job's residency lease, which keeps the VM from being evicted, so - /// `vacate_evicted_render_pools` cannot vacate the pool again before the job is published. - /// A context without a pool yet gets one at its first publication ([`Self::render_pool`]); M5 - /// backing is installed by the pair that pins the pool. - pub(crate) fn rearm_render_pool(&self, alloc: &Allocator<'_>, render_global: &Vm) -> Result { - if alloc.uat.is_m5() { - return Ok(()); - } - let pool = self.render.lock().clone(); - match pool { - Some(pool) if pool.vacant() => pool.ensure_backing(alloc, render_global, self.vm()), - _ => Ok(()), - } - } - - /// Whether this context has a render pool that pressure reclaim vacated. - pub(crate) fn render_pool_vacant(&self) -> bool { - self.render.lock().as_ref().is_some_and(|pool| pool.vacant()) + /// Claims this context's render pool for a render command's SUBMIT ([`RenderClaim`]). None + /// before the first pool, which publication builds armed. + pub(crate) fn claim_render_pool(&self) -> Option { + self.render.lock().as_ref().map(|pool| pool.claim()) } /// Drops the pool once its free-list release is consumed and the closed diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index 184f89e3cd0fe..bcb2f77c887a1 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -11,7 +11,7 @@ use super::fw::freelist::*; use super::fw::initdata::{FreeListArgs, FreeListClass, FreeListControl, FREE_LIST_BLOCK_PAGES, FREE_LIST_BLOCK_SIZE}; use super::object::{Allocator, CpuMap, KernelObject}; use crate::mmu; -use core::sync::atomic::{fence, AtomicBool, AtomicU16, AtomicU64, Ordering}; +use core::sync::atomic::{fence, AtomicBool, AtomicU16, AtomicU32, AtomicU64, Ordering}; use kernel::{ new_mutex, prelude::*, @@ -702,6 +702,9 @@ pub(crate) struct RenderPool { client_residency: Option>, /// The one VM (`mmu::Vm::id`) this pool's backing is aliased into. client_vm: u64, + /// Render commands between their SUBMIT and their drop ([`RenderClaim`]): while any, the + /// backing is not vacated. + claims: AtomicU32, control: KernelObject, state: KernelObject, served: AtomicBool, @@ -713,6 +716,23 @@ pub(crate) struct RenderPool { window: Option>, } +/// One render command of the pool's context, from its SUBMIT, which re-arms a vacated pool, until +/// the command is dropped. While any is held, the pool's backing stays ([`RenderPool::vacate`]), +/// so publication only takes it. +pub(crate) struct RenderClaim(Arc); + +impl RenderClaim { + pub(crate) fn pool(&self) -> &Arc { + &self.0 + } +} + +impl Drop for RenderClaim { + fn drop(&mut self) { + self.0.claims.fetch_sub(1, Ordering::AcqRel); + } +} + /// Keeps both a physical identity and its logical pool alive during use. /// Drop the identity pin before releasing the retained pool reference. pub(crate) struct PoolPin { @@ -770,7 +790,7 @@ impl RenderPool { let serial = RENDER_POOL_SERIAL.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| value.checked_add(1)).map_err(|_| EOVERFLOW)? + 1; Ok(Self { storage, epoch: AtomicU64::new(0), client_residency: client.residency_gate(), - client_vm: client.id(), + client_vm: client.id(), claims: AtomicU32::new(0), control, state, served: AtomicBool::new(true), serial, id, layout: PageLayout::M5(geometry), window: None }) } @@ -822,6 +842,7 @@ impl RenderPool { epoch: AtomicU64::new(0), client_residency: client.residency_gate(), client_vm: client.id(), + claims: AtomicU32::new(0), control, state, served: AtomicBool::new(false), @@ -847,13 +868,26 @@ impl RenderPool { /// pool's free-list release consumed, so no firmware reference remains; the /// next staging requires a re-armed backing. The caller drops the result /// after releasing the device mutex. + /// A claimed pool keeps its backing ([`RenderClaim`]). pub(crate) fn vacate(&self) -> Option { - let backing = self.storage.backing.lock().take(); + let mut backing = self.storage.backing.lock(); + if self.claims.load(Ordering::Acquire) != 0 { + return None; + } + let backing = backing.take(); if backing.is_some() { self.storage.page_list.store(0, Ordering::Release); } backing } + /// Claims the backing for a render command ([`RenderClaim`]). Taken under the backing lock, + /// so a [`Self::vacate`] either finished before it, leaving the pool vacant for the caller to + /// re-arm, or keeps the backing. + pub(crate) fn claim(self: &Arc) -> RenderClaim { + let _backing = self.storage.backing.lock(); + self.claims.fetch_add(1, Ordering::AcqRel); + RenderClaim(self.clone()) + } /// Installs fresh backing into a vacant pool, unless another caller did. /// The next staging rewrites the control header and descriptor row for it /// (its run-list address changes the free-list owner identity). diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 972f7afccdfdf..1d6e3988e960a 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -131,6 +131,8 @@ pub(crate) struct Packet { pub(crate) footprint: Option>, /// A compute command's hold on its owner's spare compute backing. _claim: Option, + /// A render command's hold on its context's armed render pool. + _render_claim: Option, /// Number of render passes in the submit ioctl that created this packet. pub(crate) batch_renders: u16, inputs: KVec, @@ -171,6 +173,7 @@ impl Packet { inputs: KVec, producers: Option, claim: Option, + render_claim: Option, ) -> Result> { let footprint = match &command { Validated::Render { attachments, pass, .. } => { @@ -189,6 +192,7 @@ impl Packet { completion, footprint, _claim: claim, + _render_claim: render_claim, batch_renders, inputs, producers, @@ -427,7 +431,8 @@ pub(crate) trait Backend: Send + Sync { fn reserve_render_window(&self) -> Result { Ok(()) } /// Allocate what a render command's publication would need and its client's earlier /// publications gave back under memory pressure, so a refusal is this SUBMIT's. - fn provision_render(&self) -> Result { Ok(()) } + /// The claim keeps what it provisioned until the command is dropped. + fn provision_render(&self) -> Result> { Ok(None) } fn render_scs_blocks(&self, pages: [u16; 2]) -> Result { if pages != [0; 2] { return Err(EINVAL); } Ok(super::fw::freelist::RENDER_BLOCKS) diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 58203d1561b5f..2a3f1afdb7fb2 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -257,17 +257,19 @@ impl Queue { let engine = Engine::of(&command); let index = engine.index(); let other = 1 - index; - if let Validated::Render { ray_query, .. } = &command { + let render_claim = if let Validated::Render { ray_query, .. } = &command { let blocks = self .backend .render_scs_blocks(ray_query.map(|stage| stage.scratch.pages()))?; if blocks > self.context.render_blocks() { return Err(EINVAL); } - // `guard` holds the VM's residency lease, so what this re-arms stays armed until - // the command is published, and a refusal comes back before anything is queued. - self.backend.provision_render()?; - } + // The packet holds the claim, so what this re-arms stays armed until the command is + // published, and a refusal comes back before anything is queued. + self.backend.provision_render()? + } else { + None + }; self.prune_frontier(index); self.prune_frontier(other); // Claimed before the SUBMIT provisions this command's compute backing, so nothing it was @@ -477,6 +479,7 @@ impl Queue { checked_inputs, producers, claim, + render_claim, )?; let scheduler = match engine { Engine::Render => &mut self.render, diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 070fb9c095621..69f9fcfd817a4 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -305,7 +305,7 @@ impl job::Backend for Backend { self.compute_capacity(command).and_then(|required| self.provision_compute(required)) } - fn provision_render(&self) -> Result { + fn provision_render(&self) -> Result> { // A render pool that pressure reclaim vacated is re-armed here, not at publication. self.provision_render_pool() } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 0c81c132b6f84..d2f9b66d1f1ca 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -6,7 +6,7 @@ use super::{Config, Reservation}; use crate::g17::{ buffer::MetricsLease, - freelist::{PoolPin, RenderPool}, + freelist::{PoolPin, RenderClaim, RenderPool}, preparation::Lease, job::Packet, object::{Allocator, KernelObject, Pool}, @@ -205,16 +205,21 @@ impl super::super::Backend { } } - /// Re-arms this context's render pool for a SUBMIT of render work, if pressure reclaim - /// vacated it: in the client's ioctl and under its memory cgroup, so the backing's pages are - /// charged to the client and a refusal is this SUBMIT's (ENOMEM at the cgroup's limit), before - /// the command is queued. The caller holds the job's residency lease, so the pool stays armed - /// until publication ([`Context::rearm_render_pool`]). - /// - /// [`Context::rearm_render_pool`]: crate::g17::context::Context::rearm_render_pool - pub(in crate::g17::runtime) fn provision_render_pool(&self) -> Result { - if self.context.is_m5() || !self.context.render_pool_vacant() { - return Ok(()); + /// Claims this context's NEO render pool for a SUBMIT of render work and re-arms it if + /// pressure reclaim vacated it: in the client's ioctl and under its memory cgroup, so the + /// backing's pages are charged to the client and a refusal is this SUBMIT's (ENOMEM at the + /// cgroup's limit), before the command is queued. The command holds the claim until it is + /// dropped, so no vacate empties the pool before publication. A context without a pool yet + /// gets one at its first publication; M5 backing is installed by the pair that pins the pool. + pub(in crate::g17::runtime) fn provision_render_pool(&self) -> Result> { + if self.context.is_m5() { + return Ok(None); + } + let Some(claim) = self.context.claim_render_pool() else { + return Ok(None); + }; + if !claim.pool().vacant() { + return Ok(Some(claim)); } // Recovery joins this lease before it replaces the firmware whose VMs the backing maps into. let lease = self.enter_preparation(true)?; @@ -228,14 +233,15 @@ impl super::super::Backend { }; let dev = self.shared.drm()?; let alloc = Allocator { dev: &dev, uat: &resources.uat, client: None }; - let rearm = || self.context.rearm_render_pool(&alloc, &resources.global); + let rearm = || claim.pool().ensure_backing(&alloc, &resources.global, self.context.vm()); // The backing goes in the context's own window: it is full only while the vacated // backing is still being unmapped from it, so that ENOSPC is a retry. match self.context.vm().memory_client() { Some(client) => client.charging(rearm), None => rearm(), } - .map_err(|error| if error == ENOSPC { EAGAIN } else { error }) + .map_err(|error| if error == ENOSPC { EAGAIN } else { error })?; + Ok(Some(claim)) } /// Arms an M5 pool's backing for the pair build. A pool without storage diff --git a/tools/asahi/g17-render-rearm-submit-tests.py b/tools/asahi/g17-render-rearm-submit-tests.py index 0ec1232a7938a..10b918b8eb7e0 100755 --- a/tools/asahi/g17-render-rearm-submit-tests.py +++ b/tools/asahi/g17-render-rearm-submit-tests.py @@ -2,20 +2,22 @@ # SPDX-License-Identifier: GPL-2.0-only OR MIT """A render pool that pressure reclaim vacated is re-armed at SUBMIT, not at publication. -`vacate_evicted_render_pools` gives back the backing of an idle evicted client's render pool. On -NEO the pool used to be re-armed by the first publication that needed it, in the scheduler's -worker, where the pages were charged to no memory cgroup. Now: +`vacate_evicted_render_pools` and `reclaim_idle_render_pools` give back the backing of an idle +client's render pool. On NEO the pool used to be re-armed by the first publication that needed it, +in the scheduler's worker, where the pages were charged to no memory cgroup. Now: - `Queue::enqueue` calls `Backend::provision_render` for every render command, before it prunes or - queues anything, while the command's `VmJobGuard` holds the VM's residency lease; -- the G17 backend re-arms the context's pool there (`provision_render_pool`), under - `client.charging(..)`, after checking its preparation lease; -- `Context::rearm_render_pool` is the only NEO caller of `ensure_backing`: publication - (`Context::render_pool`, `build_render_pair`) only takes the pool, and a vacant one there is EIO; + queues anything, and hands the `RenderClaim` it returns to the command's `Packet`; +- the G17 backend claims the context's pool there (`provision_render_pool`) and re-arms a vacant + one under `client.charging(..)`, after checking its preparation lease; +- `RenderPool::claim` counts the claim under the backing lock and `RenderPool::vacate` keeps the + backing of a claimed pool, so no reclaim path empties it between SUBMIT and publication; +- publication (`Context::render_pool`, `build_render_pair`) only takes the pool, and a vacant one + there is EIO; - the other `ensure_backing` callers are the M5 paths (`if alloc.uat.is_m5()` / `prepare_pool_backing`). --mutation no-submit-rearm / late-rearm / uncharged-rearm / no-lease-check / publication-rearms / -pair-rearms inject each fault and must be caught. +pair-rearms / unclaimed-vacate / claim-unlocked / claim-dropped inject each fault and must be caught. """ import argparse import re @@ -26,7 +28,7 @@ FILES = ['queue/mod.rs', 'job.rs', 'runtime/backend.rs', 'runtime/render/prepare.rs', 'context.rs', 'queue/render.rs', 'queue/render/parked.rs', 'freelist.rs'] MUTATIONS = ['no-submit-rearm', 'late-rearm', 'uncharged-rearm', 'no-lease-check', 'publication-rearms', - 'pair-rearms'] + 'pair-rearms', 'unclaimed-vacate', 'claim-unlocked', 'claim-dropped'] def sources(mutation): @@ -36,13 +38,14 @@ def sub(name, old, new): assert old in files[name], (mutation, name, old) files[name] = files[name].replace(old, new, 1) - call = ' self.backend.provision_render()?;\n' + call = ' self.backend.provision_render()?\n' if mutation == 'no-submit-rearm': - sub('queue/mod.rs', call, '') + sub('queue/mod.rs', call, ' None\n') elif mutation == 'late-rearm': - sub('queue/mod.rs', call, '') + sub('queue/mod.rs', call, ' None\n') sub('queue/mod.rs', ' self.prune_frontier(other);\n', - ' self.prune_frontier(other);\n self.backend.provision_render()?;\n') + ' self.prune_frontier(other);\n' + ' let render_claim = if render_claim.is_none() { self.backend.provision_render()? } else { None };\n') elif mutation == 'uncharged-rearm': sub('runtime/render/prepare.rs', 'Some(client) => client.charging(rearm),', 'Some(_) => rearm(),') elif mutation == 'no-lease-check': @@ -56,6 +59,13 @@ def sub(name, old, new): sub('runtime/render/prepare.rs', ' return Err(EIO);', ' return pool.ensure_backing(&Allocator { dev: &dev, uat: &resources.uat, ' 'client: None }, &resources.global, self.context.vm());') + elif mutation == 'unclaimed-vacate': + sub('freelist.rs', ' if self.claims.load(Ordering::Acquire) != 0 {\n return None;\n }\n', '') + elif mutation == 'claim-unlocked': + sub('freelist.rs', ' let _backing = self.storage.backing.lock();\n self.claims.fetch_add(', + ' self.claims.fetch_add(') + elif mutation == 'claim-dropped': + sub('queue/mod.rs', ' claim,\n render_claim,\n )?;', ' claim,\n None,\n )?;') return files @@ -85,14 +95,20 @@ def check(files): elif prune < 0 or call > prune: failures.append('FAIL line 0: queue/mod.rs: enqueue re-arms render pools after it has started to queue') - if not re.search(r'fn provision_render\(&self\) -> Result \{ Ok\(\(\)\) \}', code['job.rs']): + new = enqueue.find('Packet::new(') + if new < 0 or not re.match(r'Packet::new\([^;]*\brender_claim,\s*\)\?;', enqueue[new:]): + failures.append('FAIL line 0: queue/mod.rs: the packet does not hold the SUBMIT render claim') + if not re.search(r'fn provision_render\(&self\) -> Result> \{ Ok\(None\) \}', + code['job.rs']): failures.append('FAIL line 0: job.rs: Backend::provision_render has no harmless default') + if '_render_claim: render_claim,' not in code['job.rs']: + failures.append('FAIL line 0: job.rs: Packet drops its render claim') backend = fn_body(code['runtime/backend.rs'], 'provision_render') or '' if 'self.provision_render_pool()' not in backend: failures.append('FAIL line 0: runtime/backend.rs: the G17 backend does not re-arm at SUBMIT') provision = fn_body(code['runtime/render/prepare.rs'], 'provision_render_pool') or '' - if 'client.charging(rearm)' not in provision or 'rearm_render_pool(' not in provision: + if 'client.charging(rearm)' not in provision or 'claim.pool().ensure_backing(' not in provision: failures.append('FAIL line 0: runtime/render/prepare.rs: the SUBMIT re-arm is not charged to the client') if 'enter_preparation(' not in provision or not re.search(r'if !lease\.is_current\(\) \{\s*return Err\(EAGAIN\);', provision): failures.append('FAIL line 0: runtime/render/prepare.rs: the SUBMIT re-arm does not check its preparation lease') @@ -100,9 +116,19 @@ def check(files): pool = fn_body(code['context.rs'], 'render_pool') or '' if 'ensure_backing(' in pool or 'return Err(EIO);' not in pool: failures.append('FAIL line 0: context.rs: render_pool() re-arms at publication instead of failing a vacant pool') - rearm = fn_body(code['context.rs'], 'rearm_render_pool') or '' - if 'ensure_backing(' not in rearm: - failures.append('FAIL line 0: context.rs: rearm_render_pool() does not re-arm') + if 'claim_render_pool()' not in provision: + failures.append('FAIL line 0: runtime/render/prepare.rs: the SUBMIT does not claim the render pool') + if 'pool.claim()' not in (fn_body(code['context.rs'], 'claim_render_pool') or ''): + failures.append('FAIL line 0: context.rs: claim_render_pool() does not claim the pool') + + vacate = fn_body(code['freelist.rs'], 'vacate') or '' + guard, take = vacate.find('self.claims.load('), vacate.find('backing.take()') + if guard < 0 or take < 0 or guard > take: + failures.append('FAIL line 0: freelist.rs: vacate() empties a claimed pool') + claim = fn_body(code['freelist.rs'], 'claim') or '' + lock, count = claim.find('self.storage.backing.lock()'), claim.find('self.claims.fetch_add(') + if lock < 0 or count < 0 or lock > count: + failures.append('FAIL line 0: freelist.rs: claim() is not counted under the backing lock') pair = fn_body(code['runtime/render/prepare.rs'], 'build_render_pair') or '' if 'ensure_backing(' in pair: @@ -116,7 +142,7 @@ def check(files): failures.append(f'FAIL line 0: {name}: ensure_backing outside an M5 path') prepare_callers = [m.start() for m in re.finditer(r'ensure_backing\(', code['runtime/render/prepare.rs'])] m5_helper = fn_body(code['runtime/render/prepare.rs'], 'prepare_pool_backing') or '' - if len(prepare_callers) != m5_helper.count('ensure_backing('): + if len(prepare_callers) != m5_helper.count('ensure_backing(') + provision.count('ensure_backing('): failures.append('FAIL line 0: runtime/render/prepare.rs: ensure_backing outside prepare_pool_backing') return failures @@ -130,7 +156,7 @@ def main(): print(f) if failures: sys.exit(1) - print('ok: vacated render pools are re-armed at SUBMIT under the client, publication only takes them') + print('ok: vacated render pools are re-armed at SUBMIT under the client and stay claimed until publication') if __name__ == '__main__': diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index d0286516dfa41..78bab02018a08 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -612,7 +612,8 @@ def mutations(flag, names, base, expect=KILL): 'g17-resource-tests.py': [([], PASS)], 'g17-render-rearm-submit-tests.py': [([], PASS)] + mutations( '--mutation', ['no-submit-rearm', 'late-rearm', 'uncharged-rearm', 'no-lease-check', - 'publication-rearms', 'pair-rearms'], []), + 'publication-rearms', 'pair-rearms', 'unclaimed-vacate', 'claim-unlocked', + 'claim-dropped'], []), 'g17-queue-object-charge-tests.py': [([], PASS)] + mutations( '--mutation', ['drop-client', 'uncharged-backing', 'none-client', 'uncharged-compute', 'charged-kit'], []), From 2529bcab491b707ab2692fad47db0a463fc5db61 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 4 Dec 2026 16:40:11 -0300 Subject: [PATCH 10/10] drm/asahi: g17: re-arm a vacated render pool before any command is queued A submission can carry several commands, and Queue::enqueue() queues them one by one. The re-arm of a vacated render pool ran in enqueue(), per render command, so a refusal (ENOMEM in the client's cgroup) for a render command came back after the submission's earlier commands were already queued: not a refusal that leaves the submission untouched, but a failure with failed fences on its outputs. Re-arm once per submission in Queue::submit(), right after the context's render window is reserved and before any command is queued, holding a RenderClaim until every command is. Each render command then takes its own claim on the armed pool in enqueue() (Backend::claim_render(), which cannot fail), and its packet holds that one until it is dropped. g17-render-rearm-submit-tests checks the re-arm in submit() before the first enqueue(), none in enqueue(), and a claim per render command, with the late-rearm and unclaimed-command mutations. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/job.rs | 5 ++- drivers/gpu/drm/asahi/g17/queue/mod.rs | 19 ++++++---- drivers/gpu/drm/asahi/g17/runtime/backend.rs | 4 +++ tools/asahi/g17-render-rearm-submit-tests.py | 37 +++++++++++--------- tools/asahi/run-host-tests.py | 2 +- 5 files changed, 42 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 1d6e3988e960a..b401e24d70ab3 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -431,8 +431,11 @@ pub(crate) trait Backend: Send + Sync { fn reserve_render_window(&self) -> Result { Ok(()) } /// Allocate what a render command's publication would need and its client's earlier /// publications gave back under memory pressure, so a refusal is this SUBMIT's. - /// The claim keeps what it provisioned until the command is dropped. + /// Called once per submission, before any of its commands is queued; the claim keeps what it + /// provisioned until every command holds its own ([`Self::claim_render`]). fn provision_render(&self) -> Result> { Ok(None) } + /// A render command's claim on its context's armed pool ([`Self::provision_render`]). + fn claim_render(&self) -> Option { None } fn render_scs_blocks(&self, pages: [u16; 2]) -> Result { if pages != [0; 2] { return Err(EINVAL); } Ok(super::fw::freelist::RENDER_BLOCKS) diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 2a3f1afdb7fb2..8e7202bcfcea0 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -264,9 +264,9 @@ impl Queue { if blocks > self.context.render_blocks() { return Err(EINVAL); } - // The packet holds the claim, so what this re-arms stays armed until the command is - // published, and a refusal comes back before anything is queued. - self.backend.provision_render()? + // The submission re-armed the pool before queueing any command; the packet's own + // claim keeps it armed until this command is published. + self.backend.claim_render() } else { None }; @@ -676,11 +676,16 @@ impl crate::queue::Queue for Queue { for (publishers, room) in self.publishers.iter_mut().zip(room) { publishers.reserve(room)?; } - // The context's lower VA from its first render on, reserved before any command of the - // submission is queued: a full range refuses the submission, not a publication. - if room[Engine::Render.index()] != 0 { + // The context's lower VA from its first render on, and its pool re-armed if pressure + // vacated it, before any command of the submission is queued: a full range or the + // client's cgroup limit refuses the submission, not a publication. The claim is held + // until every command is queued with its own. + let _armed = if room[Engine::Render.index()] != 0 { self.backend.reserve_render_window()?; - } + self.backend.provision_render()? + } else { + None + }; let mut guards = guards.drain_all(); let mut work_states = KVec::new(); let aggregate = if pending.len() > 1 { diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 69f9fcfd817a4..368b64153f62e 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -305,6 +305,10 @@ impl job::Backend for Backend { self.compute_capacity(command).and_then(|required| self.provision_compute(required)) } + fn claim_render(&self) -> Option { + if self.context.is_m5() { None } else { self.context.claim_render_pool() } + } + fn provision_render(&self) -> Result> { // A render pool that pressure reclaim vacated is re-armed here, not at publication. self.provision_render_pool() diff --git a/tools/asahi/g17-render-rearm-submit-tests.py b/tools/asahi/g17-render-rearm-submit-tests.py index 10b918b8eb7e0..3aca97a74c587 100755 --- a/tools/asahi/g17-render-rearm-submit-tests.py +++ b/tools/asahi/g17-render-rearm-submit-tests.py @@ -6,8 +6,9 @@ client's render pool. On NEO the pool used to be re-armed by the first publication that needed it, in the scheduler's worker, where the pages were charged to no memory cgroup. Now: -- `Queue::enqueue` calls `Backend::provision_render` for every render command, before it prunes or - queues anything, and hands the `RenderClaim` it returns to the command's `Packet`; +- `Queue::submit` calls `Backend::provision_render` once for a submission with render commands, before + any of its commands is queued, and holds the returned `RenderClaim` until all are; `Queue::enqueue` + hands each render command's own claim (`Backend::claim_render`) to its `Packet`; - the G17 backend claims the context's pool there (`provision_render_pool`) and re-arms a vacant one under `client.charging(..)`, after checking its preparation lease; - `RenderPool::claim` counts the claim under the backing lock and `RenderPool::vacate` keeps the @@ -27,7 +28,7 @@ G17 = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' FILES = ['queue/mod.rs', 'job.rs', 'runtime/backend.rs', 'runtime/render/prepare.rs', 'context.rs', 'queue/render.rs', 'queue/render/parked.rs', 'freelist.rs'] -MUTATIONS = ['no-submit-rearm', 'late-rearm', 'uncharged-rearm', 'no-lease-check', 'publication-rearms', +MUTATIONS = ['no-submit-rearm', 'late-rearm', 'unclaimed-command', 'uncharged-rearm', 'no-lease-check', 'publication-rearms', 'pair-rearms', 'unclaimed-vacate', 'claim-unlocked', 'claim-dropped'] @@ -38,14 +39,14 @@ def sub(name, old, new): assert old in files[name], (mutation, name, old) files[name] = files[name].replace(old, new, 1) - call = ' self.backend.provision_render()?\n' + call = ' self.backend.provision_render()?\n' if mutation == 'no-submit-rearm': - sub('queue/mod.rs', call, ' None\n') + sub('queue/mod.rs', call, ' None\n') elif mutation == 'late-rearm': - sub('queue/mod.rs', call, ' None\n') - sub('queue/mod.rs', ' self.prune_frontier(other);\n', - ' self.prune_frontier(other);\n' - ' let render_claim = if render_claim.is_none() { self.backend.provision_render()? } else { None };\n') + sub('queue/mod.rs', call, ' None\n') + sub('queue/mod.rs', ' self.backend.claim_render()\n', ' self.backend.provision_render()?\n') + elif mutation == 'unclaimed-command': + sub('queue/mod.rs', ' self.backend.claim_render()\n', ' None\n') elif mutation == 'uncharged-rearm': sub('runtime/render/prepare.rs', 'Some(client) => client.charging(rearm),', 'Some(_) => rearm(),') elif mutation == 'no-lease-check': @@ -87,13 +88,17 @@ def check(files): code = {name: strip(text) for name, text in files.items()} enqueue = fn_body(code['queue/mod.rs'], 'enqueue') or '' - render = enqueue.find('if let Validated::Render') - call = enqueue.find('self.backend.provision_render()?') - prune = enqueue.find('self.prune_frontier(index)') - if call < 0 or render < 0 or not render < call: - failures.append('FAIL line 0: queue/mod.rs: enqueue does not re-arm render pools for render commands') - elif prune < 0 or call > prune: - failures.append('FAIL line 0: queue/mod.rs: enqueue re-arms render pools after it has started to queue') + submit = fn_body(code['queue/mod.rs'], 'submit') or '' + call, first = submit.find('self.backend.provision_render()?'), submit.find('self.enqueue(') + if call < 0 or 'let _armed = if room[Engine::Render.index()] != 0' not in submit: + failures.append('FAIL line 0: queue/mod.rs: a submission does not re-arm render pools for its render commands') + elif first < 0 or call > first: + failures.append('FAIL line 0: queue/mod.rs: the re-arm comes after the submission started to queue') + if 'provision_render(' in enqueue: + failures.append('FAIL line 0: queue/mod.rs: the re-arm runs per command, after earlier ones were queued') + render, claim = enqueue.find('if let Validated::Render'), enqueue.find('self.backend.claim_render()') + if claim < 0 or render < 0 or render > claim: + failures.append('FAIL line 0: queue/mod.rs: a render command takes no claim on its pool') new = enqueue.find('Packet::new(') if new < 0 or not re.match(r'Packet::new\([^;]*\brender_claim,\s*\)\?;', enqueue[new:]): diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 78bab02018a08..f26d87b1016f7 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -611,7 +611,7 @@ def mutations(flag, names, base, expect=KILL): 'wrong-j813-pipe'), []), 'g17-resource-tests.py': [([], PASS)], 'g17-render-rearm-submit-tests.py': [([], PASS)] + mutations( - '--mutation', ['no-submit-rearm', 'late-rearm', 'uncharged-rearm', 'no-lease-check', + '--mutation', ['no-submit-rearm', 'late-rearm', 'unclaimed-command', 'uncharged-rearm', 'no-lease-check', 'publication-rearms', 'pair-rearms', 'unclaimed-vacate', 'claim-unlocked', 'claim-dropped'], []), 'g17-queue-object-charge-tests.py': [([], PASS)] + mutations(