diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index 11564c2302e3d..29d03365d7e54 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 rtkit_dump.o +aurora-y += memcg_scope.o retain.o sleep_pd.o cpu_capacity.o g17/mesh_tvb_floor.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 91cde36365033..5eb88170b4155 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,8 +128,39 @@ 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)?; + Self::charged(dev, size, CpuMap::WriteCombined, client, commit) + } + + /// [`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_kernel(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); @@ -402,12 +435,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, @@ -417,14 +470,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 @@ -436,8 +482,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, @@ -476,7 +521,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 { @@ -847,6 +892,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 @@ -917,7 +964,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() { @@ -994,6 +1044,8 @@ impl Pool { order, fence, }); + drop(inner); + self.reap_deferred(super::channel::control_witnessed()); return; } } @@ -1064,7 +1116,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.ready(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/queue/render/generation.rs b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs index 80e55e9f216b6..adb5c4b6c2e9b 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs @@ -108,8 +108,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 25c8ecfaf66da..d903d0ed5c1a4 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -370,7 +370,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 }) } @@ -379,7 +379,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, @@ -460,8 +460,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, @@ -672,8 +671,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 d5c682783700c..3929355abdf94 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -1529,9 +1529,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)?; @@ -1785,7 +1788,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())?); @@ -2007,6 +2010,7 @@ impl Backend { let alloc = super::object::Allocator { dev: &dev, uat: &uat, + client: None, }; let reservation = match reservation { Ok(reservation) => reservation, @@ -2186,6 +2190,7 @@ impl Backend { let alloc = super::object::Allocator { dev: &dev, uat: &uat, + client: None, }; let reservation = match source { Ok(reservation) => reservation, @@ -2280,6 +2285,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 @@ -2320,6 +2326,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(), @@ -2330,7 +2337,8 @@ impl DeferredBatch { } /// Holds nothing: finished, or never used. pub(super) 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() @@ -2344,6 +2352,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)?, @@ -2473,6 +2482,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()); + } } } @@ -4525,6 +4537,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/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 7011c7c0ec059..c6c2c33a5e4e9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -483,6 +483,7 @@ impl Backend { let alloc = Allocator { dev: &dev, uat: &loan.uat, + client: None, }; pair.prepare( &alloc, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index b64fe33b78af6..804bbe02d9722 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( @@ -394,6 +397,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, @@ -934,6 +938,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 6c1d0a2037c55..c4f85e18b14b7 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs @@ -185,6 +185,7 @@ impl Firmware { let alloc = Allocator { dev: &dev, uat: &uat, + client: None, }; pair.prepare(&alloc, &packet, addresses, 0) }); diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index e921f16d8f113..4d17988371d6a 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -44,8 +44,12 @@ //! memory is pinned without `RLIMIT_MEMLOCK`. //! //! 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, @@ -63,6 +67,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. @@ -351,6 +364,27 @@ impl Ledger { }) } + /// Commits `bytes` of kernel memory that `client`'s queues need, whatever the limits. Idle + /// reclaim never releases it, so the bytes count against the client's and the device's + /// limits and unreclaimable limits for the client's later objects, and are given back when + /// the returned [`Commit`] is dropped. + pub(crate) fn commit_kernel(&'static self, client: &Arc, bytes: u64) -> Commit { + for counter in [ + &client.committed, + &self.user_committed, + &client.unreclaimable, + &self.user_unreclaimable, + ] { + counter.fetch_add(bytes, Ordering::AcqRel); + } + Commit { + ledger: self, + client: client.clone(), + bytes, + reclaimable: false, + } + } + /// Adds `bytes` to `client`'s and the device's committed totals, and to their unreclaimable /// ones unless `reclaimable`, if all stay within their limits; otherwise counts a refusal and /// fails with `ENOMEM`, adding nothing. @@ -468,6 +502,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 { @@ -478,11 +528,26 @@ impl Client { unreclaimable: 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) } @@ -849,6 +914,41 @@ 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_kernel(&a, 24 * MIB), None); + ring.set_held(true); + let state = Charge::user(QUEUE.commit_kernel(&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); + // Idle reclaim never releases them. + assert_eq!(QUEUE.user_unreclaimable.load(Ordering::Relaxed), 40 * MIB); + // 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); + assert_eq!(QUEUE.user_unreclaimable.load(Ordering::Relaxed), 0); + Ok(()) + } + static UNRECLAIMABLE: Ledger = Ledger::new(); #[test] @@ -901,6 +1001,20 @@ mod tests { 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(()) + } + #[test] fn exported_limits_follow_idle_reclaim() { static EXPORTED: Ledger = Ledger::new(); 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 d742657bbc2ff..e0f1504c7a333 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()->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-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 3a0f9a6dff734..b7fd10bb96268 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -216,7 +216,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 } @@ -237,12 +237,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] }) } } @@ -348,7 +348,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(); @@ -428,10 +428,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); @@ -480,7 +498,7 @@ def context_source(text): crate::forget_unmapped(); 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(after_release).unwrap(); let mut cached = Vec::new(); let page = mmu::UAT_PGSZ; @@ -512,7 +530,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); @@ -600,7 +618,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), @@ -674,7 +692,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); @@ -707,7 +725,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); @@ -868,7 +886,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); @@ -935,7 +953,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); @@ -987,6 +1005,7 @@ def context_source(text): } fn main() { + now::client_pool_retirement(); now::cached_queue_lifetimes(); now::uncached_pooled(); now::return_classes(); 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..e9f6b053787a1 --- /dev/null +++ b/tools/asahi/g17-queue-object-charge-tests.py @@ -0,0 +1,138 @@ +#!/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; +- 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 / uncharged-pages / +root-populate 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) + 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 + + +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') + # 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]}, ' + "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', + '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; " + "client-charged pages go to the client's memory cgroup") + + +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 d821f8a040ce9..c184c89c2563c 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -668,6 +668,9 @@ 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', 'uncharged-pages', + 'root-populate'], []), 'asahi-idle-vm-reclaim-feature-tests.py': [([], PASS)] + mutations( '--mutation', ['drop-g17', 'drop-m5', 'report-g16'], []), 'asahi-held-ceiling-tests.py': [([], PASS)] + mutations(