diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index fc2d2dd6cedaf..9ff6a68c66510 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -793,7 +793,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 61aa199f8cb16..aa64abe0556f9 100644 --- a/drivers/gpu/drm/asahi/g16/mod.rs +++ b/drivers/gpu/drm/asahi/g16/mod.rs @@ -913,10 +913,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) { self.vms.close(vm.id()); diff --git a/drivers/gpu/drm/asahi/g16/object.rs b/drivers/gpu/drm/asahi/g16/object.rs index cda6f6617e279..887d40ad1c1d6 100644 --- a/drivers/gpu/drm/asahi/g16/object.rs +++ b/drivers/gpu/drm/asahi/g16/object.rs @@ -418,6 +418,7 @@ impl Factory { mappings: KVec::new(), error: None, pages: 0, + charges: KVec::new(), } } @@ -441,6 +442,7 @@ impl Factory { mappings: KVec::new(), error: None, pages: 0, + charges: KVec::new(), } } @@ -466,6 +468,7 @@ impl Factory { mappings: KVec::new(), error: None, pages: 0, + charges: KVec::new(), } } @@ -517,6 +520,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 { @@ -539,6 +544,7 @@ impl Objects { mappings: KVec::new(), error: None, pages: 0, + charges: KVec::new(), }) } @@ -628,8 +634,25 @@ impl Objects { // A firmware-cached record needs a cacheable host view of the same pages (the host and // firmware caches are coherent, as for G13-G15 private objects); every other private // class keeps its write-combined view. + // A client VM's arena is client memory: admitted against, and counted for, its client + // instead of the device's kernel total. + let client = self + .private + .as_ref() + .and_then(|private| private.vm.as_ref()) + .and_then(|vm| vm.memory_client()); + let charge = match 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 req.class == Class::FwCoherent { gem::new_kernel_object(&self.dev, bytes)? + } else if charge.is_some() { + gem::new_kernel_object_wc_user_charged(&self.dev, bytes)? } else { gem::new_kernel_object_wc(&self.dev, bytes)? }; @@ -743,6 +766,13 @@ impl Objects { cached_cpu, })); let _ = self.retained.push_within_capacity(object.clone()); + // 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; a charge that could not be kept uncharges on drop. + if let Some(charge) = charge { + charge.set_held(true); + let _ = self.charges.push_within_capacity(charge); + } 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 b7a76ee776ec4..0b10ee619b09d 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 @@ -174,11 +175,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); } } @@ -193,10 +195,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) { @@ -207,7 +212,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); } } } @@ -221,6 +226,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, ) @@ -243,29 +250,47 @@ 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 { - return Err(ENOSPC); + 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(error) => { + if files[index].1 == 0 { + let _ = files.remove(index); + } + // The share refusing is "no room"; a failed allocation stays ENOMEM. + return Err(if error == EBUSY { ENOSPC } else { error }); } - *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); } @@ -389,7 +414,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); } @@ -404,10 +436,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| { @@ -431,6 +466,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/gpu.rs b/drivers/gpu/drm/asahi/gpu.rs index fb5359137b668..e1420ad69c031 100644 --- a/drivers/gpu/drm/asahi/gpu.rs +++ b/drivers/gpu/drm/asahi/gpu.rs @@ -508,8 +508,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. diff --git a/drivers/gpu/drm/asahi/queue_share.rs b/drivers/gpu/drm/asahi/queue_share.rs index 1598ca0195041..a914285100055 100644 --- a/drivers/gpu/drm/asahi/queue_share.rs +++ b/drivers/gpu/drm/asahi/queue_share.rs @@ -55,19 +55,31 @@ 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, may_take) +} + +fn take_with(processes: &mut KVec, key: usize, mm: Option>, max: u32, + 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 { 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 +126,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, 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 { + 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_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, may_take_held)?; + 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 +164,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 }) } @@ -160,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 new file mode 100755 index 0000000000000..4e82135f52c24 --- /dev/null +++ b/tools/asahi/g16-vm-share-tests.py @@ -0,0 +1,251 @@ +#!/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, 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 +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 == 'lone-takes-all': + pass + 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 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)] +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: 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) { + 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 - 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"); + 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', 'lone-takes-all') + 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 a20d283737988..c154a59ebdab4 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -260,6 +260,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)], 'g18-client-handoff-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g18-job-error-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 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); 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 96d3238471635..bd42929f117a4 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,18 +24,43 @@ 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(std::sync::atomic::AtomicBool);impl Handle{fn open()->Self{Self(std::sync::atomic::AtomicBool::new(false))}fn mark_closed(&self){self.0.store(true,Ordering::Release);}fn is_closed(&self)->bool{self.0.load(Ordering::Acquire)}} struct Cache{closes:AtomicU32,spares:StdMutex>>}impl Cache{fn new()->Self{Self{closes:AtomicU32::new(0),spares:StdMutex::new(Vec::new())}}fn close(&self){self.closes.fetch_add(1,Ordering::AcqRel);let spares=std::mem::take(&mut *self.spares.lock().unwrap());drop(spares);}} struct VmState{id:u64,vm:Handle,drops:Arc,resources:Option>}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(); @@ -42,8 +69,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)); @@ -72,6 +110,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)