From 32c3fe2f71250e6d628a8fb22f92dba2ad2a6c39 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Mon, 30 Nov 2026 01:14:18 -0300 Subject: [PATCH 1/9] drm/asahi: evict idle GPU backing past a ceiling on held memory GEM pages the GPU holds are pinned: unevictable, and released only by the driver's own idle reclaim. Two things bounded them: - **Fixed limits:** 67% of RAM per device and 50% per client, counted on allocated bytes. A fixed share of allocated bytes is not how other drivers bound GPU memory, and it caps a game at half of RAM. - **Global reclaim:** the per-VM shrinkers release an idle VM's backing in step with the rest of reclaim. That is interleaved with swapping out other processes. On an M4 Pro (48 GB), a dq-fast timeline-cases run at -j10 had clients whose GPU memory, together with the desktop, used up RAM and swap. systemd-oomd then killed the desktop's apps, while the driver refused nothing. Bound held memory the way TTM does instead: - **The ceiling:** the bytes the GPU holds at once, user and kernel objects together, have a device-wide ceiling. It defaults to half of RAM, TTM's default limit on the system pages GPU objects may hold (ttm_global_init(), ttm.pages_limit). - **Eviction first:** a user VM bind that populates an object past the ceiling first has the idle backing of user VMs released, up to the excess, as their shrinkers would release it under memory pressure. This uses a device-wide list of the VMs that have shrinkers. Objects userspace asked to keep resident are left alone. - **No refusal:** the bind then populates whatever eviction freed. As in ttm_tt_populate(), which calls ttm_global_swapout() while over ttm_pages_limit and allocates anyway once nothing is left to swap, the ceiling only starts eviction. - **Where a bind still fails:** only where the page allocator or the memory cgroup fails it. GEM shmem pages are allocated with __GFP_RETRY_MAYFAIL | __GFP_NOWARN (drm_gem_shmem_init()), so both return ENOMEM rather than invoke the OOM killer, and Borealis reports VK_ERROR_OUT_OF_DEVICE_MEMORY. - **Not checked:** restoring an evicted VM at its next submission, kernel objects and CPU mapping faults. They count towards the ceiling but evict nothing. The fixed limits become opt-in: - **asahi.client_mem_limit_pct** now defaults to 0, no limit. - **asahi.mem_limit_pct** now sets where eviction starts: 0, the default, is half of RAM, and 100 or more means never. It no longer sets a device limit that refuses. - **gpu_mem_limit_pct** (sysfs) still sets both refusing limits, for testing. With no limit, GET_PARAMS reports 0 and 0. Borealis then sizes its Vulkan heap at half of RAM (hk_resolve_uma_sysmem_heap()), the size the old 50% client limit gave it. gpu_memory reports the ceiling as held_limit. Tests: - **KUnit:** under the ceiling nothing is evicted; past it the excess is asked of idle backing and population runs; with nothing idle it still runs; only population's own ENOMEM fails it, and that counts no refusal; the ceiling is half of RAM at 8, 16, 24, 48 and 64 GB. - **Host test** (asahi-held-ceiling-tests.py): a user bind populates through the ceiling; a VM's shrinker owner joins the eviction list and leaves it before its shrinkers are freed; the ceiling refuses nothing. Each is checked by a mutation. g15-probe-init-tests also checks that the eviction list is ready before the adapters register. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/asahi_core.rs | 10 +- drivers/gpu/drm/asahi/gem.rs | 6 +- drivers/gpu/drm/asahi/memacct.rs | 139 +++++++++++++++++++++--- drivers/gpu/drm/asahi/mmu.rs | 2 +- drivers/gpu/drm/asahi/mmu/residency.rs | 38 +++++++ drivers/gpu/drm/asahi/sysfs.c | 6 +- tools/asahi/asahi-held-ceiling-tests.py | 91 ++++++++++++++++ tools/asahi/g15-probe-init-tests.py | 7 ++ tools/asahi/run-host-tests.py | 2 + 9 files changed, 278 insertions(+), 23 deletions(-) create mode 100644 tools/asahi/asahi-held-ceiling-tests.py diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b236766ef8697..6e02d8b55aeff 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -112,6 +112,8 @@ impl kernel::InPlaceModule for DriverModule { // SAFETY: Module init runs once, before either adapter is registered below. unsafe { queue_share::init() }; // SAFETY: Module init runs once, before either adapter is registered below. + unsafe { mmu::residency_init() }; + // SAFETY: Module init runs once, before either adapter is registered below. unsafe { g17::exec_share::init() }; // SAFETY: Module init runs once, before either adapter is registered below. unsafe { g17::init() }; @@ -244,12 +246,12 @@ module! { description: "Export AGX firmware stats to sysfs (1 = on, 0 = off)", }, mem_limit_pct: u32 { - default: 67, - description: "Device-wide GPU memory limit in percent of RAM (0 or >= 100: none)", + default: 0, + description: "GPU-held memory in percent of RAM past which idle GPU backing is evicted first (0: half of RAM, >= 100: never)", }, client_mem_limit_pct: u32 { - default: 50, - description: "Per-client GPU memory limit in percent of RAM (0: the device limit)", + default: 0, + description: "Per-client GPU memory limit in percent of RAM (0: none)", }, oom_attribution: u8 { default: 1, diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index 2f071da87d360..dedad6f67441f 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -152,7 +152,11 @@ pub(crate) fn held_user_sg_table<'a>( { return Err(EACCES); } - mapped_sg_table(gem, dev) + if !gem.charge.adds_held() { + return mapped_sg_table(gem, dev); + } + // Populating the pages for the GPU first evicts idle backing past the ceiling on held memory. + memacct::LEDGER.populate(gem.size() as u64, mmu::evict_idle, || mapped_sg_table(gem, dev)) } /// Takes the SG table of `gem` for a device mapping that [`held_sg_table`] or diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index c6fc7202292ab..3ed92235e11ee 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -26,10 +26,16 @@ //! `gpu_memory` sysfs file next to `agx_stats`. The device also totals the bytes of //! objects that userspace asked to keep resident (which idle reclaim releases after //! the other objects of their VM), in `gpu_memory`. -//! - A new user object is admitted only while its client stays within a per-client -//! limit and the device within a device-wide limit, both fractions of RAM. -//! A refused allocation fails with `ENOMEM`, which userspace reports as -//! out-of-device-memory, instead of pushing the machine into a global OOM. +//! - When the GPU is to hold more pages than a device-wide ceiling, half of RAM by +//! default, user and kernel objects together, the idle backing of user VMs is +//! released first, as TTM swaps out buffer objects over its own limit +//! ([`Ledger::populate`]). The ceiling only starts eviction: like TTM's, it never +//! refuses. An allocation fails only where the page allocator or the memory cgroup +//! fails it: GEM pages are allocated with `__GFP_RETRY_MAYFAIL`, so either returns +//! `ENOMEM` instead of calling the OOM killer. +//! - Opt-in limits (none by default) admit a new user object only while its client, +//! and the device, stay within a fraction of RAM. A refused allocation fails with +//! `ENOMEM`, which userspace reports as out-of-device-memory. //! //! Imported dma-bufs are charged to their exporter and are not counted here. //! Kernel objects (firmware structures, per-queue buffers and the global heaps) @@ -72,6 +78,9 @@ pub(crate) struct Ledger { pub(crate) client_limit: AtomicU64, /// Size of the live user objects kept resident at userspace's request. pub(crate) user_kept: AtomicU64, + /// Held bytes, user and kernel resident together, past which idle backing is evicted + /// before more is populated (0: none). + pub(crate) held_limit: AtomicU64, } // Keep the Rust half of the C sysfs layout contract checked as well. @@ -79,7 +88,8 @@ const _: () = { assert!(core::mem::offset_of!(Ledger, refused) == 24); assert!(core::mem::offset_of!(Ledger, client_limit) == 40); assert!(core::mem::offset_of!(Ledger, user_kept) == 48); - assert!(core::mem::size_of::() == 56); + assert!(core::mem::offset_of!(Ledger, held_limit) == 56); + assert!(core::mem::size_of::() == 64); }; /// The ledger of the (single) AGX GPU. @@ -173,24 +183,48 @@ impl Ledger { limit: AtomicU64::new(0), client_limit: AtomicU64::new(0), user_kept: AtomicU64::new(0), + held_limit: AtomicU64::new(0), } } - /// Sets the limits from the module parameters and the amount of RAM. + /// Sets the limits and the ceiling on held memory from the module parameters and the amount + /// of RAM. pub(crate) fn configure(&self) { - let limits = limits_for( - total_ram_bytes(), - module_parameters::mem_limit_pct.value(), - module_parameters::client_mem_limit_pct.value(), - ); + let total = total_ram_bytes(); + let limits = limits_for(total, 0, module_parameters::client_mem_limit_pct.value()); self.set_limits(limits); + let held = held_ceiling(total, module_parameters::mem_limit_pct.value()); + self.held_limit.store(held, Ordering::Relaxed); pr_info!( - "GPU memory limits: device {} MiB, per client {} MiB (0 = none)\n", - limits.device >> 20, - limits.client >> 20 + "GPU memory: per-client limit {} MiB (0 = none), idle backing evicted past {} MiB held\n", + limits.client >> 20, + held >> 20 ); } + /// Runs `populate`, which makes the GPU hold `bytes` more of a user object, after making + /// room for them under the ceiling on held memory: past it, `evict` is asked to release the + /// excess of idle backing first. Whatever it releases, `populate` runs; only its own error + /// fails this, as TTM populates a buffer object after swapping out what it could + /// (`ttm_tt_populate()`, `ttm_global_swapout()`). + pub(crate) fn populate( + &self, + bytes: u64, + evict: impl FnOnce(u64), + populate: impl FnOnce() -> Result, + ) -> Result { + let limit = self.held_limit.load(Ordering::Relaxed); + let held = self + .user_resident + .load(Ordering::Acquire) + .saturating_add(self.kernel_resident.load(Ordering::Acquire)) + .saturating_add(bytes); + if limit != 0 && held > limit { + evict(held - limit); + } + populate() + } + /// Admission capacities exported in the optional GET_PARAMS tail. pub(crate) fn limits(&self) -> Limits { Limits { @@ -370,6 +404,17 @@ impl Drop for WindowShare { } } +/// The held bytes past which idle backing is evicted, for `total_ram` bytes of RAM and +/// `asahi.mem_limit_pct`: by default (0) half of RAM, the limit TTM sets on the system pages GPU +/// objects may hold before it swaps them out (`ttm_global_init()`, `ttm.pages_limit`); otherwise +/// that percentage of RAM, and none from 100 up. +pub(crate) fn held_ceiling(total_ram: u64, pct: u32) -> u64 { + match pct { + 0 => total_ram / 2, + pct => pct_of(total_ram, pct), + } +} + /// Bytes of a user object reserved against the limits. pub(crate) struct Commit { ledger: &'static Ledger, @@ -455,6 +500,12 @@ impl Charge { Self::user(commit, mm) } + /// Whether populating the object for the GPU adds held memory: a user object whose pages are + /// not held yet. Imports and user-memory objects never add any. + pub(crate) fn adds_held(&self) -> bool { + matches!(self.kind, Kind::User { .. }) && !self.held.load(Ordering::Acquire) + } + fn pages(&self) -> isize { isize::try_from(self.bytes / PAGE_SIZE as u64).unwrap_or(isize::MAX) } @@ -560,8 +611,7 @@ mod tests { const MIB: u64 = 1 << 20; #[test] - fn default_limits_follow_ram() { - // The module parameter defaults. + fn opt_in_limits_follow_ram() { let l = limits_for(8 * GIB, 67, 50); assert_eq!(l.device, 8 * GIB * 67 / 100); assert_eq!(l.client, 4 * GIB); @@ -633,6 +683,63 @@ mod tests { Ok(()) } + #[test] + fn the_held_ceiling_is_half_of_ram_by_default() { + for gib in [8u64, 16, 24, 48, 64] { + assert_eq!(held_ceiling(gib * GIB, 0), gib * GIB / 2); + assert_eq!(held_ceiling(gib * GIB, 25), gib * GIB / 4); + assert_eq!(held_ceiling(gib * GIB, 100), 0); + } + } + + static CEILING: Ledger = Ledger::new(); + + #[test] + fn past_the_ceiling_idle_backing_is_evicted_and_population_proceeds() -> Result { + CEILING.held_limit.store(64 * MIB, Ordering::Relaxed); + let a = Client::new()?; + let idle = Charge::user(CEILING.admit(&a, 32 * MIB)?, None); + idle.set_held(true); + let kernel = Charge::kernel(&CEILING, 8 * MIB); + kernel.set_held(true); + // Within the ceiling: nothing is evicted. + assert_eq!(CEILING.populate(24 * MIB, |_| panic!("evicted within the ceiling"), || Ok(1))?, 1); + // Past it, the excess is asked of idle backing, which releases it, and population runs. + let mut idle = Some(idle); + let mut asked = 0; + CEILING.populate(40 * MIB, |over| { + asked = over; + drop(idle.take()); + }, || Ok(()))?; + assert_eq!(asked, 16 * MIB); + assert!(idle.is_none()); + // With nothing idle to evict, population still runs. + let mut ran = false; + CEILING.populate(128 * MIB, |_| {}, || { ran = true; Ok(()) })?; + assert!(ran); + // Only population's own failure (a mayfail ENOMEM) fails it, and it is not a refusal. + assert_eq!(CEILING.populate(128 * MIB, |_| {}, || Err::<(), _>(ENOMEM)), Err(ENOMEM)); + assert_eq!(CEILING.populate(MIB, |_| panic!(), || Err::<(), _>(ENOMEM)), Err(ENOMEM)); + assert_eq!(CEILING.refused.load(Ordering::Relaxed), 0); + // No ceiling: nothing is ever evicted. + CEILING.held_limit.store(0, Ordering::Relaxed); + CEILING.populate(u64::MAX, |_| panic!("evicted without a ceiling"), || Ok(()))?; + drop(kernel); + Ok(()) + } + + #[test] + fn only_unheld_user_objects_add_held_memory() -> Result { + let a = Client::new()?; + let user = Charge::user(CEILING.admit(&a, MIB)?, None); + assert!(user.adds_held()); + user.set_held(true); + assert!(!user.adds_held()); + assert!(!Charge::none().adds_held()); + assert!(!Charge::kernel(&CEILING, MIB).adds_held()); + Ok(()) + } + static KERNEL: Ledger = Ledger::new(); #[test] diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index ae4a95da16b87..b355b1195f478 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -135,7 +135,7 @@ pub(crate) use t8152::G18ExecutionContext; pub(crate) type T8140VmJobGuard = VmJobGuard; #[cfg(CONFIG_DRM_ASAHI_M5)] pub(crate) use m5_context::M5ExecutionContext; -pub(crate) use residency::{Gate as ResidencyGate, VmShrinker}; +pub(crate) use residency::{evict_idle, init as residency_init, Gate as ResidencyGate, VmShrinker}; /// PPL magic number for the handoff region const PPL_MAGIC: u64 = 0x4b1d000000000002; diff --git a/drivers/gpu/drm/asahi/mmu/residency.rs b/drivers/gpu/drm/asahi/mmu/residency.rs index d25e2c0278bb4..593e88da50e02 100644 --- a/drivers/gpu/drm/asahi/mmu/residency.rs +++ b/drivers/gpu/drm/asahi/mmu/residency.rs @@ -20,6 +20,39 @@ const RESTORE_BACKOFF_FACTOR: u64 = 16; /// would restore whatever reclaim released, synchronously in its next job. const RECLAIM_QUIET_NS: u64 = 2000000000; +kernel::sync::global_lock! { + // SAFETY: Module initialization initializes this lock before registering adapters. + unsafe(uninit) static IDLE_VMS: Mutex> = KVec::new(); +} + +/// Initializes the list of VMs whose idle backing [`evict_idle`] may release. +/// +/// # Safety +/// +/// Called exactly once per module instance, before any VM is created. +pub(crate) unsafe fn init() { + // SAFETY: The module initializer establishes the single-call ordering above. + unsafe { IDLE_VMS.init() }; +} + +/// Releases up to `bytes` of the idle backing of every user VM, as the first of a VM's +/// shrinkers would under memory pressure: for population past the ceiling on held memory +/// (`memacct::Ledger::populate`). Objects userspace asked to keep resident stay: the ceiling +/// only starts eviction, and only reclaim that nothing else relieves releases those. +pub(crate) fn evict_idle(bytes: u64) { + let mut target = + usize::try_from(bytes.div_ceil(kernel::page::PAGE_SIZE as u64)).unwrap_or(usize::MAX); + let owners = IDLE_VMS.lock(); + for &owner in owners.iter() { + if target == 0 { + break; + } + // SAFETY: A shrinker owner leaves the list, under this lock, before it is freed. + let owner = unsafe { &*(owner as *const VmShrinker) }; + target = target.saturating_sub(owner.vm.reclaim_idle_pages(target, false)); + } +} + fn now_ns() -> u64 { ::ktime_get() as u64 } @@ -331,6 +364,9 @@ impl VmShrinker { kernel::bindings::shrinker_register(raw); kernel::bindings::shrinker_register(kept); } + IDLE_VMS + .lock() + .push(core::ptr::from_ref(&*owner) as usize, GFP_KERNEL)?; Ok(owner) } @@ -400,6 +436,8 @@ impl VmShrinker { impl Drop for VmShrinker { fn drop(&mut self) { + let this = core::ptr::from_ref(&*self) as usize; + IDLE_VMS.lock().retain(|owner| *owner != this); for raw in [self.kept, self.raw] { if !raw.is_null() { // SAFETY: This owns the sole registration; free drains callbacks diff --git a/drivers/gpu/drm/asahi/sysfs.c b/drivers/gpu/drm/asahi/sysfs.c index bf827d9d3fd5d..844a36ae18411 100644 --- a/drivers/gpu/drm/asahi/sysfs.c +++ b/drivers/gpu/drm/asahi/sysfs.c @@ -46,6 +46,7 @@ struct asahi_gpu_memory { u64 limit; u64 client_limit; u64 user_kept; + u64 held_limit; }; struct asahi_stats_attribute { @@ -243,6 +244,8 @@ static ssize_t gpu_memory_show(struct device *dev, (unsigned long long)READ_ONCE(mem->refused)); n += scnprintf(buf + n, PAGE_SIZE - n, "user_kept %llu\n", (unsigned long long)READ_ONCE(mem->user_kept)); + n += scnprintf(buf + n, PAGE_SIZE - n, "held_limit %llu\n", + (unsigned long long)READ_ONCE(mem->held_limit)); return n; } @@ -298,7 +301,8 @@ int asahi_sysfs_register(struct device *dev, const void *snapshot, BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, refused) != 24); BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, client_limit) != 40); BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, user_kept) != 48); - BUILD_BUG_ON(sizeof(struct asahi_gpu_memory) != 56); + BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, held_limit) != 56); + BUILD_BUG_ON(sizeof(struct asahi_gpu_memory) != 64); BUILD_BUG_ON(offsetof(struct asahi_stats_snapshot, pstate) != 16); BUILD_BUG_ON(offsetof(struct asahi_stats_snapshot, busy_ns) != 40); diff --git a/tools/asahi/asahi-held-ceiling-tests.py b/tools/asahi/asahi-held-ceiling-tests.py new file mode 100644 index 0000000000000..e5267af76dd7f --- /dev/null +++ b/tools/asahi/asahi-held-ceiling-tests.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""The ceiling on GPU-held memory evicts idle backing and never refuses. + +KUnit (asahi_memacct) checks Ledger::populate itself. This checks how it is +wired, which KUnit cannot reach without a GPU: + +- a user VM bind populates through Ledger::populate with evict_idle + (gem.rs, held_user_sg_table); +- every VM shrinker owner joins the eviction list when it is registered and + leaves it before its shrinkers are freed (mmu/residency.rs); evict_idle + dereferences listed owners, so leaving it late would be a use after free; +- Ledger::populate fails only with populate's own error: the ceiling starts + eviction and refuses nothing (memacct.rs). + +--mutation skip-populate / no-unregister / late-unregister / refuse inject +each fault and must be caught. +""" +import argparse +import sys +from pathlib import Path + +ASAHI = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi' + + +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 sources(mutation): + files = {n: (ASAHI / n).read_text() for n in ('gem.rs', 'mmu/residency.rs', 'memacct.rs')} + if mutation == 'skip-populate': + files['gem.rs'] = files['gem.rs'].replace('if !gem.charge.adds_held() {', 'if true {', 1) + elif mutation == 'no-unregister': + files['mmu/residency.rs'] = files['mmu/residency.rs'].replace( + 'IDLE_VMS.lock().retain(|owner| *owner != this);', '', 1) + elif mutation == 'late-unregister': + r = files['mmu/residency.rs'] + line = ' IDLE_VMS.lock().retain(|owner| *owner != this);\n' + r = r.replace(line, '', 1) + r = r.replace(' unsafe { kernel::bindings::shrinker_free(raw) };\n }\n }\n', + ' unsafe { kernel::bindings::shrinker_free(raw) };\n }\n }\n' + line, 1) + files['mmu/residency.rs'] = r + elif mutation == 'refuse': + files['memacct.rs'] = files['memacct.rs'].replace( + 'evict(held - limit);', 'evict(held - limit);\n return Err(ENOMEM);', 1) + return files + + +def check(files): + failures = [] + bind = item(files['gem.rs'], 'pub(crate) fn held_user_sg_table') + guard = bind.find('if !gem.charge.adds_held()') + via = bind.find('memacct::LEDGER.populate(gem.size() as u64, mmu::evict_idle,') + if guard < 0 or via < 0 or 'return mapped_sg_table' not in bind[guard:via]: + failures.append('FAIL line 1: a user bind does not populate through Ledger::populate') + res = files['mmu/residency.rs'] + new = item(res, 'pub(crate) fn new(vm: &crate::mmu::Vm) -> Result>') + if 'IDLE_VMS' not in new or new.find('IDLE_VMS') < new.find('shrinker_register(kept)'): + failures.append('FAIL line 2: a shrinker owner does not join the eviction list after registering') + drop = item(res, 'impl Drop for VmShrinker') + leave = drop.find('IDLE_VMS.lock().retain(|owner| *owner != this);') + if leave < 0 or leave > drop.find('shrinker_free'): + failures.append('FAIL line 3: a shrinker owner leaves the eviction list late or never') + populate = item(files['memacct.rs'], 'pub(crate) fn populate(') + body = populate[populate.index('{'):] + if 'Err(' in body or '?' in body or not body.rstrip('}').rstrip().endswith('populate()'): + failures.append('FAIL line 4: Ledger::populate can fail other than through populate()') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['skip-populate', 'no-unregister', 'late-unregister', 'refuse']) + args = parser.parse_args() + failures = check(sources(args.mutation)) + for f in failures: + print(f) + if failures: + sys.exit(1) + print('ok: binds evict past the ceiling and are never refused for it') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g15-probe-init-tests.py b/tools/asahi/g15-probe-init-tests.py index 04e344f6f3144..8325d47481703 100644 --- a/tools/asahi/g15-probe-init-tests.py +++ b/tools/asahi/g15-probe-init-tests.py @@ -81,6 +81,7 @@ def item(text, marker): static ACTIVATED: Cell = const { Cell::new(false) }; static BINDING_READY: Cell = const { Cell::new(false) }; static QUEUE_SHARE_READY: Cell = const { Cell::new(false) }; + static RESIDENCY_READY: Cell = const { Cell::new(false) }; static EXEC_SHARE_READY: Cell = const { Cell::new(false) }; static G17_READY: Cell = const { Cell::new(false) }; static ATTACH_ERROR: Cell = const { Cell::new(false) }; @@ -161,6 +162,10 @@ def item(text, marker): mod queue_share { pub unsafe fn init() { crate::QUEUE_SHARE_READY.set(true); } } +// So must the list of VMs whose idle backing the held-memory ceiling evicts. +mod mmu { + pub unsafe fn residency_init() { crate::RESIDENCY_READY.set(true); } +} // So must the registry of execution contexts shared by a VM's G17P queues. mod g17 { pub unsafe fn init() { crate::G17_READY.set(true); } @@ -184,6 +189,7 @@ def item(text, marker): pub fn new(name: &'static std::ffi::CStr, _module: &'static ThisModule) -> impl PinInit { assert!(BINDING_READY.get(), "adapter registered before binding registry init"); assert!(QUEUE_SHARE_READY.get(), "adapter registered before queue-share registry init"); + assert!(RESIDENCY_READY.get(), "adapter registered before the idle-VM eviction list init"); assert!(EXEC_SHARE_READY.get(), "adapter registered before execution-context share registry init"); assert!(G17_READY.get(), "adapter registered before g17 compute-waiter target registry init"); try_pin_init!(Self { @@ -247,6 +253,7 @@ def item(text, marker): MODULE_READY.store(true, Ordering::Release); BINDING_READY.set(false); QUEUE_SHARE_READY.set(false); + RESIDENCY_READY.set(false); EXEC_SHARE_READY.set(false); G17_READY.set(false); FAIL_ALLOC.set(fail_alloc); TOUCH.set(touch); PROBE_ERROR.set(error); diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index e829bcd9434dc..2d09ba850b648 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)], + 'asahi-held-ceiling-tests.py': [([], PASS)] + mutations( + '--mutation', ['skip-populate', 'no-unregister', 'late-unregister', 'refuse'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)], From ba10491f9e0b670962c36b5351e08c923b9dd2a2 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 16:14:12 -0500 Subject: [PATCH 2/9] drm/asahi: honor explicit device limits alongside idle VM reclaim Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/asahi_core.rs | 2 +- drivers/gpu/drm/asahi/g17/mod.rs | 3 +++ drivers/gpu/drm/asahi/memacct.rs | 8 +++++--- drivers/gpu/drm/asahi/mmu/residency.rs | 2 +- include/uapi/drm/asahi_drm.h | 7 +++++++ tools/asahi/asahi-held-ceiling-tests.py | 6 ++++++ 6 files changed, 23 insertions(+), 5 deletions(-) diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 6e02d8b55aeff..b46fd26ed06e3 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -247,7 +247,7 @@ module! { }, mem_limit_pct: u32 { default: 0, - description: "GPU-held memory in percent of RAM past which idle GPU backing is evicted first (0: half of RAM, >= 100: never)", + description: "Device GPU memory limit in percent of RAM (0 or >= 100: unlimited); idle reclaim above this percentage (0: half RAM, >= 100: disabled)", }, client_mem_limit_pct: u32 { default: 0, diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 37c6e84473b0f..f95ed807145b7 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -3017,6 +3017,9 @@ impl gpu::Gpu for Gpu { | sync_output::FEATURE_CUMULATIVE_SIGNALS | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT | compute_channel_features(pairs::compute_channels_per_owner()); + if crate::memacct::LEDGER.held_limit.load(Ordering::Relaxed) != 0 { + params.features |= uapi::DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM as u64; + } let variant = self.shared.variant; params.features |= ordered_partial_renders_feature(variant.fragment_busy, pairs::per_owner()); diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index 3ed92235e11ee..04f92aec2f012 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -191,12 +191,14 @@ impl Ledger { /// of RAM. pub(crate) fn configure(&self) { let total = total_ram_bytes(); - let limits = limits_for(total, 0, module_parameters::client_mem_limit_pct.value()); + let device_pct = module_parameters::mem_limit_pct.value(); + let limits = limits_for(total, device_pct, module_parameters::client_mem_limit_pct.value()); self.set_limits(limits); - let held = held_ceiling(total, module_parameters::mem_limit_pct.value()); + let held = held_ceiling(total, device_pct); self.held_limit.store(held, Ordering::Relaxed); pr_info!( - "GPU memory: per-client limit {} MiB (0 = none), idle backing evicted past {} MiB held\n", + "GPU memory: device limit {} MiB, per-client limit {} MiB, idle reclaim above {} MiB held (0 = disabled)\n", + limits.device >> 20, limits.client >> 20, held >> 20 ); diff --git a/drivers/gpu/drm/asahi/mmu/residency.rs b/drivers/gpu/drm/asahi/mmu/residency.rs index 593e88da50e02..4cc49b9ae84a4 100644 --- a/drivers/gpu/drm/asahi/mmu/residency.rs +++ b/drivers/gpu/drm/asahi/mmu/residency.rs @@ -42,7 +42,7 @@ pub(crate) unsafe fn init() { pub(crate) fn evict_idle(bytes: u64) { let mut target = usize::try_from(bytes.div_ceil(kernel::page::PAGE_SIZE as u64)).unwrap_or(usize::MAX); - let owners = IDLE_VMS.lock(); + let Some(owners) = IDLE_VMS.try_lock() else { return }; for &owner in owners.iter() { if target == 0 { break; diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 99fb3de0601e3..f834a1066c8a7 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -625,6 +625,13 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_COMPUTE_TI_SPILL_LAUNCH ((1ULL) << 47) +/* + * Before populating new user backing past the device's held-memory threshold, + * the kernel attempts to reclaim idle GPU VM backing. An explicit allocation + * limit still applies. Reclaim is best effort and may release no pages. + */ +#define DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM ((1ULL) << 49) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 diff --git a/tools/asahi/asahi-held-ceiling-tests.py b/tools/asahi/asahi-held-ceiling-tests.py index e5267af76dd7f..8f669484d0f08 100644 --- a/tools/asahi/asahi-held-ceiling-tests.py +++ b/tools/asahi/asahi-held-ceiling-tests.py @@ -68,6 +68,12 @@ def check(files): leave = drop.find('IDLE_VMS.lock().retain(|owner| *owner != this);') if leave < 0 or leave > drop.find('shrinker_free'): failures.append('FAIL line 3: a shrinker owner leaves the eviction list late or never') + config = item(files['memacct.rs'], 'pub(crate) fn configure(') + if ('let device_pct = module_parameters::mem_limit_pct.value();' not in config + or 'limits_for(total, device_pct,' not in config): + failures.append('FAIL: configured device cap is lost before admission') + if 'IDLE_VMS.try_lock()' not in item(res, 'pub(crate) fn evict_idle('): + failures.append('FAIL: bind waits behind another reclaim walk') populate = item(files['memacct.rs'], 'pub(crate) fn populate(') body = populate[populate.index('{'):] if 'Err(' in body or '?' in body or not body.rstrip('}').rstrip().endswith('populate()'): From 8c2b452e520b3ec599282bc288a4786df572f832 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Tue, 1 Dec 2026 18:42:06 -0300 Subject: [PATCH 3/9] drm/asahi: report idle VM reclaim wherever user VMs reclaim DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM (bit 49) says the kernel attempts idle-VM reclaim before populating new user backing. Userspace can then drop reserves of its own against free memory. G17 reported it inline whenever the held-memory ceiling is set. M5 user VMs get the same residency gate and shrinkers from `Vm::with_status()`, so a bind there evicts idle backing the same way, but M5 did not report the bit. Decide it in one place, `mmu::idle_vm_reclaim_feature()`, next to the eviction it describes: - it reports the bit while the ceiling is set; - G17 and M5 call it from get_params; - every backend without user-VM reclaim reports nothing. Tests: - **KUnit:** the bit is set only with a ceiling. - **Host test** (asahi-idle-vm-reclaim-feature-tests.py): every backend whose new_vm reaches `with_status()` reports the bit, and no other backend does. Three injected faults are caught. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/g17/mod.rs | 4 +- drivers/gpu/drm/asahi/m5/drm.rs | 2 + drivers/gpu/drm/asahi/mmu.rs | 4 +- drivers/gpu/drm/asahi/mmu/residency.rs | 30 +++++++ .../asahi-idle-vm-reclaim-feature-tests.py | 90 +++++++++++++++++++ tools/asahi/run-host-tests.py | 2 + 6 files changed, 128 insertions(+), 4 deletions(-) create mode 100644 tools/asahi/asahi-idle-vm-reclaim-feature-tests.py diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index f95ed807145b7..dcf7c61a21e19 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -3015,11 +3015,9 @@ impl gpu::Gpu for Gpu { | uapi::DRM_ASAHI_FEATURE_ORDERED_FRAGMENT_BARRIERS as u64 | u64::from(uapi::drm_asahi_feature_DRM_ASAHI_FEATURE_COMPUTE_NO_QUERY_ACCESS) | sync_output::FEATURE_CUMULATIVE_SIGNALS + | crate::mmu::idle_vm_reclaim_feature() | crate::file::DRM_ASAHI_FEATURE_COMPUTE_TIMEOUT | compute_channel_features(pairs::compute_channels_per_owner()); - if crate::memacct::LEDGER.held_limit.load(Ordering::Relaxed) != 0 { - params.features |= uapi::DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM as u64; - } let variant = self.shared.variant; params.features |= ordered_partial_renders_feature(variant.fragment_busy, pairs::per_owner()); diff --git a/drivers/gpu/drm/asahi/m5/drm.rs b/drivers/gpu/drm/asahi/m5/drm.rs index 4ee01fced0310..f87cb0cdada00 100644 --- a/drivers/gpu/drm/asahi/m5/drm.rs +++ b/drivers/gpu/drm/asahi/m5/drm.rs @@ -152,6 +152,8 @@ impl gpu::Gpu for M5DrmGpu { params.gpu_hal_generation = 300; // One hardware command per submission. params.max_commands_per_submission = 1; + // Its user VMs have idle reclaim (`new_user_vm()`, `Vm::with_status()`). + params.features |= crate::mmu::idle_vm_reclaim_feature(); Ok(()) } fn supports_vm_status(&self) -> bool { true } diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index b355b1195f478..62e5960c7796b 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -135,7 +135,9 @@ pub(crate) use t8152::G18ExecutionContext; pub(crate) type T8140VmJobGuard = VmJobGuard; #[cfg(CONFIG_DRM_ASAHI_M5)] pub(crate) use m5_context::M5ExecutionContext; -pub(crate) use residency::{evict_idle, init as residency_init, Gate as ResidencyGate, VmShrinker}; +pub(crate) use residency::{ + evict_idle, idle_vm_reclaim_feature, init as residency_init, Gate as ResidencyGate, VmShrinker, +}; /// PPL magic number for the handoff region const PPL_MAGIC: u64 = 0x4b1d000000000002; diff --git a/drivers/gpu/drm/asahi/mmu/residency.rs b/drivers/gpu/drm/asahi/mmu/residency.rs index 4cc49b9ae84a4..a34a0b37bff69 100644 --- a/drivers/gpu/drm/asahi/mmu/residency.rs +++ b/drivers/gpu/drm/asahi/mmu/residency.rs @@ -53,6 +53,36 @@ pub(crate) fn evict_idle(bytes: u64) { } } +/// `DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM` for a backend whose user VMs have idle reclaim (a +/// residency gate and shrinkers): a user VM bind that populates past the ceiling on held memory +/// evicts idle backing first ([`evict_idle`]). Without a ceiling (`held_limit` 0) it never does. +pub(crate) fn idle_vm_reclaim_feature() -> u64 { + idle_vm_reclaim_feature_for( + crate::memacct::LEDGER + .held_limit + .load(core::sync::atomic::Ordering::Relaxed), + ) +} + +fn idle_vm_reclaim_feature_for(held_limit: u64) -> u64 { + if held_limit != 0 { + kernel::uapi::DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM as u64 + } else { + 0 + } +} + +#[kernel::macros::kunit_tests(asahi_idle_vm_reclaim_feature)] +mod feature_tests { + use super::*; + + #[test] + fn reported_only_with_a_ceiling() { + assert_eq!(idle_vm_reclaim_feature_for(1 << 30), 1 << 49); + assert_eq!(idle_vm_reclaim_feature_for(0), 0); + } +} + fn now_ns() -> u64 { ::ktime_get() as u64 } diff --git a/tools/asahi/asahi-idle-vm-reclaim-feature-tests.py b/tools/asahi/asahi-idle-vm-reclaim-feature-tests.py new file mode 100644 index 0000000000000..1c3000fdce1b2 --- /dev/null +++ b/tools/asahi/asahi-idle-vm-reclaim-feature-tests.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM is reported exactly where idle reclaim runs. + +A backend's user VMs reclaim idle backing when they carry a residency gate: +Vm::with_status() gives them one, VM_CREATE then registers their shrinkers, +and a bind past the held-memory ceiling evicts through them (evict_idle). +Every backend whose new_vm reaches with_status() must report the feature from +its get_params, through mmu::idle_vm_reclaim_feature() (which reports it only +while the ceiling is set), and no other backend may report it. + +--mutation drop-g17 / drop-m5 / report-g16 inject each fault and must be +caught. +""" +import argparse +import sys +from pathlib import Path + +ASAHI = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi' +REPORT = 'crate::mmu::idle_vm_reclaim_feature()' + + +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 backends(mutation): + files = {} + for path in sorted(ASAHI.rglob('*.rs')): + text = path.read_text() + if 'fn get_params(&self, params: &mut uapi::drm_asahi_params_global)' in text and 'fn new_vm(' in text: + files[str(path.relative_to(ASAHI))] = text + if mutation == 'drop-g17': + files['g17/mod.rs'] = files['g17/mod.rs'].replace(' | ' + REPORT + '\n', '', 1) + elif mutation == 'drop-m5': + files['m5/drm.rs'] = files['m5/drm.rs'].replace('params.features |= ' + REPORT + ';', '', 1) + elif mutation == 'report-g16': + files['g16/mod.rs'] = files['g16/mod.rs'].replace( + 'fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result {', + 'fn get_params(&self, params: &mut uapi::drm_asahi_params_global) -> Result {\n' + ' params.features |= ' + REPORT + ';', 1) + return files + + +def reclaims(name, text): + vm = item(text, 'fn new_vm(') + if '.with_status()' in vm: + return True + # A backend may build its user VMs in a helper of its own directory. + if 'new_user_vm(' in vm: + for path in (ASAHI / name).parent.rglob('*.rs'): + src = path.read_text() + if 'fn new_user_vm(' in src and '.with_status()' in item(src, 'fn new_user_vm('): + return True + return False + + +def check(files): + failures = [] + seen = 0 + for name, text in files.items(): + reports = REPORT in item(text, 'fn get_params(&self, params: &mut uapi::drm_asahi_params_global)') + if reclaims(name, text) != reports: + failures.append(f'FAIL line 1: {name}: idle reclaim {reclaims(name, text)}, reported {reports}') + seen += reports + if seen < 2: + failures.append(f'FAIL line 2: only {seen} backends report the feature; the scan is broken') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['drop-g17', 'drop-m5', 'report-g16']) + args = parser.parse_args() + failures = check(backends(args.mutation)) + for f in failures: + print(f) + if failures: + sys.exit(1) + print('ok: IDLE_VM_RECLAIM is reported exactly by the backends whose user VMs reclaim') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 2d09ba850b648..6f61a5ec597cf 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)], + 'asahi-idle-vm-reclaim-feature-tests.py': [([], PASS)] + mutations( + '--mutation', ['drop-g17', 'drop-m5', 'report-g16'], []), 'asahi-held-ceiling-tests.py': [([], PASS)] + mutations( '--mutation', ['skip-populate', 'no-unregister', 'late-unregister', 'refuse'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], From 86241547ea66628befdcd998465643ba250005d2 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Tue, 1 Dec 2026 18:47:05 -0300 Subject: [PATCH 4/9] drm/uapi: asahi: name DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM in its comment Every feature bit defined outside enum drm_asahi_feature opens its comment with its name and closes with "A feature bit like those of enum drm_asahi_feature, defined here like bit 32." Bit 49 had neither. Add both, keeping the description as it was, so userspace headers mirror one settled text. Signed-off-by: Jonathan Goyvaerts --- include/uapi/drm/asahi_drm.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index f834a1066c8a7..3e14315177b8d 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -626,9 +626,11 @@ enum drm_asahi_feature { #define DRM_ASAHI_FEATURE_COMPUTE_TI_SPILL_LAUNCH ((1ULL) << 47) /* - * Before populating new user backing past the device's held-memory threshold, - * the kernel attempts to reclaim idle GPU VM backing. An explicit allocation - * limit still applies. Reclaim is best effort and may release no pages. + * DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM: before populating new user backing past + * the device's held-memory threshold, the kernel attempts to reclaim idle GPU + * VM backing. An explicit allocation limit still applies. Reclaim is best + * effort and may release no pages. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. */ #define DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM ((1ULL) << 49) From e8c9a1aed023208835ffd5ddef5d73be2f1e63e9 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Tue, 1 Dec 2026 21:22:43 -0300 Subject: [PATCH 5/9] drm/asahi: let asahi.mem_limit_pct only move the idle reclaim threshold "drm/asahi: honor explicit device limits alongside idle VM reclaim" had an explicit asahi.mem_limit_pct set two things: the held-memory threshold where idle reclaim and eviction start, and a device limit that refuses GEM objects past the same percentage. The owner's rule (11-30) is that it only sets where reclaim starts and never refuses: past the threshold the kernel reclaims idle backing and then allocates, as TTM does past its pages limit. Keep the threshold and drop the refusal: - `configured()` derives both settings: no device limit from the percentage, the threshold from it as before. Its default (0) is unchanged: half of RAM, no device limit. - **What still refuses:** asahi.client_mem_limit_pct (opt-in per client), the gpu_mem_limit_pct sysfs file (sets device and client limits), and the caller's memory cgroup. - **Bit 49's header comment** says so plainly, in place of "An explicit allocation limit still applies." The other parts of that commit stay: evict_idle's try_lock, and bit 49 on G17. Tests: - **KUnit:** an explicit percentage moves the threshold, sets no limit, and a population past it asks for eviction and is refused nothing. The per-client limit stays the one that refuses. - **Host test** (asahi-held-ceiling-tests.py) now requires the percentage to reach only the threshold; the mem-pct-refuses fault is caught. Signed-off-by: Jonathan Goyvaerts --- drivers/gpu/drm/asahi/asahi_core.rs | 2 +- drivers/gpu/drm/asahi/memacct.rs | 45 +++++++++++++++++++++---- include/uapi/drm/asahi_drm.h | 7 ++-- tools/asahi/asahi-held-ceiling-tests.py | 22 +++++++----- tools/asahi/run-host-tests.py | 3 +- 5 files changed, 60 insertions(+), 19 deletions(-) diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index b46fd26ed06e3..8227d2cd7a34d 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -247,7 +247,7 @@ module! { }, mem_limit_pct: u32 { default: 0, - description: "Device GPU memory limit in percent of RAM (0 or >= 100: unlimited); idle reclaim above this percentage (0: half RAM, >= 100: disabled)", + description: "GPU-held memory in percent of RAM past which idle GPU backing is reclaimed first; never refuses (0: half of RAM, >= 100: never)", }, client_mem_limit_pct: u32 { default: 0, diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index 04f92aec2f012..542284ea51839 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -190,15 +190,15 @@ impl Ledger { /// Sets the limits and the ceiling on held memory from the module parameters and the amount /// of RAM. pub(crate) fn configure(&self) { - let total = total_ram_bytes(); - let device_pct = module_parameters::mem_limit_pct.value(); - let limits = limits_for(total, device_pct, module_parameters::client_mem_limit_pct.value()); + let (limits, held) = configured( + total_ram_bytes(), + module_parameters::mem_limit_pct.value(), + module_parameters::client_mem_limit_pct.value(), + ); self.set_limits(limits); - let held = held_ceiling(total, device_pct); self.held_limit.store(held, Ordering::Relaxed); pr_info!( - "GPU memory: device limit {} MiB, per-client limit {} MiB, idle reclaim above {} MiB held (0 = disabled)\n", - limits.device >> 20, + "GPU memory: per-client limit {} MiB (0 = none), idle reclaim above {} MiB held (0 = disabled)\n", limits.client >> 20, held >> 20 ); @@ -417,6 +417,15 @@ pub(crate) fn held_ceiling(total_ram: u64, pct: u32) -> u64 { } } +/// The limits and the held-memory threshold the module parameters set for `total_ram` bytes of +/// RAM. `asahi.mem_limit_pct` (`mem_pct`) sets only where idle reclaim and eviction start: it +/// never refuses an allocation. `asahi.client_mem_limit_pct` (`client_pct`) is the opt-in +/// per-client limit, which does. A device limit that refuses comes only from the +/// `gpu_mem_limit_pct` sysfs file. +fn configured(total_ram: u64, mem_pct: u32, client_pct: u32) -> (Limits, u64) { + (limits_for(total_ram, 0, client_pct), held_ceiling(total_ram, mem_pct)) +} + /// Bytes of a user object reserved against the limits. pub(crate) struct Commit { ledger: &'static Ledger, @@ -685,6 +694,30 @@ mod tests { Ok(()) } + #[test] + fn mem_limit_pct_moves_the_threshold_and_never_refuses() { + // An explicit percentage moves where reclaim starts and sets no refusing limit. + let (limits, held) = configured(48 * GIB, 25, 0); + assert_eq!(held, 12 * GIB); + assert_eq!(limits, Limits { device: 0, client: 0 }); + // Admission past the threshold is never refused for it. + CONFIGURED.set_limits(limits); + CONFIGURED.held_limit.store(held, Ordering::Relaxed); + let a = Client::new().unwrap(); + let big = CONFIGURED.admit(&a, 16 * GIB).unwrap(); + let mut asked = 0; + CONFIGURED.populate(16 * GIB, |over| asked = over, || Ok(())).unwrap(); + assert_eq!(asked, 4 * GIB); + assert_eq!(CONFIGURED.refused.load(Ordering::Relaxed), 0); + drop(big); + // The per-client limit stays the one that refuses, and is opt-in. + let (limits, held) = configured(48 * GIB, 0, 50); + assert_eq!(limits, Limits { device: 0, client: 24 * GIB }); + assert_eq!(held, 24 * GIB); + } + + static CONFIGURED: Ledger = Ledger::new(); + #[test] fn the_held_ceiling_is_half_of_ram_by_default() { for gib in [8u64, 16, 24, 48, 64] { diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index 3e14315177b8d..ffa8cfa85ac2e 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -628,9 +628,10 @@ enum drm_asahi_feature { /* * DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM: before populating new user backing past * the device's held-memory threshold, the kernel attempts to reclaim idle GPU - * VM backing. An explicit allocation limit still applies. Reclaim is best - * effort and may release no pages. A feature bit like those of enum - * drm_asahi_feature, defined here like bit 32. + * VM backing. The threshold itself never refuses an allocation; a per-client + * or device allocation limit set by the administrator, or the caller's memory + * cgroup, still can. Reclaim is best effort and may release no pages. A + * feature bit like those of enum drm_asahi_feature, defined here like bit 32. */ #define DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM ((1ULL) << 49) diff --git a/tools/asahi/asahi-held-ceiling-tests.py b/tools/asahi/asahi-held-ceiling-tests.py index 8f669484d0f08..543b8f021e09c 100644 --- a/tools/asahi/asahi-held-ceiling-tests.py +++ b/tools/asahi/asahi-held-ceiling-tests.py @@ -11,10 +11,12 @@ leaves it before its shrinkers are freed (mmu/residency.rs); evict_idle dereferences listed owners, so leaving it late would be a use after free; - Ledger::populate fails only with populate's own error: the ceiling starts - eviction and refuses nothing (memacct.rs). + eviction and refuses nothing (memacct.rs); +- asahi.mem_limit_pct sets only the threshold, never a refusing device limit + (memacct.rs, configured). ---mutation skip-populate / no-unregister / late-unregister / refuse inject -each fault and must be caught. +--mutation skip-populate / no-unregister / late-unregister / refuse / +mem-pct-refuses inject each fault and must be caught. """ import argparse import sys @@ -47,6 +49,9 @@ def sources(mutation): r = r.replace(' unsafe { kernel::bindings::shrinker_free(raw) };\n }\n }\n', ' unsafe { kernel::bindings::shrinker_free(raw) };\n }\n }\n' + line, 1) files['mmu/residency.rs'] = r + elif mutation == 'mem-pct-refuses': + files['memacct.rs'] = files['memacct.rs'].replace( + 'limits_for(total_ram, 0, client_pct)', 'limits_for(total_ram, mem_pct, client_pct)', 1) elif mutation == 'refuse': files['memacct.rs'] = files['memacct.rs'].replace( 'evict(held - limit);', 'evict(held - limit);\n return Err(ENOMEM);', 1) @@ -68,10 +73,10 @@ def check(files): leave = drop.find('IDLE_VMS.lock().retain(|owner| *owner != this);') if leave < 0 or leave > drop.find('shrinker_free'): failures.append('FAIL line 3: a shrinker owner leaves the eviction list late or never') - config = item(files['memacct.rs'], 'pub(crate) fn configure(') - if ('let device_pct = module_parameters::mem_limit_pct.value();' not in config - or 'limits_for(total, device_pct,' not in config): - failures.append('FAIL: configured device cap is lost before admission') + configured = item(files['memacct.rs'], 'fn configured(') + if ('limits_for(total_ram, 0, client_pct)' not in configured + or 'held_ceiling(total_ram, mem_pct)' not in configured): + failures.append('FAIL line 5: asahi.mem_limit_pct refuses instead of only moving the threshold') if 'IDLE_VMS.try_lock()' not in item(res, 'pub(crate) fn evict_idle('): failures.append('FAIL: bind waits behind another reclaim walk') populate = item(files['memacct.rs'], 'pub(crate) fn populate(') @@ -83,7 +88,8 @@ def check(files): def main(): parser = argparse.ArgumentParser() - parser.add_argument('--mutation', choices=['skip-populate', 'no-unregister', 'late-unregister', 'refuse']) + parser.add_argument('--mutation', choices=['skip-populate', 'no-unregister', 'late-unregister', 'refuse', + 'mem-pct-refuses']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 6f61a5ec597cf..f18d09d89665d 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -448,7 +448,8 @@ def mutations(flag, names, base, expect=KILL): 'asahi-idle-vm-reclaim-feature-tests.py': [([], PASS)] + mutations( '--mutation', ['drop-g17', 'drop-m5', 'report-g16'], []), 'asahi-held-ceiling-tests.py': [([], PASS)] + mutations( - '--mutation', ['skip-populate', 'no-unregister', 'late-unregister', 'refuse'], []), + '--mutation', ['skip-populate', 'no-unregister', 'late-unregister', 'refuse', + 'mem-pct-refuses'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)], From c6468ddcb987f8f9c5616e46235064b6840dd9f4 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Wed, 2 Dec 2026 22:34:21 -0500 Subject: [PATCH 6/9] drm/asahi: count only the unheld part of an object against the ceiling CPU faults in a revocable mapping hold single pages of an object, which are counted as held already. A bind that populates the rest counted the whole object again, and asked idle backing for more than the bind adds. Have Charge::adds_held() return the bytes that are not held yet, and pass those to Ledger::populate(). Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/gem.rs | 5 +++-- drivers/gpu/drm/asahi/memacct.rs | 29 ++++++++++++++++--------- tools/asahi/asahi-held-ceiling-tests.py | 6 ++--- 3 files changed, 25 insertions(+), 15 deletions(-) diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index 0795553ac8221..a943334423ab3 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -154,11 +154,12 @@ pub(crate) fn held_user_sg_table<'a>( { return Err(EACCES); } - if !gem.charge.adds_held() { + let adds = gem.charge.adds_held(); + if adds == 0 { return mapped_sg_table(gem, dev); } // Populating the pages for the GPU first evicts idle backing past the ceiling on held memory. - memacct::LEDGER.populate(gem.size() as u64, mmu::evict_idle, || mapped_sg_table(gem, dev)) + memacct::LEDGER.populate(adds, mmu::evict_idle, || mapped_sg_table(gem, dev)) } /// Takes the SG table of `gem` for a device mapping that [`held_sg_table`] or diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index 494dad51ca811..dbca5e5e5f8fd 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -512,10 +512,14 @@ impl Charge { Self::user(commit, mm) } - /// Whether populating the object for the GPU adds held memory: a user object whose pages are - /// not all held yet. Imports and user-memory objects never add any. - pub(crate) fn adds_held(&self) -> bool { - matches!(self.kind, Kind::User { .. }) && self.held.load(Ordering::Acquire) < self.bytes + /// The bytes that populating the object for the GPU adds to held memory: those of a user + /// object that are not held yet (CPU faults may have populated some of its pages before). + /// Imports and user-memory objects never add any. + pub(crate) fn adds_held(&self) -> u64 { + match self.kind { + Kind::User { .. } => self.bytes.saturating_sub(self.held.load(Ordering::Acquire)), + _ => 0, + } } /// Counts `bytes` more as held (`held`) or as no longer held. @@ -773,17 +777,22 @@ mod tests { } #[test] - fn only_unheld_user_objects_add_held_memory() -> Result { + fn only_the_unheld_part_of_user_objects_adds_held_memory() -> Result { let a = Client::new()?; - let user = Charge::user(CEILING.admit(&a, MIB)?, None); - assert!(user.adds_held()); + let user = Charge::user(UNHELD.admit(&a, MIB)?, None); + assert_eq!(user.adds_held(), MIB); + // Pages that CPU faults populated are held already. + user.set_held_bytes(MIB / 4); + assert_eq!(user.adds_held(), MIB * 3 / 4); user.set_held(true); - assert!(!user.adds_held()); - assert!(!Charge::none().adds_held()); - assert!(!Charge::kernel(&CEILING, MIB).adds_held()); + assert_eq!(user.adds_held(), 0); + assert_eq!(Charge::none().adds_held(), 0); + assert_eq!(Charge::kernel(&UNHELD, MIB).adds_held(), 0); Ok(()) } + static UNHELD: Ledger = Ledger::new(); + static KERNEL: Ledger = Ledger::new(); #[test] diff --git a/tools/asahi/asahi-held-ceiling-tests.py b/tools/asahi/asahi-held-ceiling-tests.py index 543b8f021e09c..22b4c5e23b2dd 100644 --- a/tools/asahi/asahi-held-ceiling-tests.py +++ b/tools/asahi/asahi-held-ceiling-tests.py @@ -38,7 +38,7 @@ def item(source, signature): def sources(mutation): files = {n: (ASAHI / n).read_text() for n in ('gem.rs', 'mmu/residency.rs', 'memacct.rs')} if mutation == 'skip-populate': - files['gem.rs'] = files['gem.rs'].replace('if !gem.charge.adds_held() {', 'if true {', 1) + files['gem.rs'] = files['gem.rs'].replace('if adds == 0 {', 'if true {', 1) elif mutation == 'no-unregister': files['mmu/residency.rs'] = files['mmu/residency.rs'].replace( 'IDLE_VMS.lock().retain(|owner| *owner != this);', '', 1) @@ -61,8 +61,8 @@ def sources(mutation): def check(files): failures = [] bind = item(files['gem.rs'], 'pub(crate) fn held_user_sg_table') - guard = bind.find('if !gem.charge.adds_held()') - via = bind.find('memacct::LEDGER.populate(gem.size() as u64, mmu::evict_idle,') + guard = bind.find('let adds = gem.charge.adds_held();\n if adds == 0 {') + via = bind.find('memacct::LEDGER.populate(adds, mmu::evict_idle,') if guard < 0 or via < 0 or 'return mapped_sg_table' not in bind[guard:via]: failures.append('FAIL line 1: a user bind does not populate through Ledger::populate') res = files['mmu/residency.rs'] From 5ce50e0ea12f46cc183098d24ba2da5152f0b2e2 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Wed, 2 Dec 2026 22:34:22 -0500 Subject: [PATCH 7/9] drm/asahi: keep default limits on memory idle reclaim never releases The held-memory ceiling replaces the default limits (67% of RAM for the device, 50% per client) with eviction. Eviction only releases objects private to a user VM that has idle reclaim. Without the limits, nothing bounds the rest: - On G13 to G16, G18 and M3, user VMs have no idle reclaim. The ceiling evicts nothing there, and one client could take all memory. - GEM_USERPTR pins are not charged to RLIMIT_MEMLOCK on the grounds that the GPU memory limits bound them. - Page tables, GPUVA records, bound objects, heap blocks and queue objects grow with a client's requests and are charged to no process, so the OOM killer does not find their owner. Keep the old default shares for what idle reclaim never releases, counted separately from the objects it does release. GEM_CREATE already knows whether the object's VM has idle reclaim: such an object is subject only to the opt-in limits, as before. asahi.mem_limit_pct still refuses nothing, and a G17 or M5 game's own buffers have no default limit. asahi.client_mem_limit_pct, if set, replaces the default per client. GET_PARAMS reports the limits on a client's objects: none where idle reclaim is reported, the default shares elsewhere, as without the ceiling. gpu_mem_limit_pct sets every limit, so 0 still disables all. gpu_memory shows the new totals. Signed-off-by: DjDeveloperr --- .../sysfs-driver-asahi-agx-gpu-mem-limit | 4 +- drivers/gpu/drm/asahi/asahi_core.rs | 2 +- drivers/gpu/drm/asahi/file.rs | 28 +- drivers/gpu/drm/asahi/memacct.rs | 290 +++++++++++++++--- drivers/gpu/drm/asahi/sysfs.c | 15 +- include/uapi/drm/asahi_drm.h | 13 +- 6 files changed, 293 insertions(+), 59 deletions(-) diff --git a/Documentation/ABI/testing/sysfs-driver-asahi-agx-gpu-mem-limit b/Documentation/ABI/testing/sysfs-driver-asahi-agx-gpu-mem-limit index 6ec563ebab50a..15a9ec145ba05 100644 --- a/Documentation/ABI/testing/sysfs-driver-asahi-agx-gpu-mem-limit +++ b/Documentation/ABI/testing/sysfs-driver-asahi-agx-gpu-mem-limit @@ -11,4 +11,6 @@ Description: GET_PARAMS calls do not change; clients must query again. A read returns the current per-client limit as a percentage - of RAM. Zero means no limit. Only the owner can write. + of RAM: the one on all objects if it is set, otherwise the + one on memory that idle reclaim never releases. Zero means no + limit. Only the owner can write. diff --git a/drivers/gpu/drm/asahi/asahi_core.rs b/drivers/gpu/drm/asahi/asahi_core.rs index 8227d2cd7a34d..e92d0b02da0da 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -251,7 +251,7 @@ module! { }, client_mem_limit_pct: u32 { default: 0, - description: "Per-client GPU memory limit in percent of RAM (0: none)", + description: "Per-client GPU memory limit in % of RAM (0: 50, unreclaimable only)", }, oom_attribution: u8 { default: 1, diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index 0e10eb3d42039..b95bffbcd18a1 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -638,11 +638,8 @@ impl File { return Err(ENODEV); } - let memory_limits = memacct::LEDGER.limits(); let mut params = uapi::drm_asahi_params_global { features: 0, - memory_limit: memory_limits.device, - client_memory_limit: memory_limits.client, vm_start: file.inner().user_range.start, vm_end: file.inner().user_range.end, @@ -658,6 +655,10 @@ impl File { gpu.get_params(&mut params)?; + let memory_limits = memacct::LEDGER + .exported_limits(params.features & uapi::DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM as u64 != 0); + params.memory_limit = memory_limits.device; + params.client_memory_limit = memory_limits.client; params.features |= gpu.feature_flags(); // Every backend admits the USC cache invalidate in the VDM root barrier. params.features |= uapi::DRM_ASAHI_FEATURE_VDM_USC_INVALIDATE as u64; @@ -948,15 +949,18 @@ impl File { }; let size = gem::checked_object_size(data.size.try_into()?)?; - let commit = memacct::LEDGER - .admit(&file.inner().mem, size as u64) - .inspect_err(|_| { - cls_pr_debug!( - Errors, - "gem_create: {:#x} bytes refused by the GPU memory limits\n", - size - ); - })?; + let admitted = if reclaim_cpu { + memacct::LEDGER.admit_reclaimable(&file.inner().mem, size as u64) + } else { + memacct::LEDGER.admit(&file.inner().mem, size as u64) + }; + let commit = admitted.inspect_err(|_| { + cls_pr_debug!( + Errors, + "gem_create: {:#x} bytes refused by the GPU memory limits\n", + size + ); + })?; // Large G17 user objects are populated in full by the first VM_BIND. // Let them release clean page cache, but do not swap out the rest of // the system for them folio by folio. Userspace can evict its BO diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index dbca5e5e5f8fd..e921f16d8f113 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -36,6 +36,12 @@ //! - Opt-in limits (none by default) admit a new user object only while its client, //! and the device, stay within a fraction of RAM. A refused allocation fails with //! `ENOMEM`, which userspace reports as out-of-device-memory. +//! - What idle reclaim never releases stays within fixed fractions of RAM, per client +//! and for the device: pinned user memory, shareable objects, the kernel memory that +//! grows with a client's requests and, where user VMs have no idle reclaim, every +//! user object ([`Ledger::admit`], [`Ledger::admit_reclaimable`]). Most of it is +//! charged to no process, so the OOM killer could not find its owner, and user +//! 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) @@ -81,6 +87,12 @@ pub(crate) struct Ledger { /// Held bytes, user and kernel resident together, past which idle backing is evicted /// before more is populated (0: none). pub(crate) held_limit: AtomicU64, + /// Committed user bytes that idle reclaim never releases. + pub(crate) user_unreclaimable: AtomicU64, + /// Device-wide limit on those plus kernel resident bytes (0: none). + pub(crate) unreclaimable_limit: AtomicU64, + /// Per-client limit on those (0: none). + pub(crate) client_unreclaimable_limit: AtomicU64, } // Keep the Rust half of the C sysfs layout contract checked as well. @@ -89,12 +101,18 @@ const _: () = { assert!(core::mem::offset_of!(Ledger, client_limit) == 40); assert!(core::mem::offset_of!(Ledger, user_kept) == 48); assert!(core::mem::offset_of!(Ledger, held_limit) == 56); - assert!(core::mem::size_of::() == 64); + assert!(core::mem::offset_of!(Ledger, client_unreclaimable_limit) == 80); + assert!(core::mem::size_of::() == 88); }; /// The ledger of the (single) AGX GPU. pub(crate) static LEDGER: Ledger = Ledger::new(); +/// The shares of RAM, in percent, that memory idle reclaim never releases may take by default: +/// in all, and per client. +const UNRECLAIMABLE_PCT: u32 = 67; +const CLIENT_UNRECLAIMABLE_PCT: u32 = 50; + /// The limits that follow from the amount of RAM and two percentages. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub(crate) struct Limits { @@ -121,11 +139,13 @@ pub(crate) fn total_ram_bytes() -> u64 { (info.totalram as u64).saturating_mul(u64::from(info.mem_unit)) } -/// Sets both limits from the percentage written through sysfs. +/// Sets every limit, on all objects and on what idle reclaim never releases, from the percentage +/// written through sysfs. #[no_mangle] pub extern "C" fn asahi_set_mem_limit_pct(pct: u32) { let limits = limits_for(total_ram_bytes(), pct, pct); LEDGER.set_limits(limits); + LEDGER.set_unreclaimable_limits(limits); pr_info!( "GPU memory limits set: device {} MiB, per client {} MiB (0 = none)\n", limits.device >> 20, @@ -165,6 +185,25 @@ fn try_add_within(counter: &AtomicU64, bytes: u64, limit: u64, extra: u64) -> bo } } +/// Adds `bytes` to a client's and the device's counter if both stay within `limits`, the +/// device's together with `extra`; otherwise adds nothing. Returns whether the bytes were added. +fn try_add_both( + client: &AtomicU64, + device: &AtomicU64, + bytes: u64, + limits: Limits, + extra: u64, +) -> bool { + if !try_add_within(client, bytes, limits.client, 0) { + return false; + } + if !try_add_within(device, bytes, limits.device, extra) { + sub(client, bytes); + return false; + } + true +} + fn sub(counter: &AtomicU64, bytes: u64) { let prev = counter.fetch_sub(bytes, Ordering::AcqRel); if prev < bytes { @@ -184,22 +223,31 @@ impl Ledger { client_limit: AtomicU64::new(0), user_kept: AtomicU64::new(0), held_limit: AtomicU64::new(0), + user_unreclaimable: AtomicU64::new(0), + unreclaimable_limit: AtomicU64::new(0), + client_unreclaimable_limit: AtomicU64::new(0), } } /// Sets the limits and the ceiling on held memory from the module parameters and the amount /// of RAM. pub(crate) fn configure(&self) { + let ram = total_ram_bytes(); + let client_pct = module_parameters::client_mem_limit_pct.value(); let (limits, held) = configured( - total_ram_bytes(), + ram, module_parameters::mem_limit_pct.value(), - module_parameters::client_mem_limit_pct.value(), + client_pct, ); + let unreclaimable = unreclaimable_limits_for(ram, client_pct); self.set_limits(limits); + self.set_unreclaimable_limits(unreclaimable); self.held_limit.store(held, Ordering::Relaxed); pr_info!( - "GPU memory: per-client limit {} MiB (0 = none), idle reclaim above {} MiB held (0 = disabled)\n", + "GPU memory: per-client limit {} MiB (0 = none), unreclaimable limits device {} MiB, per client {} MiB, idle reclaim above {} MiB held (0 = disabled)\n", limits.client >> 20, + unreclaimable.device >> 20, + unreclaimable.client >> 20, held >> 20 ); } @@ -227,8 +275,24 @@ impl Ledger { populate() } - /// Admission capacities exported in the optional GET_PARAMS tail. - pub(crate) fn limits(&self) -> Limits { + /// Admission capacities exported in the optional GET_PARAMS tail: the limits on an object + /// created for a VM that has idle reclaim (`reclaimable`), and otherwise on every object. + pub(crate) fn exported_limits(&self, reclaimable: bool) -> Limits { + let limits = self.limits(); + if reclaimable { + return limits; + } + let unreclaimable = self.unreclaimable_limits(); + // 0 is no limit: the smaller of those there are. + let tighter = |a: u64, b: u64| if a == 0 || b == 0 { a.max(b) } else { a.min(b) }; + Limits { + device: tighter(limits.device, unreclaimable.device), + client: tighter(limits.client, unreclaimable.client), + } + } + + /// The limits on everything admitted. + fn limits(&self) -> Limits { Limits { device: self.limit.load(Ordering::Relaxed), client: self.client_limit.load(Ordering::Relaxed), @@ -240,40 +304,85 @@ impl Ledger { self.client_limit.store(limits.client, Ordering::Relaxed); } - /// Admits a new user object of `bytes` for `client`. + /// The limits on what idle reclaim never releases. + fn unreclaimable_limits(&self) -> Limits { + Limits { + device: self.unreclaimable_limit.load(Ordering::Relaxed), + client: self.client_unreclaimable_limit.load(Ordering::Relaxed), + } + } + + pub(crate) fn set_unreclaimable_limits(&self, limits: Limits) { + self.unreclaimable_limit.store(limits.device, Ordering::Relaxed); + self.client_unreclaimable_limit + .store(limits.client, Ordering::Relaxed); + } + + /// Admits `bytes` for `client` that idle reclaim never releases. /// - /// Reserves the bytes against both limits; the returned [`Commit`] gives + /// Reserves the bytes against the limits; the returned [`Commit`] gives /// them back when it is dropped. pub(crate) fn admit(&'static self, client: &Arc, bytes: u64) -> Result { - self.reserve(client, bytes)?; + self.commit(client, bytes, false) + } + + /// Admits a new user object of `bytes` for `client`, as [`Self::admit`], whose backing idle + /// reclaim of its VM releases: only the opt-in limits apply to it. + pub(crate) fn admit_reclaimable( + &'static self, + client: &Arc, + bytes: u64, + ) -> Result { + self.commit(client, bytes, true) + } + + fn commit( + &'static self, + client: &Arc, + bytes: u64, + reclaimable: bool, + ) -> Result { + self.reserve(client, bytes, reclaimable)?; Ok(Commit { ledger: self, client: client.clone(), bytes, + reclaimable, }) } - /// 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 { - let client_limit = self.client_limit.load(Ordering::Relaxed); - if !try_add_within(&client.committed, bytes, client_limit, 0) { - self.refused.fetch_add(1, Ordering::Relaxed); - return Err(ENOMEM); - } - // Kernel objects share the device limit but are never refused. + /// 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. + fn reserve(&self, client: &Client, bytes: u64, reclaimable: bool) -> Result { + // Kernel objects share the device limits but are never refused. let kernel = self.kernel_resident.load(Ordering::Relaxed); - if !try_add_within( - &self.user_committed, - bytes, - self.limit.load(Ordering::Relaxed), - kernel, - ) { - sub(&client.committed, bytes); - self.refused.fetch_add(1, Ordering::Relaxed); - return Err(ENOMEM); + if try_add_both(&client.committed, &self.user_committed, bytes, self.limits(), kernel) { + if reclaimable + || try_add_both( + &client.unreclaimable, + &self.user_unreclaimable, + bytes, + self.unreclaimable_limits(), + kernel, + ) + { + return Ok(()); + } + self.release(client, bytes, true); + } + self.refused.fetch_add(1, Ordering::Relaxed); + Err(ENOMEM) + } + + /// Takes back what [`Self::reserve`] added. + fn release(&self, client: &Client, bytes: u64, reclaimable: bool) { + sub(&client.committed, bytes); + sub(&self.user_committed, bytes); + if !reclaimable { + sub(&client.unreclaimable, bytes); + sub(&self.user_unreclaimable, bytes); } - Ok(()) } } @@ -299,15 +408,21 @@ impl Usage { /// user object of that size would be admitted; otherwise fails with `ENOMEM` and charges /// nothing. pub(crate) fn try_add(&mut self, bytes: u64) -> Result { - self.ledger.reserve(&self.client, bytes)?; + self.ledger.reserve(&self.client, bytes, false)?; self.hold(bytes); Ok(()) } /// Charges `bytes` more whatever the limits, for memory that already exists. pub(crate) fn add(&mut self, bytes: u64) { - self.client.committed.fetch_add(bytes, Ordering::AcqRel); - self.ledger.user_committed.fetch_add(bytes, Ordering::AcqRel); + for counter in [ + &self.client.committed, + &self.ledger.user_committed, + &self.client.unreclaimable, + &self.ledger.user_unreclaimable, + ] { + counter.fetch_add(bytes, Ordering::AcqRel); + } self.hold(bytes); } @@ -339,8 +454,7 @@ impl Drop for Usage { fn drop(&mut self) { sub(&self.client.resident, self.bytes); sub(&self.ledger.user_resident, self.bytes); - sub(&self.client.committed, self.bytes); - sub(&self.ledger.user_committed, self.bytes); + self.ledger.release(&self.client, self.bytes, false); } } @@ -348,6 +462,8 @@ impl Drop for Usage { pub(crate) struct Client { /// Size of the live user objects this client created. committed: AtomicU64, + /// The part of `committed` that idle reclaim never releases. + unreclaimable: AtomicU64, /// Size of those whose backing the GPU currently holds. resident: AtomicU64, /// Bytes of the device's firmware timestamp window this client's bound buffers hold. @@ -359,6 +475,7 @@ impl Client { Ok(Arc::new( Self { committed: AtomicU64::new(0), + unreclaimable: AtomicU64::new(0), resident: AtomicU64::new(0), timestamp_window: AtomicU64::new(0), }, @@ -420,23 +537,35 @@ pub(crate) fn held_ceiling(total_ram: u64, pct: u32) -> u64 { /// The limits and the held-memory threshold the module parameters set for `total_ram` bytes of /// RAM. `asahi.mem_limit_pct` (`mem_pct`) sets only where idle reclaim and eviction start: it /// never refuses an allocation. `asahi.client_mem_limit_pct` (`client_pct`) is the opt-in -/// per-client limit, which does. A device limit that refuses comes only from the +/// per-client limit, which does. A device limit on every object comes only from the /// `gpu_mem_limit_pct` sysfs file. fn configured(total_ram: u64, mem_pct: u32, client_pct: u32) -> (Limits, u64) { (limits_for(total_ram, 0, client_pct), held_ceiling(total_ram, mem_pct)) } +/// The limits on what idle reclaim never releases, for `total_ram` bytes of RAM: +/// `asahi.client_mem_limit_pct` (`client_pct`), if set, replaces the default per client. +fn unreclaimable_limits_for(total_ram: u64, client_pct: u32) -> Limits { + let client_pct = match client_pct { + 0 => CLIENT_UNRECLAIMABLE_PCT, + pct => pct, + }; + limits_for(total_ram, UNRECLAIMABLE_PCT, client_pct) +} + /// Bytes of a user object reserved against the limits. pub(crate) struct Commit { ledger: &'static Ledger, client: Arc, bytes: u64, + /// Whether idle reclaim releases the object's backing. + reclaimable: bool, } impl Drop for Commit { fn drop(&mut self) { - sub(&self.client.committed, self.bytes); - sub(&self.ledger.user_committed, self.bytes); + self.ledger + .release(&self.client, self.bytes, self.reclaimable); } } @@ -553,7 +682,7 @@ impl Charge { } /// Moves a user object's charge to `to`, the client now using it: its committed bytes, - /// within `to`'s limit, and its held bytes. The device totals and the process attribution + /// within `to`'s limits, and its held bytes. The device totals and the process attribution /// stay as they are. A refusal fails with `ENOMEM` and leaves the charge where it was. /// Other kinds are attributed to no client and are left alone. pub(crate) fn transfer(&mut self, to: &Arc) -> Result { @@ -566,7 +695,17 @@ impl Charge { return Ok(()); } let ledger = commit.ledger; - if !try_add_within(&to.committed, bytes, ledger.client_limit.load(Ordering::Relaxed), 0) { + let reclaimable = commit.reclaimable; + let unreclaimable_limit = ledger.unreclaimable_limits().client; + let mut moved = try_add_within(&to.committed, bytes, ledger.limits().client, 0); + if moved + && !reclaimable + && !try_add_within(&to.unreclaimable, bytes, unreclaimable_limit, 0) + { + sub(&to.committed, bytes); + moved = false; + } + if !moved { ledger.refused.fetch_add(1, Ordering::Relaxed); return Err(ENOMEM); } @@ -575,6 +714,9 @@ impl Charge { sub(&commit.client.resident, held); } sub(&commit.client.committed, bytes); + if !reclaimable { + sub(&commit.client.unreclaimable, bytes); + } commit.client = to.clone(); Ok(()) } @@ -707,6 +849,76 @@ mod tests { Ok(()) } + static UNRECLAIMABLE: Ledger = Ledger::new(); + + #[test] + fn unreclaimable_memory_is_bounded_by_default() -> Result { + let default = unreclaimable_limits_for(8 * GIB, 0); + assert_eq!(default, Limits { device: 8 * GIB * 67 / 100, client: 4 * GIB }); + // The per-client parameter moves it, within the device's share. + assert_eq!(unreclaimable_limits_for(8 * GIB, 25).client, 2 * GIB); + assert_eq!(unreclaimable_limits_for(8 * GIB, 100).client, default.device); + // As configured by default: no limit on what idle reclaim releases. + let (limits, _) = configured(8 * GIB, 0, 0); + UNRECLAIMABLE.set_limits(limits); + UNRECLAIMABLE.set_unreclaimable_limits(default); + let a = Client::new()?; + let idle = UNRECLAIMABLE.admit_reclaimable(&a, 7 * GIB)?; + let more = UNRECLAIMABLE.admit_reclaimable(&a, GIB)?; + assert_eq!(UNRECLAIMABLE.refused.load(Ordering::Relaxed), 0); + // The rest of a client's memory has its own share, which those did not use up. + let pinned = UNRECLAIMABLE.admit(&a, 4 * GIB)?; + assert_eq!(UNRECLAIMABLE.admit(&a, 4096).err(), Some(ENOMEM)); + let mut usage = Usage::new(&UNRECLAIMABLE, a.clone()); + assert_eq!(usage.try_add(4096), Err(ENOMEM)); + assert_eq!(a.committed(), 12 * GIB); + // Other clients stay within the device's share, together with kernel objects. + let b = Client::new()?; + let kernel = Charge::kernel(&UNRECLAIMABLE, GIB); + kernel.set_held(true); + assert_eq!(UNRECLAIMABLE.admit(&b, GIB).err(), Some(ENOMEM)); + assert_eq!(b.committed(), 0); + drop(kernel); + let shared = UNRECLAIMABLE.admit(&b, GIB)?; + // A charge moves to another client within that client's share only. + let mut moving = Charge::user(pinned, None); + assert_eq!(moving.transfer(&b), Err(ENOMEM)); + drop(shared); + moving.transfer(&b)?; + let again = UNRECLAIMABLE.admit(&a, MIB)?; + assert_eq!(UNRECLAIMABLE.admit(&b, MIB).err(), Some(ENOMEM)); + drop((idle, more, moving, again, usage)); + for counter in [ + &a.committed, + &a.unreclaimable, + &b.committed, + &b.unreclaimable, + &UNRECLAIMABLE.user_committed, + &UNRECLAIMABLE.user_unreclaimable, + ] { + assert_eq!(counter.load(Ordering::Relaxed), 0); + } + Ok(()) + } + + #[test] + fn exported_limits_follow_idle_reclaim() { + static EXPORTED: Ledger = Ledger::new(); + let none = Limits { device: 0, client: 0 }; + let default = unreclaimable_limits_for(8 * GIB, 0); + EXPORTED.set_unreclaimable_limits(default); + assert_eq!(EXPORTED.exported_limits(true), none); + assert_eq!(EXPORTED.exported_limits(false), default); + // Opt-in limits apply to both; the smaller limit is the one that refuses. + EXPORTED.set_limits(Limits { device: 0, client: 2 * GIB }); + assert_eq!(EXPORTED.exported_limits(true).client, 2 * GIB); + assert_eq!(EXPORTED.exported_limits(false).client, 2 * GIB); + EXPORTED.set_limits(Limits { device: 7 * GIB, client: 7 * GIB }); + assert_eq!(EXPORTED.exported_limits(false), default); + EXPORTED.set_unreclaimable_limits(none); + assert_eq!(EXPORTED.exported_limits(false).device, 7 * GIB); + } + #[test] fn mem_limit_pct_moves_the_threshold_and_never_refuses() { // An explicit percentage moves where reclaim starts and sets no refusing limit. diff --git a/drivers/gpu/drm/asahi/sysfs.c b/drivers/gpu/drm/asahi/sysfs.c index 844a36ae18411..f4c8b73221f11 100644 --- a/drivers/gpu/drm/asahi/sysfs.c +++ b/drivers/gpu/drm/asahi/sysfs.c @@ -47,6 +47,9 @@ struct asahi_gpu_memory { u64 client_limit; u64 user_kept; u64 held_limit; + u64 user_unreclaimable; + u64 unreclaimable_limit; + u64 client_unreclaimable_limit; }; struct asahi_stats_attribute { @@ -246,6 +249,12 @@ static ssize_t gpu_memory_show(struct device *dev, (unsigned long long)READ_ONCE(mem->user_kept)); n += scnprintf(buf + n, PAGE_SIZE - n, "held_limit %llu\n", (unsigned long long)READ_ONCE(mem->held_limit)); + n += scnprintf(buf + n, PAGE_SIZE - n, "user_unreclaimable %llu\n", + (unsigned long long)READ_ONCE(mem->user_unreclaimable)); + n += scnprintf(buf + n, PAGE_SIZE - n, "unreclaimable_limit %llu\n", + (unsigned long long)READ_ONCE(mem->unreclaimable_limit)); + n += scnprintf(buf + n, PAGE_SIZE - n, "client_unreclaimable_limit %llu\n", + (unsigned long long)READ_ONCE(mem->client_unreclaimable_limit)); return n; } @@ -258,7 +267,8 @@ static ssize_t gpu_mem_limit_pct_show(struct device *dev, struct asahi_stats_attribute *stats = container_of(attr, struct asahi_stats_attribute, limit_attr); u64 total = (u64)totalram_pages() << PAGE_SHIFT; - u64 client = READ_ONCE(stats->memory->client_limit); + u64 client = READ_ONCE(stats->memory->client_limit) ?: + READ_ONCE(stats->memory->client_unreclaimable_limit); return sysfs_emit(buf, "%llu\n", client ? (unsigned long long)div64_u64(client * 100 + total / 2, total) : 0); @@ -302,7 +312,8 @@ int asahi_sysfs_register(struct device *dev, const void *snapshot, BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, client_limit) != 40); BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, user_kept) != 48); BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, held_limit) != 56); - BUILD_BUG_ON(sizeof(struct asahi_gpu_memory) != 64); + BUILD_BUG_ON(offsetof(struct asahi_gpu_memory, client_unreclaimable_limit) != 80); + BUILD_BUG_ON(sizeof(struct asahi_gpu_memory) != 88); BUILD_BUG_ON(offsetof(struct asahi_stats_snapshot, pstate) != 16); BUILD_BUG_ON(offsetof(struct asahi_stats_snapshot, busy_ns) != 40); diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index c6235847178ac..f784b299eebcc 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -232,7 +232,10 @@ struct drm_asahi_params_global { /** * @memory_limit: Device-wide limit on user committed plus kernel * resident bytes. Zero means no driver limit. This is a capacity, - * not current free memory; other clients share it. + * not current free memory; other clients share it. With + * DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM, this and @client_memory_limit + * are the limits on the objects that idle reclaim can release (those + * private to a VM); all other memory has limits of its own. */ __u64 memory_limit; @@ -633,9 +636,11 @@ enum drm_asahi_feature { * DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM: before populating new user backing past * the device's held-memory threshold, the kernel attempts to reclaim idle GPU * VM backing. The threshold itself never refuses an allocation; a per-client - * or device allocation limit set by the administrator, or the caller's memory - * cgroup, still can. Reclaim is best effort and may release no pages. A - * feature bit like those of enum drm_asahi_feature, defined here like bit 32. + * or device allocation limit set by the administrator, the limits on memory + * that idle reclaim never releases (such as GEM_USERPTR and shareable + * objects), or the caller's memory cgroup, still can. Reclaim is best effort + * and may release no pages. A feature bit like those of enum + * drm_asahi_feature, defined here like bit 32. */ #define DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM ((1ULL) << 49) From 3cf6a87e11381852be2c9ceba10949df1931c933 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Wed, 2 Dec 2026 22:34:22 -0500 Subject: [PATCH 8/9] drm/asahi: do not repeat a look for idle backing that came up short Past the ceiling, every bind that populates pages looked for idle backing in every user VM. A look visits every mapping of each VM and holds that VM's reservation and the UAT lock meanwhile, also for a VM in use, whose advised contents it may purge. A game past the ceiling with nothing idle left paid for that at each new buffer. A VM in use is not idle before RECLAIM_QUIET_NS after its last job. Once a look has released less than it was asked for, populate right away for that long before looking again. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/mmu/residency.rs | 27 +++++++++++++++++++++++++ tools/asahi/asahi-held-ceiling-tests.py | 20 +++++++++++++----- tools/asahi/run-host-tests.py | 4 ++-- 3 files changed, 44 insertions(+), 7 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu/residency.rs b/drivers/gpu/drm/asahi/mmu/residency.rs index 6bd6d9a6b3587..beb6e02b3c670 100644 --- a/drivers/gpu/drm/asahi/mmu/residency.rs +++ b/drivers/gpu/drm/asahi/mmu/residency.rs @@ -35,11 +35,30 @@ pub(crate) unsafe fn init() { unsafe { IDLE_VMS.init() }; } +/// When [`evict_idle`] looks for idle backing again (monotonic nanoseconds). +static NEXT_LOOK: AtomicU64 = AtomicU64::new(0); + +/// When to look again after a look at `now` that left `missing` of the pages it was asked for. +/// +/// A look visits every mapping of every user VM and holds a VM's reservation meanwhile. While +/// everything held is in use, the binds of a client past the ceiling would each repeat it for +/// nothing. A VM in use is not idle before [`RECLAIM_QUIET_NS`] after its last job, so binds that +/// follow within that time populate right away. +fn next_look(now: u64, missing: usize) -> u64 { + match missing { + 0 => 0, + _ => now.saturating_add(RECLAIM_QUIET_NS), + } +} + /// Releases up to `bytes` of the idle backing of every user VM, as the first of a VM's /// shrinkers would under memory pressure: for population past the ceiling on held memory /// (`memacct::Ledger::populate`). Objects userspace asked to keep resident stay: the ceiling /// only starts eviction, and only reclaim that nothing else relieves releases those. pub(crate) fn evict_idle(bytes: u64) { + if now_ns() < NEXT_LOOK.load(Ordering::Relaxed) { + return; + } let mut target = usize::try_from(bytes.div_ceil(kernel::page::PAGE_SIZE as u64)).unwrap_or(usize::MAX); let Some(owners) = IDLE_VMS.try_lock() else { return }; @@ -51,6 +70,7 @@ pub(crate) fn evict_idle(bytes: u64) { let owner = unsafe { &*(owner as *const VmShrinker) }; target = target.saturating_sub(owner.vm.reclaim_idle_pages(target, false)); } + NEXT_LOOK.store(next_look(now_ns(), target), Ordering::Relaxed); } /// `DRM_ASAHI_FEATURE_IDLE_VM_RECLAIM` for a backend whose user VMs have idle reclaim (a @@ -76,6 +96,13 @@ fn idle_vm_reclaim_feature_for(held_limit: u64) -> u64 { mod feature_tests { use super::*; + #[test] + fn a_look_that_came_up_short_is_not_repeated_at_once() { + assert_eq!(next_look(5, 0), 0); + assert_eq!(next_look(5, 1), 5 + RECLAIM_QUIET_NS); + assert_eq!(next_look(u64::MAX, 1), u64::MAX); + } + #[test] fn reported_only_with_a_ceiling() { assert_eq!(idle_vm_reclaim_feature_for(1 << 30), 1 << 49); diff --git a/tools/asahi/asahi-held-ceiling-tests.py b/tools/asahi/asahi-held-ceiling-tests.py index 22b4c5e23b2dd..44fb96fd49c86 100644 --- a/tools/asahi/asahi-held-ceiling-tests.py +++ b/tools/asahi/asahi-held-ceiling-tests.py @@ -10,13 +10,15 @@ - every VM shrinker owner joins the eviction list when it is registered and leaves it before its shrinkers are freed (mmu/residency.rs); evict_idle dereferences listed owners, so leaving it late would be a use after free; +- a look for idle backing that came up short is not repeated by the next bind: + a look visits every mapping of every user VM (mmu/residency.rs, evict_idle); - Ledger::populate fails only with populate's own error: the ceiling starts eviction and refuses nothing (memacct.rs); - asahi.mem_limit_pct sets only the threshold, never a refusing device limit (memacct.rs, configured). ---mutation skip-populate / no-unregister / late-unregister / refuse / -mem-pct-refuses inject each fault and must be caught. +--mutation skip-populate / no-unregister / late-unregister / every-bind-looks / +refuse / mem-pct-refuses inject each fault and must be caught. """ import argparse import sys @@ -49,6 +51,9 @@ def sources(mutation): r = r.replace(' unsafe { kernel::bindings::shrinker_free(raw) };\n }\n }\n', ' unsafe { kernel::bindings::shrinker_free(raw) };\n }\n }\n' + line, 1) files['mmu/residency.rs'] = r + elif mutation == 'every-bind-looks': + files['mmu/residency.rs'] = files['mmu/residency.rs'].replace( + 'NEXT_LOOK.store(next_look(now_ns(), target), Ordering::Relaxed);', '', 1) elif mutation == 'mem-pct-refuses': files['memacct.rs'] = files['memacct.rs'].replace( 'limits_for(total_ram, 0, client_pct)', 'limits_for(total_ram, mem_pct, client_pct)', 1) @@ -77,8 +82,13 @@ def check(files): if ('limits_for(total_ram, 0, client_pct)' not in configured or 'held_ceiling(total_ram, mem_pct)' not in configured): failures.append('FAIL line 5: asahi.mem_limit_pct refuses instead of only moving the threshold') - if 'IDLE_VMS.try_lock()' not in item(res, 'pub(crate) fn evict_idle('): + evict = item(res, 'pub(crate) fn evict_idle(') + if 'IDLE_VMS.try_lock()' not in evict: failures.append('FAIL: bind waits behind another reclaim walk') + skip = evict.find('if now_ns() < NEXT_LOOK.load(Ordering::Relaxed) {\n return;') + again = evict.find('NEXT_LOOK.store(next_look(now_ns(), target), Ordering::Relaxed);') + if not 0 <= skip < evict.find('IDLE_VMS.try_lock()') < again: + failures.append('FAIL line 6: every bind past the ceiling looks for idle backing again') populate = item(files['memacct.rs'], 'pub(crate) fn populate(') body = populate[populate.index('{'):] if 'Err(' in body or '?' in body or not body.rstrip('}').rstrip().endswith('populate()'): @@ -88,8 +98,8 @@ def check(files): def main(): parser = argparse.ArgumentParser() - parser.add_argument('--mutation', choices=['skip-populate', 'no-unregister', 'late-unregister', 'refuse', - 'mem-pct-refuses']) + parser.add_argument('--mutation', choices=['skip-populate', 'no-unregister', 'late-unregister', + 'every-bind-looks', 'refuse', 'mem-pct-refuses']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 6f4cc5b9f6dba..f31ca5fe80df4 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -556,8 +556,8 @@ def mutations(flag, names, base, expect=KILL): 'asahi-idle-vm-reclaim-feature-tests.py': [([], PASS)] + mutations( '--mutation', ['drop-g17', 'drop-m5', 'report-g16'], []), 'asahi-held-ceiling-tests.py': [([], PASS)] + mutations( - '--mutation', ['skip-populate', 'no-unregister', 'late-unregister', 'refuse', - 'mem-pct-refuses'], []), + '--mutation', ['skip-populate', 'no-unregister', 'late-unregister', 'every-bind-looks', + 'refuse', 'mem-pct-refuses'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)], From 7ae56e51538b2376b8880ccac5d2d9fd27c36837 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 3 Dec 2026 09:02:26 -0500 Subject: [PATCH 9/9] drm/asahi: check the quiet time again under the idle list lock evict_idle() checks NEXT_LOOK before it takes the list lock. A bind can pass that check and be scheduled out before try_lock(). If another bind then looks, comes up short and sets NEXT_LOOK, the first one takes the lock and walks every mapping of every user VM again at once, although nothing it could release is idle yet. NEXT_LOOK is stored with the lock held, so check it again after taking the lock. The check before the lock stays: it keeps binds within the quiet time off the lock. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/mmu/residency.rs | 5 +++++ tools/asahi/asahi-held-ceiling-tests.py | 26 ++++++++++++++++++++----- tools/asahi/run-host-tests.py | 2 +- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu/residency.rs b/drivers/gpu/drm/asahi/mmu/residency.rs index beb6e02b3c670..fd166be1edbee 100644 --- a/drivers/gpu/drm/asahi/mmu/residency.rs +++ b/drivers/gpu/drm/asahi/mmu/residency.rs @@ -62,6 +62,11 @@ pub(crate) fn evict_idle(bytes: u64) { let mut target = usize::try_from(bytes.div_ceil(kernel::page::PAGE_SIZE as u64)).unwrap_or(usize::MAX); let Some(owners) = IDLE_VMS.try_lock() else { return }; + // The check above keeps a bind within the quiet time off the lock. It can be stale by now: + // another bind may have looked, come up short and set the time under the lock meanwhile. + if now_ns() < NEXT_LOOK.load(Ordering::Relaxed) { + return; + } for &owner in owners.iter() { if target == 0 { break; diff --git a/tools/asahi/asahi-held-ceiling-tests.py b/tools/asahi/asahi-held-ceiling-tests.py index 44fb96fd49c86..bd18cade8eeb9 100644 --- a/tools/asahi/asahi-held-ceiling-tests.py +++ b/tools/asahi/asahi-held-ceiling-tests.py @@ -11,14 +11,17 @@ leaves it before its shrinkers are freed (mmu/residency.rs); evict_idle dereferences listed owners, so leaving it late would be a use after free; - a look for idle backing that came up short is not repeated by the next bind: - a look visits every mapping of every user VM (mmu/residency.rs, evict_idle); + a look visits every mapping of every user VM (mmu/residency.rs, evict_idle). + A bind checks before it takes the list lock (the cheap path), and again under + it, since another bind may have looked between its first check and the lock; - Ledger::populate fails only with populate's own error: the ceiling starts eviction and refuses nothing (memacct.rs); - asahi.mem_limit_pct sets only the threshold, never a refusing device limit (memacct.rs, configured). --mutation skip-populate / no-unregister / late-unregister / every-bind-looks / -refuse / mem-pct-refuses inject each fault and must be caught. +unlocked-look-check / refuse / mem-pct-refuses inject each fault and must be +caught. """ import argparse import sys @@ -54,6 +57,12 @@ def sources(mutation): elif mutation == 'every-bind-looks': files['mmu/residency.rs'] = files['mmu/residency.rs'].replace( 'NEXT_LOOK.store(next_look(now_ns(), target), Ordering::Relaxed);', '', 1) + elif mutation == 'unlocked-look-check': + # Only the check before the lock: a bind that passed it looks again after another's look. + r = files['mmu/residency.rs'] + look = r.index('IDLE_VMS.try_lock()') + files['mmu/residency.rs'] = r[:look] + r[look:].replace( + 'if now_ns() < NEXT_LOOK.load(Ordering::Relaxed) {\n return;\n }\n', '', 1) elif mutation == 'mem-pct-refuses': files['memacct.rs'] = files['memacct.rs'].replace( 'limits_for(total_ram, 0, client_pct)', 'limits_for(total_ram, mem_pct, client_pct)', 1) @@ -85,10 +94,16 @@ def check(files): evict = item(res, 'pub(crate) fn evict_idle(') if 'IDLE_VMS.try_lock()' not in evict: failures.append('FAIL: bind waits behind another reclaim walk') - skip = evict.find('if now_ns() < NEXT_LOOK.load(Ordering::Relaxed) {\n return;') + check = 'if now_ns() < NEXT_LOOK.load(Ordering::Relaxed) {\n return;' + skip = evict.find(check) + lock = evict.find('IDLE_VMS.try_lock()') + recheck = evict.find(check, max(lock, 0)) + look = evict.find('for &owner in owners.iter()') again = evict.find('NEXT_LOOK.store(next_look(now_ns(), target), Ordering::Relaxed);') - if not 0 <= skip < evict.find('IDLE_VMS.try_lock()') < again: + if not 0 <= skip < lock < again: failures.append('FAIL line 6: every bind past the ceiling looks for idle backing again') + if not 0 <= lock < recheck < look: + failures.append('FAIL line 7: a bind that checked before another looked repeats the look') populate = item(files['memacct.rs'], 'pub(crate) fn populate(') body = populate[populate.index('{'):] if 'Err(' in body or '?' in body or not body.rstrip('}').rstrip().endswith('populate()'): @@ -99,7 +114,8 @@ def check(files): def main(): parser = argparse.ArgumentParser() parser.add_argument('--mutation', choices=['skip-populate', 'no-unregister', 'late-unregister', - 'every-bind-looks', 'refuse', 'mem-pct-refuses']) + 'every-bind-looks', 'unlocked-look-check', 'refuse', + 'mem-pct-refuses']) args = parser.parse_args() failures = check(sources(args.mutation)) for f in failures: diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index f31ca5fe80df4..7b035b9646baf 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -557,7 +557,7 @@ def mutations(flag, names, base, expect=KILL): '--mutation', ['drop-g17', 'drop-m5', 'report-g16'], []), 'asahi-held-ceiling-tests.py': [([], PASS)] + mutations( '--mutation', ['skip-populate', 'no-unregister', 'late-unregister', 'every-bind-looks', - 'refuse', 'mem-pct-refuses'], []), + 'unlocked-look-check', 'refuse', 'mem-pct-refuses'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)],