From 2dc7fb52d56de679e70124fdf491c817d4862258 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 01:01:20 -0300 Subject: [PATCH 1/3] 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 da65b3f1562c1b56b2bb9047cdea1f366a67c37c Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 16:18:03 -0500 Subject: [PATCH 2/3] 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 d3c209678b13479f9e4ed77fb1f4c969d1d90e70 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Wed, 2 Dec 2026 12:28:24 -0300 Subject: [PATCH 3/3] drm/asahi: g17: charge client_backing() pages to the client's memory cgroup KernelObject::client_backing() admits an object to its client's limits and counts it as the client's held memory, but it populated the pages in whatever task called it. Its callers run in workers too: tiler heap growth at publication (runtime/render/grow.rs, runtime/render/prepare.rs) and M5 render targets. A worker has no memory cgroup of its own, so those pages were charged to the root cgroup while the driver's ledger said they were the client's: a MemoryMax limit on the client did not bound them, and the OOM killer and systemd-oomd could not see them in the client's cgroup. Build the object through charged(), as queue_backing() does: it populates the pages under client.charging(), so they are charged to the memory cgroup of the task that opened the client, whichever task builds the object. g17-queue-object-charge-tests now checks that client_backing() goes through charged() and that charged() populates inside client.charging(), with two mutations that restore each fault. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/object.rs | 11 ++--- tools/asahi/g17-queue-object-charge-tests.py | 47 +++++++++++++++++--- tools/asahi/run-host-tests.py | 3 +- 3 files changed, 48 insertions(+), 13 deletions(-) diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index a3aed32cad412..99ace369afbd8 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -114,7 +114,9 @@ impl KernelObject { /// Write-combined [`Self::backing`] that a client's commands size, charged to that client /// (`client`) as a user buffer of the same size would be: admitted against its and the /// device's memory limits before it is allocated, failing with ENOMEM over either, and then - /// counted as its held memory instead of kernel memory, until the object is dropped. + /// counted as its held memory instead of kernel memory, and its pages charged to the client's + /// memory cgroup, until the object is dropped. Callers run in workers too (tiler heap growth at + /// publication), so the pages go to the client's cgroup whatever task populates them. /// Without a client (a kernel VM's object) it is kernel memory, as [`Self::backing`]. pub(crate) fn client_backing( dev: &AsahiDrmDevice, @@ -126,12 +128,7 @@ impl KernelObject { }; let bytes = gem::checked_object_size(size)? as u64; let commit = crate::memacct::LEDGER.admit(client, bytes)?; - let mut object = - Self::with_object(gem::new_kernel_object_wc_user_charged(dev, size)?, size)?; - let charge = crate::memacct::Charge::user(commit, None); - charge.set_held(true); - object.charge = Some(charge); - Ok(object) + Self::charged(dev, size, CpuMap::WriteCombined, client, commit) } /// [`Self::backing`] that `client`'s queues need, charged to it whatever the limits: counted diff --git a/tools/asahi/g17-queue-object-charge-tests.py b/tools/asahi/g17-queue-object-charge-tests.py index fa4ad66de9a12..e9f6b053787a1 100644 --- a/tools/asahi/g17-queue-object-charge-tests.py +++ b/tools/asahi/g17-queue-object-charge-tests.py @@ -18,10 +18,15 @@ - 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. + appear only in object.rs, the global boot files and the PUBLICATION files; +- an object charged to a client has its pages charged to that client's memory + cgroup whichever task builds it: `client_backing` (tiler heap growth and M5 + render targets, built in workers) goes through `charged`, which populates + inside `client.charging(..)`. A worker has no memory cgroup of its own, so + pages populated there otherwise land in the root cgroup. ---mutation drop-client / uncharged-backing / none-client inject each fault -and must be caught. +--mutation drop-client / uncharged-backing / none-client / uncharged-pages / +root-populate inject each fault and must be caught. """ import argparse import re @@ -48,9 +53,27 @@ 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-pages': + # client_backing populates in the calling task again, as before the fix. + k = 'object.rs' + files[k] = files[k].replace(' Self::charged(dev, size, CpuMap::WriteCombined, client, commit)\n', + ' Self::with_object(gem::new_kernel_object_wc_user_charged(dev, size)?, size)\n', 1) + elif mutation == 'root-populate': + k = 'object.rs' + files[k] = files[k].replace('client.charging(|| Self::with_object(obj, size))?', + 'Self::with_object(obj, size)?', 1) return files +def fn_body(code, name): + """The text of `fn name` up to the next `fn` at the same indent (good enough for these short functions).""" + m = re.search(r'\n([ \t]*)(pub\(crate\) )?fn ' + name + r'\(', code) + if not m: + return None + end = re.search(r'\n' + m.group(1) + r'(pub\(crate\) )?fn ', code[m.end():]) + return code[m.end():m.end() + end.start()] if end else code[m.end():] + + def line(text, pos): return text.count('\n', 0, pos) + 1 @@ -76,6 +99,18 @@ def check(files): 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') + # Client-charged pages go to the client's memory cgroup whatever task populates them. + obj = '\n'.join(l.split('//')[0] for l in files['object.rs'].split('\n')) + cb, charged = fn_body(obj, "client_backing"), fn_body(obj, "charged") + if cb is None or charged is None: + failures.append('FAIL line 0: object.rs: client_backing or charged not found; the scan is broken') + else: + if 'Self::charged(' not in cb or 'with_object(' in cb: + failures.append('FAIL line 0: object.rs: client_backing populates its pages outside charged(), ' + "so a worker's population is charged to the root memory cgroup") + if not re.search(r'client\.charging\(\s*\|\|\s*Self::with_object\(', charged) \ + or charged.count('with_object(') != 1: + failures.append('FAIL line 0: object.rs: charged() populates outside client.charging()') # 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]}, ' @@ -87,14 +122,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-pages', 'root-populate']) 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 objects are charged to the client, publication's are not yet; " + "client-charged pages go to the client's memory cgroup") if __name__ == '__main__': diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index da9196faf2e54..b3d9b3e59cc67 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -446,7 +446,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-pages', + 'root-populate'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)],