From 29e65832352fe86a7fb9925ffed0412fd1682e6d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:40:07 +1100 Subject: [PATCH 1/4] drm/asahi: g16: share the live VMs between processes, not only open files Every G16 user VM holds one of the device's 63 TTBAT slots for its lifetime. The live-VM limit was counted per open file only, so it did not bound how many of the slots one process holds, and VM creation by other clients could fail with ENOSPC until that process exits. Count the live VMs against the process that created them as well, by the rule the queues already use (queue_share): a process may always hold half of the VMs, and more only while a reserve stays free for the others, or while it is the only process holding any. The count follows the VM's live token, so a VM whose handle is closed but whose binding is still deferred keeps counting. The eight-per-file limit stays. queue_share gains Shares, the same per-process count kept under its owner's lock, so the registry can apply the rule to its own resource. Add a host test that runs the production reservation and release against mocks: VMs stay available to a new process and the compositor beside a process holding many, a VM given back can be created again, and a process alone may still use every VM. The previous reservation and a share that is never given back are mutants. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g16/vm.rs | 63 ++++--- drivers/gpu/drm/asahi/queue_share.rs | 40 ++++- tools/asahi/g16-vm-share-tests.py | 237 +++++++++++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 4 files changed, 319 insertions(+), 22 deletions(-) create mode 100755 tools/asahi/g16-vm-share-tests.py diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 5bb4f434454cc..2ea9bfdbdb7f5 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -12,7 +12,8 @@ //! (`vm.install_driver_mappings`): user binds there fail (EINVAL); //! - bind it to an exclusive TTBAT slot ([`mmu::Uat::bind`]) for as long as its [`VmState`] //! lives; at most [`super::hw::sizes::MAX_VMS`] such VMs (ENOSPC beyond, checked before -//! binding so the slot allocator never blocks). +//! binding so the slot allocator never blocks), shared between processes as the queues are +//! ([`crate::queue_share::Shares`]), since a process may open the device many times. //! //! The [`VmState`] of a VM is shared by the [`Registry`] (while the client's VM handle exists), //! the VM's queues and its jobs. It cannot be owned by the [`mmu::Vm`] itself: the slot binding @@ -151,11 +152,12 @@ pub(crate) struct LiveToken { registry: Arc, bind: Option, file_id: u64, + process: usize, } impl Drop for LiveToken { fn drop(&mut self) { drop(self.bind.take()); - self.registry.release(self.file_id); + self.registry.release(self.file_id, self.process); } } @@ -170,10 +172,13 @@ pub(crate) struct Registry { /// Includes deferred/retained bindings after the file handle closes. #[pin] files: Mutex>, + /// The live VMs counted per creating process; taken under `files`. + #[pin] + processes: Mutex, } /// A reserved place among the live VMs, released unless a [`VmState`] takes it over. -struct Reservation<'a>(Option<&'a Registry>, u64); +struct Reservation<'a>(Option<&'a Registry>, u64, usize); impl Reservation<'_> { fn into_state(mut self) { @@ -184,7 +189,7 @@ impl Reservation<'_> { impl Drop for Reservation<'_> { fn drop(&mut self) { if let Some(registry) = self.0 { - registry.release(self.1); + registry.release(self.1, self.2); } } } @@ -198,6 +203,8 @@ impl Registry { vms <- new_mutex!(vms, "g16::Registry::vms"), live: AtomicU32::new(0), files <- new_mutex!(files, "g16::Registry::files"), + processes <- new_mutex!(crate::queue_share::Shares::new(), + "g16::Registry::processes"), }), GFP_KERNEL, ) @@ -220,29 +227,46 @@ impl Registry { let rollback = kernel::types::ScopeGuard::new(|| { self.live.fetch_sub(1, Ordering::AcqRel); }); - { + let process = { let mut files = self.files.lock(); - if let Some((_, count)) = files.iter_mut().find(|(id, _)| *id == file_id) { - if *count >= MAX_VMS_PER_FILE { + let index = match files.iter().position(|(id, _)| *id == file_id) { + Some(index) if files[index].1 >= MAX_VMS_PER_FILE => return Err(ENOSPC), + Some(index) => index, + None => { + files.push((file_id, 0), GFP_NOWAIT)?; + files.len() - 1 + } + }; + match self.processes.lock().take_current(limit, GFP_NOWAIT) { + Ok(process) => { + files[index].1 += 1; + process + } + Err(_) => { + if files[index].1 == 0 { + let _ = files.remove(index); + } return Err(ENOSPC); } - *count += 1; - } else { - files.push((file_id, 1), GFP_NOWAIT)?; } - } + }; rollback.dismiss(); - Ok(Reservation(Some(self), file_id)) + Ok(Reservation(Some(self), file_id, process)) } - fn release(&self, file_id: u64) { - let mut files = self.files.lock(); - if let Some(index) = files.iter().position(|(id, _)| *id == file_id) { - files[index].1 -= 1; - if files[index].1 == 0 { - let _ = files.remove(index); + fn release(&self, file_id: u64, process: usize) { + let gone = { + let mut files = self.files.lock(); + if let Some(index) = files.iter().position(|(id, _)| *id == file_id) { + files[index].1 -= 1; + if files[index].1 == 0 { + let _ = files.remove(index); + } } - } + self.processes.lock().give_back(process) + }; + // Drops the process's mm reference outside the registry locks. + drop(gone); self.live.fetch_sub(1, Ordering::AcqRel); } @@ -390,6 +414,7 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Resul registry: registry.clone(), bind: Some(bind), file_id, + process: reservation.2, }) .into(); reservation.into_state(); diff --git a/drivers/gpu/drm/asahi/queue_share.rs b/drivers/gpu/drm/asahi/queue_share.rs index 1598ca0195041..f09deb2576ae0 100644 --- a/drivers/gpu/drm/asahi/queue_share.rs +++ b/drivers/gpu/drm/asahi/queue_share.rs @@ -57,6 +57,11 @@ fn may_take(held: u32, total: u32, max: u32) -> bool { /// Counts a new queue against the process `key`; EBUSY when [`may_take`] refuses it. fn take(processes: &mut KVec, key: usize, mm: Option>, max: u32) -> Result { + take_with(processes, key, mm, max, GFP_KERNEL) +} + +fn take_with(processes: &mut KVec, key: usize, mm: Option>, max: u32, + flags: kernel::alloc::Flags) -> Result { let total = processes.iter().map(|process| process.held).sum::(); let index = processes.iter().position(|process| process.key == key); let held = index.map_or(0, |index| processes[index].held); @@ -67,7 +72,7 @@ fn take(processes: &mut KVec, key: usize, mm: Option>, max: u3 Some(index) => processes[index].held += 1, None => { let (tgid, comm) = current_name(); - processes.push(Process { key, _mm: mm, held: 1, tgid, comm }, GFP_KERNEL)? + processes.push(Process { key, _mm: mm, held: 1, tgid, comm }, flags)? } } Ok(()) @@ -114,6 +119,36 @@ fn give_back(processes: &mut KVec, key: usize) -> Option { (processes[index].held == 0).then(|| processes.swap_remove(index)) } +/// The current process's key and an `mm` reference that keeps it from being reused. +fn current_key() -> (usize, Option>) { + let mm = kernel::current!().mm().map(|mm| ARef::from(&**mm)); + (mm.as_ref().map_or(0, |mm| mm.as_raw() as usize), mm) +} + +/// Another device-wide resource shared between processes by the same rule as the queues, +/// under its owner's lock. +pub(crate) struct Shares(KVec); + +impl Shares { + pub(crate) const fn new() -> Self { + Self(KVec::new()) + } + + /// Counts one more of the `max` against the current process and returns its key; EBUSY + /// when [`may_take`] refuses it. + pub(crate) fn take_current(&mut self, max: u32, flags: kernel::alloc::Flags) -> Result { + let (key, mm) = current_key(); + take_with(&mut self.0, key, mm, max, flags)?; + Ok(key) + } + + /// Gives one back of the process `key`; returns the process once it holds none, to drop + /// outside the owner's lock. + pub(crate) fn give_back(&mut self, key: usize) -> Option { + give_back(&mut self.0, key) + } +} + /// One queue counted against the process that created it; dropping it gives the queue back. pub(crate) struct Share { key: usize, @@ -122,8 +157,7 @@ pub(crate) struct Share { impl Share { /// Counts a new queue against the current process, of the device's `max` queues. pub(crate) fn take_current(max: u32) -> Result { - let mm = kernel::current!().mm().map(|mm| ARef::from(&**mm)); - let key = mm.as_ref().map_or(0, |mm| mm.as_raw() as usize); + let (key, mm) = current_key(); take(&mut PROCESSES.lock(), key, mm, max)?; Ok(Self { key }) } diff --git a/tools/asahi/g16-vm-share-tests.py b/tools/asahi/g16-vm-share-tests.py new file mode 100755 index 0000000000000..6e1eb235f7f05 --- /dev/null +++ b/tools/asahi/g16-vm-share-tests.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Compile the G16 VM registry's reservation with host mocks and check how live VMs are shared. + +The production Registry::reserve and Registry::release (g16/vm.rs) and the process share rule +(queue_share.rs) are copied from the tree and built with rustc against mocks of the kernel +mutex, vector, scope guard and current process. A process may open the device many times, so +the live VMs must be shared per process: one process with many files must leave room for the +others, and giving VMs back must make room again. + +--mutations also runs the checks against each mutant below and expects every one to fail: +the registry as it was before the process share, and the share taken but never given back. +""" +import argparse +import os +from pathlib import Path +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +ASAHI = ROOT / '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 before_share(): + """The reservation as it was before VMs were shared per process.""" + return r'''fn reserve(&self, file_id: u64) -> Result> { + self.prune(); + let limit = if module_parameters::robust_isolation.value() != 0 { 1 } else { hw::sizes::MAX_VMS }; + self.live + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |live| { + (live < limit).then_some(live + 1) + }) + .map_err(|_| ENOSPC)?; + let rollback = kernel::types::ScopeGuard::new(|| { + self.live.fetch_sub(1, Ordering::AcqRel); + }); + { + let mut files = self.files.lock(); + if let Some((_, count)) = files.iter_mut().find(|(id, _)| *id == file_id) { + if *count >= MAX_VMS_PER_FILE { + return Err(ENOSPC); + } + *count += 1; + } else { + files.push((file_id, 1), GFP_NOWAIT)?; + } + } + rollback.dismiss(); + Ok(Reservation(Some(self), file_id, 0)) + }''' + + +def fixture(mutation): + vm = (ASAHI / 'g16/vm.rs').read_text() + share = (ASAHI / 'queue_share.rs').read_text() + reserve = item(vm, 'fn reserve(&self, file_id: u64)') + release = item(vm, 'fn release(&self, file_id: u64') + if mutation == 'before-share': + reserve = before_share() + elif mutation == 'never-give-back': + old = 'self.processes.lock().give_back(process)' + if old not in release: + raise RuntimeError('mutation site changed: never-give-back') + release = release.replace(old, 'None::') + per_file = next(line for line in vm.splitlines() if line.startswith('const MAX_VMS_PER_FILE')) + max_vms = next(line.strip() for line in (ASAHI / 'g16/hw.rs').read_text().splitlines() + if 'const MAX_VMS:' in line).replace('pub(crate) ', '') + policy = '\n'.join(item(share, signature) for signature in ( + 'fn reserve(max: u32)', 'fn may_take(', 'fn take_with(', 'fn give_back(processes')) + shares = item(share, 'impl Shares {') + return r''' +#![allow(dead_code, unused_imports, non_upper_case_globals)] +use std::cell::{Cell, RefCell}; +use std::sync::atomic::{AtomicU32, Ordering}; +type Error = i32; +type Result = std::result::Result; +const ENOSPC: Error = -28; +const EBUSY: Error = -16; +const ENOMEM: Error = -12; +#[derive(Clone, Copy)] struct Flags; +const GFP_NOWAIT: Flags = Flags; +const GFP_KERNEL: Flags = Flags; +mod kernel { + pub mod alloc { pub type Flags = super::super::Flags; } + pub mod types { + pub struct ScopeGuard(Option); + impl ScopeGuard { + pub fn new(f: F) -> Self { Self(Some(f)) } + pub fn dismiss(mut self) { self.0 = None; } + } + impl Drop for ScopeGuard { + fn drop(&mut self) { if let Some(f) = self.0.take() { f() } } + } + } +} +struct KVec(Vec); +impl KVec { + const fn new() -> Self { Self(Vec::new()) } + fn push(&mut self, v: T, _: Flags) -> Result { self.0.push(v); Ok(()) } + fn remove(&mut self, i: usize) -> Result { Ok(self.0.remove(i)) } + fn swap_remove(&mut self, i: usize) -> T { self.0.swap_remove(i) } +} +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +struct Mutex(RefCell); +impl Mutex { fn lock(&self) -> std::cell::RefMut<'_, T> { self.0.borrow_mut() } } +struct ARef(T); +struct Mm; +type Pid = i32; +mod module_parameters { + pub struct P; impl P { pub fn value(&self) -> u32 { 0 } } + pub static robust_isolation: P = P; +} +mod hw { pub mod sizes { pub ''' + max_vms + r''' } } +thread_local! { static CURRENT: Cell = Cell::new(1); } +fn current_name() -> (Pid, [u8; 16]) { (CURRENT.with(|c| c.get()) as Pid, [0; 16]) } +fn current_key() -> (usize, Option>) { (CURRENT.with(|c| c.get()), None) } +struct Process { key: usize, _mm: Option>, held: u32, tgid: Pid, comm: [u8; 16] } +pub(crate) struct Shares(KVec); +''' + policy + '\n' + shares + '\n' + per_file + r''' +struct Registry { live: AtomicU32, files: Mutex>, processes: Mutex } +struct Reservation<'a>(Option<&'a Registry>, u64, usize); +impl Drop for Reservation<'_> { + fn drop(&mut self) { if let Some(registry) = self.0 { registry.release(self.1, self.2); } } +} +impl Registry { + fn prune(&self) {} +''' + reserve + '\n' + release + r''' +} + +fn as_process(key: usize) { CURRENT.with(|c| c.set(key)); } + +fn main() { + let max = hw::sizes::MAX_VMS; + let registry = Registry { live: AtomicU32::new(0), files: Mutex(RefCell::new(KVec::new())), + processes: Mutex(RefCell::new(Shares::new())) }; + // A compositor (process 1) holds one VM. + as_process(1); + let compositor = registry.reserve(100).expect("compositor VM"); + // Process 2 opens the device again and again, creating every VM each file allows. + as_process(2); + let mut taken = Vec::new(); + for file in 200..(200 + max as u64) { + let before = taken.len(); + for _ in 0..MAX_VMS_PER_FILE { + match registry.reserve(file) { + Ok(r) => taken.push(r), + Err(e) => { assert_eq!(e, ENOSPC); break; } + } + } + if taken.len() == before { break; } + } + let held = taken.len() as u32; + println!("process 2 holds {} of {} VMs", held, max); + // A process may hold half the device's VMs whatever the others hold. + assert!(held >= max / 2, "a process may hold half the device's VMs"); + // But it leaves room for the others: a newly started process and the compositor get VMs. + as_process(3); + let late = registry.reserve(300).expect("FAIL line 1: a newly started process gets no VM"); + as_process(1); + let second = registry.reserve(100).expect("FAIL line 2: the compositor gets no second VM"); + assert!(registry.live.load(Ordering::Acquire) <= max); + drop(late); + drop(second); + // A VM given back can be created again by the same process. + as_process(2); + drop(taken.pop()); + taken.push(registry.reserve(9999).expect("FAIL line 3: a given back VM cannot be created again")); + drop(taken); + drop(compositor); + // Everything given back: one process alone may use every VM. + as_process(4); + let mut all = Vec::new(); + for file in 0..(max as u64 + 8) { + for _ in 0..MAX_VMS_PER_FILE { + if let Ok(r) = registry.reserve(1000 + file) { all.push(r) } + } + } + assert_eq!(all.len() as u32, max, "FAIL line 4: a process alone cannot use every VM"); + drop(all); + assert_eq!(registry.live.load(Ordering::Acquire), 0); + assert!(registry.processes.lock().0.is_empty(), "FAIL line 5: a process share outlives its VMs"); + println!("ok"); +} +''' + + +def run(mutation, work): + src = Path(work) / f'{mutation or "control"}.rs' + exe = Path(work) / f'{mutation or "control"}' + src.write_text(fixture(mutation)) + build = subprocess.run(['rustc', '--edition=2021', '-O', '-C', 'overflow-checks=on', + '-o', str(exe), str(src)], capture_output=True, text=True) + if build.returncode: + raise RuntimeError(f'{mutation or "control"} does not compile:\n{build.stderr}') + result = subprocess.run([str(exe)], capture_output=True, text=True, timeout=60) + return result.returncode, result.stdout + result.stderr + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--mutations', action='store_true') + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='g16-vm-share-') as work: + code, output = run(None, work) + print(output.strip()) + if code: + print('FAIL control') + return 1 + print('PASS control') + if not args.mutations: + return 0 + killed = 0 + names = ('before-share', 'never-give-back') + for name in names: + code, output = run(name, work) + if code and 'panicked at' in output: + killed += 1 + print(f'KILLED {name}: ' + next(line for line in output.splitlines() if 'panicked' in line or 'FAIL' in line)) + else: + print(f'SURVIVED {name}:\n{output}') + print(f'{killed}/{len(names)} mutants killed') + return 0 if killed == len(names) else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290..d7bc94e20404c 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -206,6 +206,7 @@ def mutations(flag, names, base, expect=KILL): 'g15-retention-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], + 'g16-vm-share-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery', 'quarantine', 'epoch', 'cutoff', 'whole-batch', 'legacy-format', 'read-drain'), out()), From 4915f4b23ac42feaa7065fb6dc1493c7e2cf0117 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:40:09 +1100 Subject: [PATCH 2/4] drm/asahi: g16: charge a VM's private arenas to its client A G16 VM's first render or compute submission builds its private arena (the two PB heaps, TPC, tilemap, pools and slot storage: about 0.7 GiB for a rendering VM) from kernel objects. They were counted only in the device's kernel total, never against the client, so neither the per-client limit nor fdinfo saw them. Hand the client's memory accounting to the backend when the VM is created (new_vm_for_file() gets the file's memacct client) and set it on the VM before the registry and the arenas see it. Private objects of a client VM are then admitted against that client's limit (ENOMEM past it, failing the submission that needed the arena) and held as its user memory instead of kernel memory, so they are counted once. The session's own objects and VMs without a client are unchanged. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/file.rs | 2 +- drivers/gpu/drm/asahi/g16/mod.rs | 11 ++++++++--- drivers/gpu/drm/asahi/g16/object.rs | 24 +++++++++++++++++++++++- drivers/gpu/drm/asahi/g16/vm.rs | 14 ++++++++++++-- drivers/gpu/drm/asahi/gpu.rs | 10 ++++++++-- 5 files changed, 52 insertions(+), 9 deletions(-) diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index b69834163d5b9..1073c7d18d90e 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -709,7 +709,7 @@ impl File { let gpu = ®_data.gpu; let file_id = file.inner().id; let vm = gpu - .new_vm_for_file(kernel_range.clone(), file_id)? + .new_vm_for_file(kernel_range.clone(), file_id, &file.inner().mem)? .with_memory_client(file.inner().mem.clone()); // G16 registers a retained backend owner before returning this VM. Any later // allocation can fail before file::Vm exists to run its normal close path. diff --git a/drivers/gpu/drm/asahi/g16/mod.rs b/drivers/gpu/drm/asahi/g16/mod.rs index f161b218a0d06..9b865aa0b1446 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -617,10 +617,15 @@ impl gpu::Gpu for Gpu { } fn new_vm(&self, kernel_range: Range) -> Result { - vm::new_vm(self, kernel_range, 0) + vm::new_vm(self, kernel_range, 0, None) } - fn new_vm_for_file(&self, kernel_range: Range, file_id: u64) -> Result { - vm::new_vm(self, kernel_range, file_id) + fn new_vm_for_file( + &self, + kernel_range: Range, + file_id: u64, + memory: &Arc, + ) -> Result { + vm::new_vm(self, kernel_range, file_id, Some(memory.clone())) } fn vm_closed(&self, vm: &mmu::Vm) { let registry = self diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index 0f26cb3276738..d083a4b204402 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -314,6 +314,7 @@ impl Factory { mappings: KVec::new(), error: None, pages: 0, + charges: KVec::new(), } } } @@ -340,6 +341,8 @@ pub(crate) struct Objects { error: Option, /// Host-window pages backed by objects. pages: usize, + /// The charges of private objects sized by the VM's client, held as long as their backing. + charges: KVec, } impl Objects { @@ -360,6 +363,7 @@ impl Objects { mappings: KVec::new(), error: None, pages: 0, + charges: KVec::new(), }) } @@ -417,7 +421,25 @@ impl Objects { & !(hw::PAGE as usize - 1); self.retained.reserve(1, GFP_KERNEL)?; self.mappings.reserve(3, GFP_KERNEL)?; - let mut backing = gem::new_kernel_object_wc(&self.dev, bytes)?; + // A client VM's arena is client memory: admitted against, and counted for, its client + // instead of the device's kernel total. + let charge = match private.vm.memory_client() { + Some(client) => { + self.charges.reserve(1, GFP_KERNEL)?; + let commit = crate::memacct::LEDGER.admit(client, bytes as u64)?; + Some(crate::memacct::Charge::user(commit, None)) + } + None => None, + }; + let mut backing = if charge.is_some() { + gem::new_kernel_object_wc_user_charged(&self.dev, bytes)? + } else { + gem::new_kernel_object_wc(&self.dev, bytes)? + }; + if let Some(charge) = charge { + charge.set_held(true); + self.charges.push(charge, GFP_KERNEL)?; + } let registered = self.dev.registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); gem::prepare_new_object(&backing.gem, parent.as_ref())?; diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 2ea9bfdbdb7f5..3070c2113a3d7 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -372,7 +372,14 @@ pub(crate) fn reserved_ranges() -> [Range; 2] { } /// Creates a user VM (`gpu::Gpu::new_vm`). -pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Result { +/// +/// Kernel memory sized by the VM's client (its private arenas) is charged to `memory`. +pub(crate) fn new_vm( + gpu: &Gpu, + kernel_range: Range, + file_id: u64, + memory: Option>, +) -> Result { if gpu.shared.crashed.load(Ordering::Acquire) { return Err(EIO); } @@ -387,10 +394,13 @@ pub(crate) fn new_vm(gpu: &Gpu, kernel_range: Range, file_id: u64) -> Resul }; let reservation = registry.reserve(file_id)?; let id = gpu.ids.vm.next(); - let vm = gpu + let mut vm = gpu .uat .new_vm(id, kernel_range.clone())? .with_tracked_status()?; + if let Some(memory) = memory { + vm = vm.with_memory_client(memory); + } // Driver mappings retain their VM. Break that ownership if any later step fails, // including binding/state allocation and registry insertion. let failed_vm = kernel::types::ScopeGuard::new_with_data(vm.clone(), |vm| { diff --git a/drivers/gpu/drm/asahi/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index 4817bed0c2078..d37378a2d420f 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -448,8 +448,14 @@ pub(crate) trait Gpu: Send + Sync { } /// Create a new `Vm` with the given range reserved for kernel-managed objects. fn new_vm(&self, kernel_range: Range) -> Result; - /// Create a VM charged to a DRM file when the backend bounds retained bindings. - fn new_vm_for_file(&self, kernel_range: Range, _file_id: u64) -> Result { + /// Create a VM charged to a DRM file when the backend bounds retained bindings; kernel + /// memory the backend sizes by the VM's client is charged to `_memory`. + fn new_vm_for_file( + &self, + kernel_range: Range, + _file_id: u64, + _memory: &Arc, + ) -> Result { self.new_vm(kernel_range) } /// Release the backend's handle owner after closing user mapping admission. From 15334152440a6c8547d6f2c4592e00c86eed7d39 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 16:54:43 +1100 Subject: [PATCH 3/4] drm/asahi: g16: keep VM slots for later clients and charge arenas once they live Review follow-up. The live-VM share took the queues' rule, which lets a process alone take every slot. Queues come and go, but a G16 VM keeps its TTBAT slot until it is closed, so one client started before the compositor could hold all 63 and leave none for anything started later. VMs now take may_take_held(): a process alone still leaves the reserve (7 of 63) for the others. Queues keep their rule. The arena charge was marked held and pushed before the fallible steps (registration_guard(), prepare_new_object(), vmap(), the mappings). If one failed on a container that lives on, the backing was freed and the charge stayed held. Hold and push it once the object is retained. A refused share is ENOSPC, as before; an allocation failure under the registry lock now stays ENOMEM instead of reading as ENOSPC. Update the host tests: test-vm-registry.py for the new Registry, Reservation and release() signatures (CI was red), with the VM share by queue_share.rs's own rule and a case for the reserve a lone process leaves; g16-vm-share-tests.py for the same, with a mutant for the old rule. Both pass; all three mutants fail. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g16/object.rs | 11 ++-- drivers/gpu/drm/asahi/g16/vm.rs | 5 +- drivers/gpu/drm/asahi/queue_share.rs | 45 ++++++++++++--- tools/asahi/g16-vm-share-tests.py | 24 ++++++-- .../drivers/gpu/asahi-m4/test-vm-registry.py | 55 ++++++++++++++++--- 5 files changed, 114 insertions(+), 26 deletions(-) diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index d083a4b204402..3708309511857 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -436,10 +436,6 @@ impl Objects { } else { gem::new_kernel_object_wc(&self.dev, bytes)? }; - if let Some(charge) = charge { - charge.set_held(true); - self.charges.push(charge, GFP_KERNEL)?; - } let registered = self.dev.registration_guard().ok_or(ENODEV)?; let parent: &kernel::platform::Device = registered.as_ref(); gem::prepare_new_object(&backing.gem, parent.as_ref())?; @@ -535,6 +531,13 @@ impl Objects { GFP_KERNEL, )?; self.retained.push(object.clone(), GFP_KERNEL)?; + // Held only once nothing can fail any more: an earlier error frees the backing, and a + // held charge left behind in a container that lives on would count memory that is gone. + // `charges` has room reserved, so this push does not allocate. + if let Some(charge) = charge { + charge.set_held(true); + self.charges.push(charge, GFP_KERNEL)?; + } self.pages += bytes / hw::PAGE as usize; Ok(object) } diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 3070c2113a3d7..d45a3c6392e98 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -242,11 +242,12 @@ impl Registry { files[index].1 += 1; process } - Err(_) => { + Err(error) => { if files[index].1 == 0 { let _ = files.remove(index); } - return Err(ENOSPC); + // The share refusing is "no room"; a failed allocation stays ENOMEM. + return Err(if error == EBUSY { ENOSPC } else { error }); } } }; diff --git a/drivers/gpu/drm/asahi/queue_share.rs b/drivers/gpu/drm/asahi/queue_share.rs index f09deb2576ae0..a914285100055 100644 --- a/drivers/gpu/drm/asahi/queue_share.rs +++ b/drivers/gpu/drm/asahi/queue_share.rs @@ -55,17 +55,24 @@ fn may_take(held: u32, total: u32, max: u32) -> bool { held < max / 2 || held == total || max.saturating_sub(total.saturating_add(1)) >= reserve(max) } +/// [`may_take`] for a resource a process keeps until it closes it (a G16 VM's TTBAT slot): +/// even a process alone leaves [`reserve`] free, or one client started before the compositor +/// would hold every slot until it exits. +fn may_take_held(held: u32, total: u32, max: u32) -> bool { + held < max / 2 || max.saturating_sub(total.saturating_add(1)) >= reserve(max) +} + /// Counts a new queue against the process `key`; EBUSY when [`may_take`] refuses it. fn take(processes: &mut KVec, key: usize, mm: Option>, max: u32) -> Result { - take_with(processes, key, mm, max, GFP_KERNEL) + take_with(processes, key, mm, max, GFP_KERNEL, may_take) } fn take_with(processes: &mut KVec, key: usize, mm: Option>, max: u32, - flags: kernel::alloc::Flags) -> Result { + flags: kernel::alloc::Flags, allowed: fn(u32, u32, u32) -> bool) -> Result { let total = processes.iter().map(|process| process.held).sum::(); let index = processes.iter().position(|process| process.key == key); let held = index.map_or(0, |index| processes[index].held); - if !may_take(held, total, max) { + if !allowed(held, total, max) { return Err(EBUSY); } match index { @@ -125,8 +132,8 @@ fn current_key() -> (usize, Option>) { (mm.as_ref().map_or(0, |mm| mm.as_raw() as usize), mm) } -/// Another device-wide resource shared between processes by the same rule as the queues, -/// under its owner's lock. +/// Another device-wide resource shared between processes, under its owner's lock: by the +/// queues' rule, except that a process alone also leaves the reserve ([`may_take_held`]). pub(crate) struct Shares(KVec); impl Shares { @@ -135,10 +142,10 @@ impl Shares { } /// Counts one more of the `max` against the current process and returns its key; EBUSY - /// when [`may_take`] refuses it. + /// when [`may_take_held`] refuses it. pub(crate) fn take_current(&mut self, max: u32, flags: kernel::alloc::Flags) -> Result { let (key, mm) = current_key(); - take_with(&mut self.0, key, mm, max, flags)?; + take_with(&mut self.0, key, mm, max, flags, may_take_held)?; Ok(key) } @@ -194,6 +201,30 @@ mod tests { assert!(may_take(28, 57, 58)); } + #[test] + fn a_lone_vm_holder_still_leaves_the_reserve() -> Result { + // 63 G16 VM slots keep 7 free. A process alone stops at 56: the compositor started + // after it still gets a slot. + assert_eq!(reserve(63), 7); + assert!(may_take_held(55, 55, 63)); + assert!(!may_take_held(56, 56, 63)); + // Below half its share a process may still take from the reserve. + assert!(may_take_held(3, 60, 63)); + let mut processes = KVec::new(); + for _ in 0..56 { + take_with(&mut processes, 1, None, 63, GFP_KERNEL, may_take_held)?; + } + assert_eq!( + take_with(&mut processes, 1, None, 63, GFP_KERNEL, may_take_held), + Err(EBUSY) + ); + // A second process (the compositor) gets one of the slots that were held back. + take_with(&mut processes, 2, None, 63, GFP_KERNEL, may_take_held)?; + // The same lone process may take every queue: queues are not held until close. + assert!(may_take(56, 56, 63)); + Ok(()) + } + #[test] fn a_lone_process_with_two_files_reaches_the_full_budget() -> Result { let mut processes = KVec::new(); diff --git a/tools/asahi/g16-vm-share-tests.py b/tools/asahi/g16-vm-share-tests.py index 6e1eb235f7f05..4e82135f52c24 100755 --- a/tools/asahi/g16-vm-share-tests.py +++ b/tools/asahi/g16-vm-share-tests.py @@ -9,7 +9,8 @@ others, and giving VMs back must make room again. --mutations also runs the checks against each mutant below and expects every one to fail: -the registry as it was before the process share, and the share taken but never given back. +the registry as it was before the process share, the share taken but never given back, and a +process alone allowed to take every VM slot (the reserve it must leave for later clients). """ import argparse import os @@ -67,6 +68,8 @@ def fixture(mutation): release = item(vm, 'fn release(&self, file_id: u64') if mutation == 'before-share': reserve = before_share() + elif mutation == 'lone-takes-all': + pass elif mutation == 'never-give-back': old = 'self.processes.lock().give_back(process)' if old not in release: @@ -76,7 +79,13 @@ def fixture(mutation): max_vms = next(line.strip() for line in (ASAHI / 'g16/hw.rs').read_text().splitlines() if 'const MAX_VMS:' in line).replace('pub(crate) ', '') policy = '\n'.join(item(share, signature) for signature in ( - 'fn reserve(max: u32)', 'fn may_take(', 'fn take_with(', 'fn give_back(processes')) + 'fn reserve(max: u32)', 'fn may_take(', 'fn may_take_held(', 'fn take_with(', + 'fn give_back(processes')) + if mutation == 'lone-takes-all': + old = 'held < max / 2 || max.saturating_sub' + if old not in policy: + raise RuntimeError('mutation site changed: lone-takes-all') + policy = policy.replace(old, 'held < max / 2 || held == total || max.saturating_sub', 1) shares = item(share, 'impl Shares {') return r''' #![allow(dead_code, unused_imports, non_upper_case_globals)] @@ -178,7 +187,8 @@ def fixture(mutation): taken.push(registry.reserve(9999).expect("FAIL line 3: a given back VM cannot be created again")); drop(taken); drop(compositor); - // Everything given back: one process alone may use every VM. + // Everything given back: a process alone still leaves the reserve, since a VM keeps its + // slot until it is closed, and a process started after it gets a VM. as_process(4); let mut all = Vec::new(); for file in 0..(max as u64 + 8) { @@ -186,7 +196,11 @@ def fixture(mutation): if let Ok(r) = registry.reserve(1000 + file) { all.push(r) } } } - assert_eq!(all.len() as u32, max, "FAIL line 4: a process alone cannot use every VM"); + assert_eq!(all.len() as u32, max - reserve(max), + "FAIL line 4: a process alone takes the reserve (or less than the rest)"); + as_process(5); + let after = registry.reserve(5000).expect("FAIL line 6: a process started later gets no VM"); + drop(after); drop(all); assert_eq!(registry.live.load(Ordering::Acquire), 0); assert!(registry.processes.lock().0.is_empty(), "FAIL line 5: a process share outlives its VMs"); @@ -221,7 +235,7 @@ def main(): if not args.mutations: return 0 killed = 0 - names = ('before-share', 'never-give-back') + names = ('before-share', 'never-give-back', 'lone-takes-all') for name in names: code, output = run(name, work) if code and 'panicked at' in output: diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py index add96b48bb335..12b9cadd6aacb 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-registry.py @@ -6,10 +6,12 @@ from pathlib import Path import subprocess root=kernel_root();out=output_dir();s=(root/'drivers/gpu/drm/asahi/g16/vm.rs').read_text() -def item(marker): - a=s.index(marker);b=s.index('{',a);i=b+1;n=1 - while n:n+=(s[i]=='{')-(s[i]=='}');i+=1 - return s[a:i] +qs=(root/'drivers/gpu/drm/asahi/queue_share.rs').read_text() +def item(marker,text=None): + text=s if text is None else text + a=text.index(marker);b=text.index('{',a);i=b+1;n=1 + while n:n+=(text[i]=='{')-(text[i]=='}');i+=1 + return text[a:i] source=r''' #![allow(dead_code,unused_variables,non_upper_case_globals)] extern crate self as kernel; @@ -22,17 +24,42 @@ def item(marker): mod hw{pub mod sizes{pub const MAX_VMS:u32=63;}} mod module_parameters{pub struct Param;impl Param{pub fn value(&self)->u32{0}}pub static robust_isolation:Param=Param;} mod types{pub struct ScopeGuard(Option);implScopeGuard{pub fn new(f:F)->Self{Self(Some(f))}pub fn dismiss(mut self){self.0.take();}}implDrop for ScopeGuard{fn drop(&mut self){if let Some(f)=self.0.take(){f()}}}} +const EBUSY:u32=16; +// The VM share, by queue_share.rs's own rule; the current process is set per test. +mod queue_share{ + use super::*; + thread_local!{pub static CURRENT:std::cell::Cell=std::cell::Cell::new(1);} + __QS_RESERVE__ + __QS_MAY_TAKE_HELD__ + pub struct Shares(Vec<(usize,u32)>); + impl Shares{ + pub const fn new()->Self{Self(Vec::new())} + pub fn take_current(&mut self,max:u32,_f:u32)->Result{ + let key=CURRENT.with(|c|c.get());let total=self.0.iter().map(|p|p.1).sum::(); + let held=self.0.iter().find(|p|p.0==key).map_or(0,|p|p.1); + if !may_take_held(held,total,max){return Err(EBUSY);} + match self.0.iter_mut().find(|p|p.0==key){Some(p)=>p.1+=1,None=>self.0.push((key,1))} + Ok(key) + } + pub fn give_back(&mut self,key:usize)->Option{ + let i=self.0.iter().position(|p|p.0==key)?;self.0[i].1-=1; + (self.0[i].1==0).then(||self.0.swap_remove(i).0) + } + pub fn held(&self)->u32{self.0.iter().map(|p|p.1).sum()} + } +} +fn as_process(key:usize){queue_share::CURRENT.with(|c|c.set(key));} struct Handle;impl Handle{fn is_closed(&self)->bool{false}} struct VmState{id:u64,vm:Handle,drops:Arc}impl Drop for VmState{fn drop(&mut self){self.drops.fetch_add(1,Ordering::AcqRel);}} __REGISTRY__ -struct Reservation<'a>(Option<&'a Registry>,u64); +struct Reservation<'a>(Option<&'a Registry>,u64,usize); __RESERVATION_DROP__ impl Registry{ __RESERVE__ __RELEASE__ __CLOSE__ __PRUNE__ - fn new_test()->Self{Self{live:AtomicU32::new(0),vms:Mutex(StdMutex::new(KVec(Vec::with_capacity(63)))),files:Mutex(StdMutex::new(KVec(Vec::with_capacity(63))))}} + fn new_test()->Self{Self{live:AtomicU32::new(0),vms:Mutex(StdMutex::new(KVec(Vec::with_capacity(63)))),files:Mutex(StdMutex::new(KVec(Vec::with_capacity(63)))),processes:Mutex(StdMutex::new(queue_share::Shares::new()))}} } #[test]fn pending_and_live_file_quota_returns_only_on_release(){ let r=Registry::new_test();let mut owners:Vec<_>=(0..8).map(|_|r.reserve(7).unwrap()).collect(); @@ -41,8 +68,19 @@ def item(marker): drop((owners,other));assert_eq!(r.live.load(Ordering::Acquire),0);assert!(r.files.lock().is_empty()); } #[test]fn device_quota_is_still_bounded_across_files(){ - let r=Registry::new_test();let owners:Vec<_>=(0..63).map(|n|r.reserve(n/8).unwrap()).collect(); - assert!(matches!(r.reserve(100),Err(ENOSPC)));drop(owners);assert_eq!(r.live.load(Ordering::Acquire),0); + // Eight processes, one file each: the device limit still holds across them. + let r=Registry::new_test();let owners:Vec<_>=(0..63u64).map(|n|{as_process((n/8+1) as usize);r.reserve(n/8).unwrap()}).collect(); + as_process(100);assert!(matches!(r.reserve(100),Err(ENOSPC)));drop(owners);assert_eq!(r.live.load(Ordering::Acquire),0); + assert_eq!(r.processes.lock().held(),0); +} +#[test]fn a_process_alone_leaves_vm_slots_for_the_compositor(){ + // One process across eight files stops at 56 of 63; another process still gets a slot. + let r=Registry::new_test();as_process(1); + let owners:Vec<_>=(0..56).map(|n|r.reserve(n/7).unwrap()).collect(); + assert!(matches!(r.reserve(9),Err(ENOSPC)));assert!(r.files.lock().iter().all(|(id,_)|*id!=9)); + as_process(2);let compositor=r.reserve(50).unwrap(); + drop(owners);drop(compositor);assert_eq!(r.live.load(Ordering::Acquire),0); + assert!(r.files.lock().is_empty());assert_eq!(r.processes.lock().held(),0); } #[test]fn close_releases_registry_owner_without_another_vm_create(){ let r=Registry::new_test();let drops=Arc::new(AtomicU32::new(0)); @@ -55,6 +93,7 @@ def item(marker): ''' for tag,marker in [('REGISTRY','pub(crate) struct Registry'),('RESERVATION_DROP',"impl Drop for Reservation<'_>"),('RESERVE','fn reserve(&self, file_id:'),('RELEASE','fn release(&self, file_id:'),('CLOSE','pub(crate) fn close(&self, id:'),('PRUNE','fn prune(&self)')]: source=source.replace('__'+tag+'__',item(marker).replace(' #[pin]\n','')) +source=source.replace('__QS_RESERVE__','pub '+item('fn reserve(max: u32)',qs)).replace('__QS_MAY_TAKE_HELD__','pub '+item('fn may_take_held(',qs)) source=source.replace('struct Reservation<',s[s.index('const MAX_VMS_PER_FILE:'):s.index(';',s.index('const MAX_VMS_PER_FILE:'))+1]+'\nstruct Reservation<',1) p=out/'registry.rs';p.write_text(source) subprocess.run(rustc()+['--edition=2021','--test',str(p),'-o',str(out/'registry')],check=True) From 2606f52b8c95ed596f74d26676fd100fb15a407e Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Fri, 27 Nov 2026 19:02:55 +1100 Subject: [PATCH 4/4] selftests: asahi-m4: build LiveToken with its process owner The main merge brought test-resources.py fixtures that build the production LiveToken from vm.rs. With this branch the token carries the creating process and Registry::release() takes it, so the fixtures no longer compiled (E0063/E0061, asahi-m4 host test red). Give the mock tokens process 0 and the mock Registry::release() the process argument. Signed-off-by: Ryan Murray --- .../selftests/drivers/gpu/asahi-m4/test-resources.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py index cb84603adc556..6f0e1a35efe8b 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -235,7 +235,7 @@ def module(text, name): let released = std::sync::Arc::new(AtomicBool::new(false)); let registry = Arc::new(Registry { live: live.clone() }, 0).unwrap(); let bind = mmu::VmBind { live, released: released.clone() }; - let token = Arc::new(LiveToken { registry, bind: Some(bind), file_id: 0 }, 0).unwrap(); + let token = Arc::new(LiveToken { registry, bind: Some(bind), file_id: 0, process: 0 }, 0).unwrap(); (Self { cache: Some(cache), _live: Some(token), ..Self::new() }, released) } pub fn is_closed(&self)->bool{self.closed.load(Ordering::Acquire)} @@ -250,14 +250,14 @@ def module(text, name): || self.vm.cache.as_ref().is_some_and(|cache| cache.renders_unpublished()) } } - struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64){self.live.fetch_sub(1,Ordering::AcqRel);}} + struct Registry{live:std::sync::Arc}impl Registry{fn release(&self,_file:u64,_process:usize){self.live.fetch_sub(1,Ordering::AcqRel);}} __LIVE_TOKEN__ __LIVE_DROP__ #[test]fn accounting_outlives_deferred_arenas_and_releases_binding_first(){ use std::sync::atomic::{AtomicU32,AtomicBool}; let count=std::sync::Arc::new(AtomicU32::new(1));let released=std::sync::Arc::new(AtomicBool::new(false)); let registry=Arc::new(Registry{live:count.clone()},0).unwrap(); - let token=Arc::new(LiveToken{registry,file_id:0,bind:Some(mmu::VmBind{live:count.clone(),released:released.clone()})},0).unwrap(); + let token=Arc::new(LiveToken{registry,file_id:0,process:0,bind:Some(mmu::VmBind{live:count.clone(),released:released.clone()})},0).unwrap(); let deferred_arena=token.clone();drop(token); assert_eq!(count.load(Ordering::Acquire),1);assert!(!released.load(Ordering::Acquire)); drop(deferred_arena);assert!(released.load(Ordering::Acquire));assert_eq!(count.load(Ordering::Acquire),0);