Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 21 additions & 18 deletions drivers/gpu/drm/asahi/gem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AsahiObject>;

/// 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.
Expand All @@ -115,12 +116,13 @@ fn set_mapping_held(gem: &Object, held: bool) {
unsafe { AtomicUsize::from_ptr(core::ptr::addr_of_mut!((*mapping).flags).cast::<usize>()) };
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
Expand Down Expand Up @@ -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: &<Self::Driver as drm::Driver>::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: &<Self::Driver as drm::Driver>::Object, resident: usize) {
set_mapping_held(obj, resident);
}

/// Optional handle for exporting a gem object.
Expand Down
88 changes: 63 additions & 25 deletions drivers/gpu/drm/asahi/memacct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -400,8 +400,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,
}
Expand All @@ -418,7 +419,7 @@ impl Charge {
Self {
kind: Kind::None,
bytes: 0,
held: AtomicBool::new(false),
held: AtomicU64::new(0),
kept: AtomicBool::new(false),
}
}
Expand All @@ -428,7 +429,7 @@ impl Charge {
Self {
kind: Kind::Kernel(ledger),
bytes,
held: AtomicBool::new(false),
held: AtomicU64::new(0),
kept: AtomicBool::new(false),
}
}
Expand All @@ -444,7 +445,7 @@ impl Charge {
Self {
kind: Kind::User { commit, mm },
bytes,
held: AtomicBool::new(false),
held: AtomicU64::new(0),
kept: AtomicBool::new(false),
}
}
Expand All @@ -455,33 +456,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 });
}
}
Expand All @@ -506,21 +504,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);
}
}

Expand Down Expand Up @@ -656,7 +665,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);
Expand Down Expand Up @@ -733,6 +742,35 @@ 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(())
}

static USAGE: Ledger = Ledger::new();

#[test]
Expand Down Expand Up @@ -766,7 +804,7 @@ mod tests {
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);
}

Expand Down
24 changes: 16 additions & 8 deletions drivers/gpu/drm/asahi/mmu/residency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -463,23 +463,28 @@ 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
} else {
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)
}) };
Expand Down Expand Up @@ -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); }
}
Expand All @@ -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)
}) };
Expand Down
17 changes: 13 additions & 4 deletions drivers/gpu/drm/drm_gem_shmem_helper.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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,
Expand Down
19 changes: 11 additions & 8 deletions include/drm/drm_gem_shmem_helper.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading