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 44453ab8d800d..5290b8e3fd0e6 100644 --- a/drivers/gpu/drm/asahi/asahi_core.rs +++ b/drivers/gpu/drm/asahi/asahi_core.rs @@ -113,6 +113,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() }; @@ -245,12 +247,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 reclaimed first; never refuses (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 % 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 b5c34c9851d28..b1aa0bbe4dfba 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/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 4c2a0280bac9b..673375a2301dc 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -3113,6 +3113,7 @@ 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()); let variant = self.shared.variant; diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index d72fd857a9745..a943334423ab3 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -154,7 +154,12 @@ pub(crate) fn held_user_sg_table<'a>( { return Err(EACCES); } - mapped_sg_table(gem, dev) + 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(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/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/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index e5f60c14e2eb5..e921f16d8f113 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -26,10 +26,22 @@ //! `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. +//! - 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) @@ -72,6 +84,15 @@ 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, + /// 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. @@ -79,12 +100,19 @@ 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::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 { @@ -111,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, @@ -155,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 { @@ -173,26 +222,77 @@ impl Ledger { limit: AtomicU64::new(0), 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 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(), + let ram = total_ram_bytes(); + let client_pct = module_parameters::client_mem_limit_pct.value(); + let (limits, held) = configured( + 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 limits: device {} MiB, per client {} MiB (0 = none)\n", - limits.device >> 20, - limits.client >> 20 + "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 ); } - /// Admission capacities exported in the optional GET_PARAMS tail. - pub(crate) fn limits(&self) -> Limits { + /// 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: 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), @@ -204,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(()) } } @@ -263,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); } @@ -303,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); } } @@ -312,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. @@ -323,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), }, @@ -370,17 +523,49 @@ 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), + } +} + +/// 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 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); } } @@ -456,6 +641,16 @@ impl Charge { Self::user(commit, mm) } + /// 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. fn apply(&self, bytes: u64, held: bool) { match &self.kind { @@ -487,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 { @@ -500,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); } @@ -509,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(()) } @@ -569,8 +777,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); @@ -642,6 +849,162 @@ 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. + 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] { + 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_the_unheld_part_of_user_objects_adds_held_memory() -> Result { + let a = Client::new()?; + 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_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/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 279538b848e9c..62bb37cf6f2d4 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -139,7 +139,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::{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 d6fcb6fe85822..fd166be1edbee 100644 --- a/drivers/gpu/drm/asahi/mmu/residency.rs +++ b/drivers/gpu/drm/asahi/mmu/residency.rs @@ -20,6 +20,101 @@ 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() }; +} + +/// 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 }; + // 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; + } + // 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)); + } + 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 +/// 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 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); + assert_eq!(idle_vm_reclaim_feature_for(0), 0); + } +} + fn now_ns() -> u64 { ::ktime_get() as u64 } @@ -386,6 +481,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) } @@ -455,6 +553,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 ad9eb1be320ec..cc329765405ee 100644 --- a/drivers/gpu/drm/asahi/sysfs.c +++ b/drivers/gpu/drm/asahi/sysfs.c @@ -46,6 +46,10 @@ struct asahi_gpu_memory { u64 limit; u64 client_limit; u64 user_kept; + u64 held_limit; + u64 user_unreclaimable; + u64 unreclaimable_limit; + u64 client_unreclaimable_limit; }; struct asahi_stats_attribute { @@ -247,6 +251,14 @@ 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)); + 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; } @@ -259,7 +271,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 +315,9 @@ 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(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 84d0a047fa9e9..81a26ffaf7054 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; @@ -643,6 +646,18 @@ enum drm_asahi_feature { */ #define DRM_ASAHI_FEATURE_COMPUTE_TI_SPILL_LAUNCH ((1ULL) << 47) +/* + * 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, 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) + #define DRM_ASAHI_PARAM_GROUP_VM_STATUS 1 #define DRM_ASAHI_PARAM_GROUP_QUEUE_LIMITS 2 diff --git a/tools/asahi/asahi-driver-map-charge-tests.py b/tools/asahi/asahi-driver-map-charge-tests.py index d95446586e27b..1a667e9d7569e 100644 --- a/tools/asahi/asahi-driver-map-charge-tests.py +++ b/tools/asahi/asahi-driver-map-charge-tests.py @@ -4,9 +4,9 @@ The harness compiles from drivers/gpu/drm/asahi/pgtable.rs the page-table walk (walk(), walk_inner(), free_table()) with alloc_pages(), prepare_map(), prepare_driver_map(), charge_to() -and Drop; from memacct.rs Ledger::reserve(), Usage, try_add_within() and sub(); and from mmu.rs -VmInner::map_node(), which makes every mapping of the driver in a client's address space. They run -against a model of the page allocator that counts live pages. +and Drop; from memacct.rs Ledger::reserve() with what it calls, Usage, try_add_within() and +sub(); and from mmu.rs VmInner::map_node(), which makes every mapping of the driver in a +client's address space. They run against a model of the page allocator that counts live pages. What it shows: - at the client's limit and at the device's, map_node() succeeds: its tables are allocated and @@ -137,9 +137,11 @@ def optional(source, signature): f: impl FnOnce(*mut u8) -> Result) -> Result { std::mem::ManuallyDrop::new(Page(phys)).with_pointer_into_page(offset, len, f) } -struct Client { committed: AtomicU64, resident: AtomicU64 } +struct Client { committed: AtomicU64, unreclaimable: AtomicU64, resident: AtomicU64 } impl Client { - fn new() -> Arc { Arc::new(Self { committed: AtomicU64::new(0), resident: AtomicU64::new(0) }) } + fn new() -> Arc { + Arc::new(Self { committed: AtomicU64::new(0), unreclaimable: AtomicU64::new(0), resident: AtomicU64::new(0) }) + } fn committed(&self) -> u64 { self.committed.load(Ordering::Relaxed) } fn resident(&self) -> u64 { self.resident.load(Ordering::Relaxed) } } @@ -311,10 +313,15 @@ def harness(text): item(pt, 'pub(crate) fn ensure_unmapped('), item(pt, 'pub(crate) fn discard_partial_map('), optional(pt, 'pub(crate) fn prepare_driver_map('), optional(pt, 'fn prepare_tables(')] methods = '\n'.join(methods).replace('crate::memacct::', '').replace('crate::mem::sync()', 'mem::sync()') + # Ledger::reserve() and what it calls; a tree with limits on what idle reclaim never releases + # (linux#3685) has more of them. ledger = item(acct, 'pub(crate) struct Ledger {') + '\nimpl Ledger {\n' + '\n'.join( - item(acct, s) for s in ('pub(crate) const fn new() -> Self {', 'pub(crate) fn set_limits(', - 'fn reserve(&self')) + '\n}\n' - ledger += '\n'.join(item(acct, s) for s in ('pub(crate) struct Limits {', 'fn try_add_within(', 'fn sub(')) + [item(acct, s) for s in ('pub(crate) const fn new() -> Self {', 'pub(crate) fn set_limits(', + 'fn reserve(&self')] + + [optional(acct, s) for s in ('fn limits(&self)', 'fn unreclaimable_limits(&self)', + 'fn release(&self')]) + '\n}\n' + ledger += '\n'.join([item(acct, s) for s in ('pub(crate) struct Limits {', 'fn try_add_within(', 'fn sub(')] + + [optional(acct, 'fn try_add_both(')]) usage = '\n'.join(item(acct, s) for s in ('pub(crate) struct Usage {', 'impl Usage {', 'impl Drop for Usage {')) return '\n'.join([ PRELUDE, consts, 'type Pte = AtomicU64;', missing, ledger, usage, table, diff --git a/tools/asahi/asahi-held-ceiling-tests.py b/tools/asahi/asahi-held-ceiling-tests.py new file mode 100644 index 0000000000000..bd18cade8eeb9 --- /dev/null +++ b/tools/asahi/asahi-held-ceiling-tests.py @@ -0,0 +1,129 @@ +#!/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; +- 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 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 / +unlocked-look-check / refuse / mem-pct-refuses 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 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) + 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 == '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) + 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('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'] + 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') + 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') + 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') + 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 < 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()'): + 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', + 'every-bind-looks', 'unlocked-look-check', 'refuse', + 'mem-pct-refuses']) + 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/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/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 497e690a65f8c..7941c94e4e395 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -623,6 +623,11 @@ 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', 'every-bind-looks', + 'unlocked-look-check', 'refuse', 'mem-pct-refuses'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)],