From cb8099602b9179342cba1f0ecd796dbfb331c3d7 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 04:37:50 -0500 Subject: [PATCH 1/4] drm/asahi: memacct: count held bytes, not a held flag A charge counted the object's backing as held in full or not at all. Record the bytes held instead, so that a part of the backing can be counted: set_held_bytes() counts the difference to what was counted before, up to the object's size, and set_held() holds all or nothing as before. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/memacct.rs | 88 +++++++++++++++++++++++--------- 1 file changed, 63 insertions(+), 25 deletions(-) diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index 0eb959e810545..073da45ac9b0d 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -326,8 +326,9 @@ enum Kind { pub(crate) struct Charge { kind: Kind, bytes: u64, - /// Whether the bytes are currently counted as held by the GPU. - held: AtomicBool, + /// The bytes currently counted as held: all of them while the object's whole backing is + /// held, fewer while only some of its pages are (CPU faults in revocable mappings). + held: AtomicU64, /// Whether the bytes are currently counted as kept resident. kept: AtomicBool, } @@ -344,7 +345,7 @@ impl Charge { Self { kind: Kind::None, bytes: 0, - held: AtomicBool::new(false), + held: AtomicU64::new(0), kept: AtomicBool::new(false), } } @@ -354,7 +355,7 @@ impl Charge { Self { kind: Kind::Kernel(ledger), bytes, - held: AtomicBool::new(false), + held: AtomicU64::new(0), kept: AtomicBool::new(false), } } @@ -370,7 +371,7 @@ impl Charge { Self { kind: Kind::User { commit, mm }, bytes, - held: AtomicBool::new(false), + held: AtomicU64::new(0), kept: AtomicBool::new(false), } } @@ -381,33 +382,30 @@ impl Charge { Self::user(commit, mm) } - fn pages(&self) -> isize { - isize::try_from(self.bytes / PAGE_SIZE as u64).unwrap_or(isize::MAX) - } - - fn apply(&self, held: bool) { + /// Counts `bytes` more as held (`held`) or as no longer held. + fn apply(&self, bytes: u64, held: bool) { match &self.kind { Kind::None => {} Kind::Kernel(ledger) => { if held { - ledger.kernel_resident.fetch_add(self.bytes, Ordering::AcqRel); + ledger.kernel_resident.fetch_add(bytes, Ordering::AcqRel); } else { - sub(&ledger.kernel_resident, self.bytes); + sub(&ledger.kernel_resident, bytes); } } Kind::User { commit, mm } => { if held { - commit.client.resident.fetch_add(self.bytes, Ordering::AcqRel); + commit.client.resident.fetch_add(bytes, Ordering::AcqRel); commit .ledger .user_resident - .fetch_add(self.bytes, Ordering::AcqRel); + .fetch_add(bytes, Ordering::AcqRel); } else { - sub(&commit.client.resident, self.bytes); - sub(&commit.ledger.user_resident, self.bytes); + sub(&commit.client.resident, bytes); + sub(&commit.ledger.user_resident, bytes); } if let Some(mm) = mm { - let pages = self.pages(); + let pages = isize::try_from(bytes / PAGE_SIZE as u64).unwrap_or(isize::MAX); mm.add_rss_counter(RssCounter::Shmem, if held { pages } else { -pages }); } } @@ -432,21 +430,32 @@ impl Charge { ledger.refused.fetch_add(1, Ordering::Relaxed); return Err(ENOMEM); } - if held { - to.resident.fetch_add(bytes, Ordering::AcqRel); - sub(&commit.client.resident, bytes); + if held != 0 { + to.resident.fetch_add(held, Ordering::AcqRel); + sub(&commit.client.resident, held); } sub(&commit.client.committed, bytes); commit.client = to.clone(); Ok(()) } - /// Records that the GPU now holds (or no longer holds) the object's backing. + /// Records that all of the object's backing is now held (or none of it is). /// /// Idempotent: only a change of state is counted. pub(crate) fn set_held(&self, held: bool) { - if self.held.swap(held, Ordering::AcqRel) != held { - self.apply(held); + self.set_held_bytes(if held { self.bytes } else { 0 }); + } + + /// Records that `bytes` of the object's backing are now held, at most its size. + /// + /// Idempotent: only the difference to the bytes counted before is counted. + pub(crate) fn set_held_bytes(&self, bytes: u64) { + let bytes = bytes.min(self.bytes); + let before = self.held.swap(bytes, Ordering::AcqRel); + if bytes > before { + self.apply(bytes - before, true); + } else if before > bytes { + self.apply(before - bytes, false); } } @@ -582,7 +591,7 @@ mod tests { HELD.set_limits(Limits { device: 0, client: 0 }); let a = Client::new()?; let charge = Charge::user(HELD.admit(&a, 8 * MIB)?, None); - assert!(!charge.held.load(Ordering::Relaxed)); + assert_eq!(charge.held.load(Ordering::Relaxed), 0); charge.set_held(true); charge.set_held(true); assert_eq!(a.resident(), 8 * MIB); @@ -659,11 +668,40 @@ mod tests { Ok(()) } + static PART: Ledger = Ledger::new(); + + #[test] + fn some_pages_are_charged_as_they_are_held() -> Result { + const PAGE: u64 = PAGE_SIZE as u64; + PART.set_limits(Limits { device: 0, client: 0 }); + let a = Client::new()?; + let charge = Charge::user(PART.admit(&a, 8 * PAGE)?, None); + // Pages held one by one, as CPU faults in a revocable mapping hold them. + charge.set_held_bytes(PAGE); + charge.set_held_bytes(2 * PAGE); + assert_eq!(a.resident(), 2 * PAGE); + assert_eq!(PART.user_resident.load(Ordering::Relaxed), 2 * PAGE); + // All of the backing, then some of it again; never more than the object's size. + charge.set_held(true); + assert_eq!(a.resident(), 8 * PAGE); + charge.set_held_bytes(16 * PAGE); + assert_eq!(a.resident(), 8 * PAGE); + charge.set_held_bytes(3 * PAGE); + assert_eq!(a.resident(), 3 * PAGE); + charge.set_held_bytes(3 * PAGE); + assert_eq!(PART.user_resident.load(Ordering::Relaxed), 3 * PAGE); + // Freeing the object uncharges what it held. + drop(charge); + assert_eq!(a.resident(), 0); + assert_eq!(PART.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } + #[test] fn imports_are_not_counted() { let charge = Charge::none(); charge.set_held(true); - assert!(charge.held.load(Ordering::Relaxed)); + assert_eq!(charge.held.load(Ordering::Relaxed), 0); drop(charge); } From 5633d0b071913426afe61d04cc56bddf3f830d71 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 04:37:50 -0500 Subject: [PATCH 2/4] drm/shmem-helper: report the CPU pages of revocable mappings CPU faults in revocable mappings populate an object's pages one at a time while no device mapping holds its page array. Those pages stay referenced and the mapping unevictable until the mappings are revoked or closed, but pages_changed() reported only the page array, so a driver could not account for them. Report the number of pages that back the object instead of whether its array exists: all of its pages while the array does, otherwise the populated CPU pages, after each change to either. The Rust binding passes the count on and gains resident_pages_locked(), which reads the same number under the reservation lock. drm/asahi charges the pages reported, so the client and the process that created a VM-private object are charged for the pages its CPU mappings fault in, and the mapping is marked held while any are. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/gem.rs | 39 ++++++++++-------- drivers/gpu/drm/drm_gem_shmem_helper.c | 17 ++++++-- include/drm/drm_gem_shmem_helper.h | 19 +++++---- rust/kernel/drm/gem/mod.rs | 12 +++--- rust/kernel/drm/gem/shmem.rs | 57 +++++++++++++++++++------- 5 files changed, 94 insertions(+), 50 deletions(-) diff --git a/drivers/gpu/drm/asahi/gem.rs b/drivers/gpu/drm/asahi/gem.rs index 2f071da87d360..d72fd857a9745 100644 --- a/drivers/gpu/drm/asahi/gem.rs +++ b/drivers/gpu/drm/asahi/gem.rs @@ -81,21 +81,22 @@ pub(crate) struct AsahiObject { /// Type alias for the shmem GEM object type for this driver. pub(crate) type Object = shmem::Object; -/// Marks whether the pages of `gem` are held. +/// Marks `resident` pages of `gem` held, or none. /// -/// It follows the object's shmem page array ([`AsahiObject::pages_changed`]). Every holder of -/// that array keeps its pages referenced (a device SG table, a kernel vmap, a PFN CPU mapping or -/// a dma-buf pin), so the pages cannot migrate. Unmarked, the compaction migrate scanner still +/// It follows the pages that back the object ([`AsahiObject::pages_changed`]): all of them while +/// its shmem page array exists, otherwise those that CPU faults populated in revocable mappings. +/// Every holder keeps its pages referenced (a device SG table, a kernel vmap, a PFN CPU mapping +/// or a dma-buf pin), so the pages cannot migrate. Unmarked, the compaction migrate scanner still /// isolates them from the unevictable LRU and every migration fails. The shmem mapping of a /// held object is therefore marked inaccessible, which compaction and migration check and which /// comes with unevictable, as `mapping_set_inaccessible()` sets it; nothing reads or writes a GEM -/// shmem file through its mapping. Releasing the array (the last holder gone, idle backing -/// released or the object purged) clears the mark, so the released pages can be swapped and -/// migrated again. +/// shmem file through its mapping. Releasing the last of them (the last holder gone, mappings +/// revoked, idle backing released or the object purged) clears the mark, so the released pages +/// can be swapped and migrated again. /// -/// The same transitions charge and uncharge the held pages (see [`memacct`]): a held user object -/// counts towards the resident set of the process that created it. -fn set_mapping_held(gem: &Object, held: bool) { +/// The same transitions charge and uncharge the held pages (see [`memacct`]): the held pages of a +/// user object count towards the resident set of the process that created it. +fn set_mapping_held(gem: &Object, resident: usize) { let raw = gem.as_raw(); // SAFETY: `gem` keeps the GEM object alive. A shmem-backed object's `filp` and its // `f_mapping` are set at initialization and never change; imported objects have none. @@ -115,12 +116,13 @@ fn set_mapping_held(gem: &Object, held: bool) { unsafe { AtomicUsize::from_ptr(core::ptr::addr_of_mut!((*mapping).flags).cast::()) }; let inaccessible = 1usize << kernel::bindings::mapping_flags_AS_INACCESSIBLE; let unevictable = 1usize << kernel::bindings::mapping_flags_AS_UNEVICTABLE; - if held { + if resident != 0 { flags.fetch_or(inaccessible | unevictable, Ordering::Relaxed); } else { flags.fetch_and(!inaccessible, Ordering::Relaxed); } - gem.charge.set_held(held); + let bytes = resident.saturating_mul(kernel::page::PAGE_SIZE); + gem.charge.set_held_bytes(u64::try_from(bytes).unwrap_or(u64::MAX)); } /// Takes the SG table of `gem`, which holds its pages for the device (and so the object, see @@ -654,12 +656,13 @@ impl DriverObject for AsahiObject { } } - /// The page array of `obj` was populated or released: its backing is held from the first - /// holder of the array to the last (see [`set_mapping_held`]). That includes the holders the - /// generic shmem helpers create, CPU mappings, dma-buf pins and kernel vmaps, as well as the - /// SG tables of device mappings. - fn pages_changed(obj: &::Object, present: bool) { - set_mapping_held(obj, present); + /// The pages that back `obj` changed to `resident` (see [`set_mapping_held`]). All of them + /// are held from the first holder of its page array to the last, which includes the holders + /// the generic shmem helpers create (CPU mappings, dma-buf pins and kernel vmaps) as well as + /// the SG tables of device mappings. Without the array, CPU faults in revocable mappings hold + /// one page each. + fn pages_changed(obj: &::Object, resident: usize) { + set_mapping_held(obj, resident); } /// Optional handle for exporting a gem object. diff --git a/drivers/gpu/drm/drm_gem_shmem_helper.c b/drivers/gpu/drm/drm_gem_shmem_helper.c index edc59c673a049..3aa76e0acfb05 100644 --- a/drivers/gpu/drm/drm_gem_shmem_helper.c +++ b/drivers/gpu/drm/drm_gem_shmem_helper.c @@ -252,6 +252,15 @@ void drm_gem_shmem_free(struct drm_gem_shmem_object *shmem) } EXPORT_SYMBOL_GPL(drm_gem_shmem_free); +/* Reports the pages that back the object now (see &drm_gem_shmem_object.pages_changed). */ +static void drm_gem_shmem_pages_changed(struct drm_gem_shmem_object *shmem) +{ + if (shmem->pages_changed) + shmem->pages_changed(shmem, shmem->pages ? + shmem->base.size >> PAGE_SHIFT : + shmem->cpu_pages_count); +} + static int drm_gem_shmem_get_pages_locked(struct drm_gem_shmem_object *shmem) { struct drm_gem_object *obj = &shmem->base; @@ -283,8 +292,7 @@ static int drm_gem_shmem_get_pages_locked(struct drm_gem_shmem_object *shmem) refcount_set(&shmem->pages_use_count, 1); - if (shmem->pages_changed) - shmem->pages_changed(shmem, true); + drm_gem_shmem_pages_changed(shmem); return 0; } @@ -314,8 +322,7 @@ void drm_gem_shmem_put_pages_locked(struct drm_gem_shmem_object *shmem) shmem->pages_mark_accessed_on_put = false; shmem->pages_mark_dirty_on_put = false; - if (shmem->pages_changed) - shmem->pages_changed(shmem, false); + drm_gem_shmem_pages_changed(shmem); } } EXPORT_SYMBOL_GPL(drm_gem_shmem_put_pages_locked); @@ -591,6 +598,7 @@ static struct page *drm_gem_shmem_cpu_page_locked(struct drm_gem_shmem_object *s return page; shmem->cpu_pages[index] = page; shmem->cpu_pages_count++; + drm_gem_shmem_pages_changed(shmem); return page; } @@ -628,6 +636,7 @@ static void drm_gem_shmem_put_cpu_pages_locked(struct drm_gem_shmem_object *shme } kvfree(shmem->cpu_pages); shmem->cpu_pages = NULL; + drm_gem_shmem_pages_changed(shmem); } static struct page *drm_gem_shmem_present_page(struct drm_gem_shmem_object *shmem, diff --git a/include/drm/drm_gem_shmem_helper.h b/include/drm/drm_gem_shmem_helper.h index cdc059289894e..8d611b3f5cfcb 100644 --- a/include/drm/drm_gem_shmem_helper.h +++ b/include/drm/drm_gem_shmem_helper.h @@ -48,15 +48,18 @@ struct drm_gem_shmem_object { bool pages_bounded_reclaim; /** - * @pages_changed: Optional. Called under base.resv right after @pages - * is populated (@present true) and right after it is released (false). - * Every holder of @pages counts in @pages_use_count: CPU VMAs other - * than revocable ones, pins (dma-buf attachments), kernel vmaps and - * the device SG table. This reports the first of them and the end of - * the last, so the driver can account the backing for each of them. - * Set before the object is published. + * @pages_changed: Optional. Called under base.resv whenever the number + * of pages that back the object changes, with that number: all of the + * object's pages while @pages exists, otherwise the populated entries of + * @cpu_pages. Every holder of @pages counts in @pages_use_count: CPU + * VMAs other than revocable ones, pins (dma-buf attachments), kernel + * vmaps and the device SG table. The pages that CPU faults populate in + * revocable VMAs are held until the VMAs are revoked or the last of + * them is closed. The driver can account the backing for each holder + * from this. Set before the object is published. */ - void (*pages_changed)(struct drm_gem_shmem_object *shmem, bool present); + void (*pages_changed)(struct drm_gem_shmem_object *shmem, + unsigned long resident); /** * @cpu_pages: Pages populated one at a time by CPU faults on revocable diff --git a/rust/kernel/drm/gem/mod.rs b/rust/kernel/drm/gem/mod.rs index 83918bc4a1e29..eb6ab79dd1f10 100644 --- a/rust/kernel/drm/gem/mod.rs +++ b/rust/kernel/drm/gem/mod.rs @@ -119,12 +119,14 @@ pub trait DriverObject: Sync + Send + Sized + 'static { unimplemented!() } - /// The shmem backing pages of an object were populated (`present`) or released. + /// The number of shmem pages that back an object changed to `resident`. /// - /// Called with the object's reservation lock held, for the first holder of the pages and - /// after the last one: a CPU mapping (other than a revocable one), a pin (a dma-buf - /// attachment), a kernel vmap or the device SG table. It must not take that lock. - fn pages_changed(_obj: &DriverAllocImpl, _present: bool) { + /// All of the object's pages are resident from the first holder of its page array to the + /// last one: a CPU mapping (other than a revocable one), a pin (a dma-buf attachment), a + /// kernel vmap or the device SG table. Without the array, the pages that CPU faults populated + /// in revocable mappings are, until the mappings are revoked or closed. Called with the + /// object's reservation lock held; it must not take that lock. + fn pages_changed(_obj: &DriverAllocImpl, _resident: usize) { build_error!(crate::error::VTABLE_DEFAULT_ERROR) } diff --git a/rust/kernel/drm/gem/shmem.rs b/rust/kernel/drm/gem/shmem.rs index 887b17066481a..68a73959c1e80 100644 --- a/rust/kernel/drm/gem/shmem.rs +++ b/rust/kernel/drm/gem/shmem.rs @@ -245,17 +245,17 @@ impl Object { /// [`DriverObject::pages_changed`]. extern "C" fn pages_changed_callback( shmem: *mut bindings::drm_gem_shmem_object, - present: bool, + resident: usize, ) { // SAFETY: The C helpers pass a live shmem object of this driver, with its reservation lock // held. Every GEM object of the driver is an `Object` (see `create_object_callback()`). let obj: &gem::DriverAllocImpl = unsafe { IntoGEMObject::from_raw(&raw mut (*shmem).base) }; - T::pages_changed(obj, present); + T::pages_changed(obj, resident); } /// The `pages_changed` callback to install in a new object. - const PAGES_CHANGED: Option = + const PAGES_CHANGED: Option = if T::HAS_PAGES_CHANGED { Some(Self::pages_changed_callback) } else { @@ -661,6 +661,25 @@ impl Object { !unsafe { (*self.as_raw_shmem()).sgt }.is_null() } + /// The shmem pages that back the object now, as [`DriverObject::pages_changed`] reports + /// them: all of them while its page array exists, otherwise those CPU faults populated in + /// revocable mappings. + /// + /// # Safety + /// + /// The caller holds the object's DMA reservation lock. + pub unsafe fn resident_pages_locked(&self) -> usize { + let shmem = self.as_raw_shmem(); + // SAFETY: Reservation ownership serializes the page array and the CPU page count. + unsafe { + if (*shmem).pages.is_null() { + (*shmem).cpu_pages_count + } else { + self.size() >> crate::page::PAGE_SHIFT + } + } + } + /// Whether backing without a Rust SG lease can be reclaimed or purged. /// /// Also accepts backing whose SG table was already released by idle reclaim. @@ -1120,7 +1139,6 @@ mod tests { io::Io, page::PAGE_SIZE, // }; - use core::sync::atomic::AtomicBool; // The bare minimum needed to create a fake drm driver for kunit @@ -1130,8 +1148,8 @@ mod tests { struct KunitFile; #[pin_data] struct KunitObject { - /// Whether `pages_changed` last reported the pages present. - present: AtomicBool, + /// The resident pages `pages_changed` last reported. + resident: AtomicUsize, /// How often `pages_changed` was called. changes: AtomicUsize, } @@ -1169,13 +1187,13 @@ mod tests { _args: Self::Args, ) -> impl PinInit { try_pin_init!(KunitObject { - present: AtomicBool::new(false), + resident: AtomicUsize::new(0), changes: AtomicUsize::new(0), }) } - fn pages_changed(obj: &Object, present: bool) { - obj.present.store(present, Ordering::Release); + fn pages_changed(obj: &Object, resident: usize) { + obj.resident.store(resident, Ordering::Release); obj.changes.fetch_add(1, Ordering::AcqRel); } } @@ -1273,25 +1291,34 @@ mod tests { #[test] fn pages_changed_spans_every_holder() -> Result { + const PAGES: usize = 4; let (dev, drm) = create_drm_dev()?; - let obj = Object::::new(&drm, PAGE_SIZE, ObjectConfig::default(), ())?; - assert!(!obj.present.load(Ordering::Acquire)); + let obj = Object::::new(&drm, PAGES * PAGE_SIZE, ObjectConfig::default(), ())?; + let resident = |obj: &Object| { + let _guard = DmaResvGuard::new(obj); + // SAFETY: The reservation is held. + let now = unsafe { obj.resident_pages_locked() }; + // The callback reported what the object now has. + assert_eq!(obj.resident.load(Ordering::Acquire), now); + now + }; + assert_eq!(resident(&obj), 0); let vmap = obj.vmap::<4>()?; - assert!(obj.present.load(Ordering::Acquire)); + assert_eq!(resident(&obj), PAGES); let table = obj.sg_table(dev.as_ref().as_ref())?.into_lease(); drop(vmap); // The device SG table still holds the pages. - assert!(obj.present.load(Ordering::Acquire)); + assert_eq!(resident(&obj), PAGES); drop(table); { let _guard = DmaResvGuard::new(&obj); // SAFETY: Reservation held; no device mappings or SG leases exist in this test. unsafe { obj.release_idle_pages_locked()? }; } - assert!(!obj.present.load(Ordering::Acquire)); + assert_eq!(resident(&obj), 0); assert_eq!(obj.changes.load(Ordering::Acquire), 2); drop(obj.vmap::<4>()?); - assert!(!obj.present.load(Ordering::Acquire)); + assert_eq!(resident(&obj), 0); assert_eq!(obj.changes.load(Ordering::Acquire), 4); Ok(()) } From a4cb3c61450ec7a72b8e54888bcceb2c506a6858 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 04:37:51 -0500 Subject: [PATCH 3/4] drm/asahi: mmu: reclaim the CPU pages of idle objects Idle reclaim counted and released only objects with a device SG table. Once it had released an object's table, pages that CPU faults then populated in the object's revocable mappings stayed held until the VM's next job or until the mappings were closed. Count the pages that back an idle object, its page array or its CPU pages, and release whichever it has: releasing idle backing revokes the CPU mappings as well. Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/mmu/residency.rs | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/drivers/gpu/drm/asahi/mmu/residency.rs b/drivers/gpu/drm/asahi/mmu/residency.rs index d25e2c0278bb4..2489999cd8803 100644 --- a/drivers/gpu/drm/asahi/mmu/residency.rs +++ b/drivers/gpu/drm/asahi/mmu/residency.rs @@ -463,15 +463,16 @@ impl Vm { // this reservation; linked aliases retain their borrowed BO and GEM. let _ = unsafe { inner.for_each_private_bo(|_, bo| { let object = bo.obj(); - // Count retained backing on idle VMs, and purgeable contents even if idle - // reclaim already released the table. Never wait on the BO mutex under resv. + // Count retained backing on idle VMs, including pages that CPU faults populated + // after idle reclaim released the table, and purgeable contents even if it did. + // Never wait on the BO mutex under resv. let Some(segments) = bo.data().segments.try_lock() else { return Ok(true); }; let advised = object.madv_locked() > 0; + let resident = object.resident_pages_locked(); let releasable = if segments.is_some() { object.sole_sg_lease_releasable_locked() } else { - (advised || object.has_sg_table_locked()) - && object.unleased_pages_releasable_locked() + (advised || resident != 0) && object.unleased_pages_releasable_locked() }; let counted = if advised { !kept @@ -479,7 +480,11 @@ impl Vm { idle && object.keep_resident() == kept }; if object.idle_reclaim_candidate() && counted && releasable { - pages = pages.saturating_add(object.size() / kernel::page::PAGE_SIZE); + pages = pages.saturating_add(if advised { + object.size() / kernel::page::PAGE_SIZE + } else { + resident + }); } Ok(true) }) }; @@ -621,8 +626,10 @@ impl Vm { object.sole_sg_lease_releasable_locked() } else { // A competing lease may have made the previous release fail after we - // dropped our segments. Retry that table, but do not count empty backing. - object.has_sg_table_locked() && object.unleased_pages_releasable_locked() + // dropped our segments: retry that table. Or CPU faults populated pages + // after an earlier release: revoke them. Do not count empty backing. + object.resident_pages_locked() != 0 + && object.unleased_pages_releasable_locked() }; if !releasable { return Ok(true); } } @@ -647,8 +654,9 @@ impl Vm { // Every private GPUVA alias was removed from the device page // tables above. Kernel mappings and other SG owners are excluded; // the C/Rust backing helper rechecks exclusion before release. + let resident = object.resident_pages_locked(); if object.release_idle_pages_locked().is_ok() { - unpinned = unpinned.saturating_add(object.size() / kernel::page::PAGE_SIZE); + unpinned = unpinned.saturating_add(resident); } Ok(unpinned < target) }) }; From fbd98d12d6bdd1d8561ba3286b9d344c1343a847 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 26 Nov 2026 04:37:51 -0500 Subject: [PATCH 4/4] selftests: drm/asahi: charges and reclaim of CPU-faulted pages Check that each page CPU faults populate in a VM-private object is charged to its client and creating process until the mapping goes. With ASAHI_RESIDENCY_DROP_CACHES=1, check that reclaim releasing an idle object's backing moves it off the unevictable LRU, that it then revokes the pages CPU faults populate in the object as well, and that their contents fault back in. Signed-off-by: DjDeveloperr --- .../drivers/gpu/asahi-residency/residency.c | 104 +++++++++++++++++- 1 file changed, 102 insertions(+), 2 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/asahi-residency/residency.c b/tools/testing/selftests/drivers/gpu/asahi-residency/residency.c index a6dc704af3880..bef2f49683bc5 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-residency/residency.c +++ b/tools/testing/selftests/drivers/gpu/asahi-residency/residency.c @@ -20,8 +20,9 @@ * kept_objects_stay_purgeable and requests_serialize_with_reclaim, which * write to the memory.reclaim file of the root memory cgroup. * - * ASAHI_RESIDENCY_DROP_CACHES=1 runs kept_objects_go_under_urgent_pressure, - * which writes 2 to /proc/sys/vm/drop_caches. That runs every shrinker of + * ASAHI_RESIDENCY_DROP_CACHES=1 runs reclaim_revokes_cpu_faulted_pages and + * kept_objects_go_under_urgent_pressure, which write 2 to + * /proc/sys/vm/drop_caches. That runs every shrinker of * the system at the last reclaim priority: it drops the dentry and inode * caches, with the page cache of the files they stood for, and the idle * memory of every GPU client. @@ -201,6 +202,22 @@ static long long rss_shmem(void) return kb < 0 ? -1 : kb << 10; } +/* Unevictable in bytes: the memory on the system's unevictable LRU lists. */ +static long long unevictable(void) +{ + char line[256]; + long long kb = -1; + FILE *f = fopen("/proc/meminfo", "r"); + + if (!f) + return -1; + while (fgets(line, sizeof(line), f)) + if (sscanf(line, "Unevictable: %lld kB", &kb) == 1) + break; + fclose(f); + return kb < 0 ? -1 : kb << 10; +} + /* MemAvailable in bytes. */ static long long mem_available(void) { @@ -1323,6 +1340,39 @@ TEST_F(objects, foreign_imports_hold_the_backing) EXPECT_EQ(rss0, rss_shmem()); } +/* + * The CPU mappings of a VM-private object can be revoked: without a device + * mapping that holds all of its pages, each CPU fault holds one page. The + * object's client and creating process are charged for those pages, until + * the last mapping goes. + */ +TEST_F(asahi, cpu_faults_charge_their_pages) +{ + const uint64_t size = 64 * PAGE; + struct drm_asahi_gem_create bo = { + .size = size, .flags = DRM_ASAHI_GEM_VM_PRIVATE, .vm_id = self->vm, + }; + long long resident0 = client_resident(self->fd), rss0 = rss_shmem(); + char *map; + + ASSERT_GE(resident0, 0); + ASSERT_GE(rss0, 0); + ASSERT_EQ(0, ioc(self->fd, DRM_IOCTL_ASAHI_GEM_CREATE, &bo)); + map = map_object(self->fd, bo.handle, size); + ASSERT_NE(MAP_FAILED, map); + EXPECT_EQ(resident0, client_resident(self->fd)); + map[0] = 1; + map[8 * PAGE] = 2; + map[8 * PAGE + 1] = 3; + map[63 * PAGE] = 4; + EXPECT_EQ(resident0 + 3 * (long long)PAGE, client_resident(self->fd)); + EXPECT_EQ(rss0 + 3 * (long long)PAGE, rss_shmem()); + ASSERT_EQ(0, munmap(map, size)); + EXPECT_EQ(resident0, client_resident(self->fd)); + EXPECT_EQ(rss0, rss_shmem()); + close_handle(self->fd, bo.handle); +} + /* * Of two idle objects, reclaim releases the one that is not kept first, at * any priority. Reclaim that does not come to the kept objects (see the top @@ -1565,6 +1615,56 @@ TEST_F_TIMEOUT(asahi, requests_serialize_with_reclaim, 180) close_handle(self->fd, control); } +/* + * Reclaim releases the backing of an idle object, which leaves the + * unevictable LRU: the system counts it there, which moves by more than + * the per-CPU counter drift for an object this size. CPU faults in the + * object then hold their pages one at a time, until reclaim revokes them + * as well. The contents stay and fault back in. + */ +TEST_F_TIMEOUT(asahi, reclaim_revokes_cpu_faulted_pages, 60) +{ + const uint64_t size = 16384 * PAGE; + const char *run = getenv("ASAHI_RESIDENCY_DROP_CACHES"); + long long resident0 = client_resident(self->fd), held; + uint32_t bo; + char *map; + + if (!run || strcmp(run, "1")) + SKIP(return, "set ASAHI_RESIDENCY_DROP_CACHES=1 to drop the system's caches"); + if (geteuid()) + SKIP(return, "dropping caches needs root"); + if (mem_available() < (long long)(4 * size)) + SKIP(return, "not enough available memory for the test object"); + ASSERT_GE(resident0, 0); + bo = bound_object(self->fd, self->vm, &self->va, self->va_end, size); + ASSERT_NE(0, bo); + EXPECT_EQ(resident0 + (long long)size, client_resident(self->fd)); + map = map_object(self->fd, bo, size); + ASSERT_NE(MAP_FAILED, map); + map[0] = 0x5a; + + sleep(IDLE_SECONDS); + held = unevictable(); + ASSERT_GE(held, (long long)size / 2); + ASSERT_EQ(0, write_string("/proc/sys/vm/drop_caches", "2")); + ASSERT_EQ(resident0, client_resident(self->fd)); + EXPECT_LE(unevictable(), held - (long long)size / 2); + EXPECT_EQ(0x5a, map[0]); + map[8 * PAGE] = 0x3c; + EXPECT_EQ(resident0 + 2 * (long long)PAGE, client_resident(self->fd)); + + sleep(IDLE_SECONDS); + ASSERT_EQ(0, write_string("/proc/sys/vm/drop_caches", "2")); + EXPECT_EQ(resident0, client_resident(self->fd)); + EXPECT_EQ(0x5a, map[0]); + EXPECT_EQ(0x3c, map[8 * PAGE]); + EXPECT_EQ(resident0 + 2 * (long long)PAGE, client_resident(self->fd)); + ASSERT_EQ(0, munmap(map, size)); + EXPECT_EQ(resident0, client_resident(self->fd)); + close_handle(self->fd, bo); +} + /* * Urgent reclaim (here: every shrinker run at the last priority) releases * kept objects too. Where the shrinker passes can be recorded, the record