diff --git a/drivers/gpu/drm/asahi/g16/vm.rs b/drivers/gpu/drm/asahi/g16/vm.rs index 9546f47c30045..04fbe1d15164f 100644 --- a/drivers/gpu/drm/asahi/g16/vm.rs +++ b/drivers/gpu/drm/asahi/g16/vm.rs @@ -10,11 +10,18 @@ //! ([`object::Objects::clients`]) as driver mappings at their fixed GVAs, and reserve //! [`super::hw::client::CLIENT_APERTURE`], the pass-slot range and the PB page list //! (`vm.install_driver_mappings`): user binds there fail (EINVAL); +//! - keep it unbound ([`IdleVm`]) until its client creates a queue. +//! +//! With the VM's first queue ([`lookup`]): +//! //! - 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), shared between processes as the queues are //! ([`crate::queue_share::Shares`]), since a process may open the device many times. //! +//! Only a queue's jobs run in a VM's context, so a VM without one needs no slot: a Vulkan +//! client opens one such VM for its physical device beside the VM its logical device uses. +//! //! 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 //! holds a `Vm` reference. The registry drops its reference once the shared lifetime reports the @@ -34,6 +41,7 @@ use kernel::{ drm::gem::BaseObject, new_mutex, prelude::*, + rbtree::{RBTree, RBTreeNode}, sync::{aref::ARef, Arc, Mutex, UniqueArc}, }; @@ -133,7 +141,7 @@ pub(crate) struct VmStateInner { /// The VM: span checks, stream reads and job guards. pub(crate) vm: mmu::Vm, /// Private mappings are kept outside generic close's user GPUVA teardown. - context_mappings: KVec, + context_mappings: Option>>, pub(crate) resources: Option>, #[allow(dead_code)] pub(crate) live: Arc, @@ -152,33 +160,61 @@ impl Drop for VmStateInner { fn drop(&mut self) { mod_pr_debug!("G16: VM {} releases context {}\n", self.id, self.slot); drop(self.resources.take()); - self.context_mappings.clear(); + drop(self.context_mappings.take()); } } -/// Count a VM until every deferred arena has unmapped and released its binding. +/// Count a bound VM until every deferred arena has unmapped and released its binding. pub(crate) struct LiveToken { registry: Arc, bind: Option, - file_id: u64, + _place: Arc, process: usize, } impl Drop for LiveToken { fn drop(&mut self) { drop(self.bind.take()); - self.registry.release(self.file_id, self.process); + self.registry.release(self.process); + } +} + +/// One of its file's VMs, counted until the VM is closed and, if it was bound, every deferred +/// arena has unmapped. +pub(crate) struct FilePlace { + registry: Arc, + file_id: u64, +} +impl Drop for FilePlace { + fn drop(&mut self) { + self.registry.leave(self.file_id); } } -/// Live-VM accounting and the VMs whose client handle is open. +/// A VM whose client has created no queue yet. Nothing runs in its context, so it holds no TTBAT +/// slot; [`lookup`] binds it for its first queue. +struct IdleVm { + vm: mmu::Vm, + status: Arc, + mappings: Arc>, + place: Arc, +} + +/// VM accounting and the VMs whose client handle is open. #[pin_data] pub(crate) struct Registry { - /// VMs whose client handle may still be open, oldest first. + /// Bound VMs whose client handle may still be open, oldest first. #[pin] vms: Mutex>>, + /// VMs without a queue, by identifier. Its nodes are allocated before taking the lock, + /// which `fail_all()` takes under the device lock. + #[pin] + idle: Mutex>, + /// Serializes the binding of VMs ([`lookup`]): a VM is bound once. + #[pin] + binding: Mutex<()>, /// Live [`VmState`]s (each holds a TTBAT slot) plus reservations being created. live: AtomicU32, - /// Includes deferred/retained bindings after the file handle closes. + /// The VMs of each file. Includes deferred/retained bindings after the file handle closes. #[pin] files: Mutex>, /// The live VMs counted per creating process; taken under `files`. @@ -186,8 +222,8 @@ pub(crate) struct Registry { processes: Mutex, } -/// A reserved place among the live VMs, released unless a [`VmState`] takes it over. -struct Reservation<'a>(Option<&'a Registry>, u64, usize); +/// A reserved TTBAT slot among the live VMs, released unless a [`VmState`] takes it over. +struct Reservation<'a>(Option<&'a Registry>, usize); impl Reservation<'_> { fn into_state(mut self) { @@ -198,7 +234,7 @@ impl Reservation<'_> { impl Drop for Reservation<'_> { fn drop(&mut self) { if let Some(registry) = self.0 { - registry.release(self.1, self.2); + registry.release(self.1); } } } @@ -210,6 +246,8 @@ impl Registry { Arc::pin_init( pin_init!(Self { vms <- new_mutex!(vms, "g16::Registry::vms"), + idle <- new_mutex!(RBTree::new(), "g16::Registry::idle"), + binding <- new_mutex!((), "g16::Registry::binding"), live: AtomicU32::new(0), files <- new_mutex!(files, "g16::Registry::files"), processes <- new_mutex!(crate::queue_share::Shares::new(), @@ -219,8 +257,40 @@ impl Registry { ) } - /// Reserves a place for a new VM after dropping the registry's references to closed VMs. - fn reserve(&self, file_id: u64) -> Result> { + /// Counts a new VM against its file. + fn admit(registry: &Arc, file_id: u64) -> Result> { + // The place gives its count back when dropped, so allocate it before counting. + let place = UniqueArc::::new_uninit(GFP_KERNEL)?; + { + let mut files = registry.files.lock(); + match files.iter().position(|(id, _)| *id == file_id) { + Some(index) if files[index].1 >= MAX_VMS_PER_FILE => return Err(ENOSPC), + Some(index) => files[index].1 += 1, + None => files.push((file_id, 1), GFP_NOWAIT)?, + } + } + Ok(place + .write(FilePlace { + registry: registry.clone(), + file_id, + }) + .into()) + } + + /// Takes a VM off its file's count. + fn leave(&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); + } + } + } + + /// Reserves a TTBAT slot for a VM's first queue after dropping the registry's references to + /// closed VMs. + fn reserve(&self) -> Result> { self.prune(); // The shared slot allocator hands out a single slot with robust isolation. let limit = if module_parameters::robust_isolation.value() != 0 { @@ -236,45 +306,18 @@ impl Registry { let rollback = kernel::types::ScopeGuard::new(|| { self.live.fetch_sub(1, Ordering::AcqRel); }); - let process = { - let mut files = self.files.lock(); - 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 }); - } - } - }; + let process = self + .processes + .lock() + .take_current(limit, GFP_NOWAIT) + // The share refusing is "no room"; a failed allocation stays ENOMEM. + .map_err(|error| if error == EBUSY { ENOSPC } else { error })?; rollback.dismiss(); - Ok(Reservation(Some(self), file_id, process)) + Ok(Reservation(Some(self), process)) } - 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) - }; + fn release(&self, process: usize) { + let gone = 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); @@ -283,6 +326,9 @@ impl Registry { /// Drop the handle owner immediately, outside the registry lock. Other references /// still protect jobs, both hardware units' last owners, and deferred destruction. pub(crate) fn close(&self, id: u64) { + // A VM that never had a queue: its mappings go here, outside the registry locks. + let idle = self.idle.lock().remove_node(&id); + drop(idle); let state = { let mut vms = self.vms.lock(); let index = vms.iter().position(|state| state.id == id); @@ -387,6 +433,9 @@ impl Registry { /// Latches `error` on every VM whose client handle is open. The fail-stop path calls it under /// the device lock. pub(crate) fn fail_all(&self, error: Error) { + for idle in self.idle.lock().values() { + idle.status.record(error); + } for state in self.vms.lock().iter() { state.status.record(error); } @@ -399,7 +448,7 @@ pub(crate) fn reserved_ranges() -> [Range; 2] { [0x1000000000..0x1000010000, 0x7000000000..0x7100000000] } -/// Creates a user VM (`gpu::Gpu::new_vm`). +/// Creates a user VM (`gpu::Gpu::new_vm`), unbound until its first queue. /// /// Kernel memory sized by the VM's client (its private arenas) is charged to `memory`. pub(crate) fn new_vm( @@ -414,13 +463,13 @@ pub(crate) fn new_vm( // Reserve outside the device lock: reclaim may wait for a fence whose poller needs it. let mut aliases = KVec::with_capacity(hw::sizes::MAX_CLIENT, GFP_KERNEL)?; // Snapshot only references and metadata under the device lock; map after releasing it. - let (registry, factory) = { + let registry = { let state = gpu.shared.state.lock(); let firmware = state.as_ref().ok_or(ENODEV)?; ClientAlias::collect(&firmware.objects, &mut aliases)?; - (firmware.vms.clone(), firmware.private_factory.clone()) + firmware.vms.clone() }; - let reservation = registry.reserve(file_id)?; + let place = Registry::admit(®istry, file_id)?; let id = gpu.ids.vm.next(); let mut vm = gpu .uat @@ -430,7 +479,7 @@ pub(crate) fn new_vm( 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. + // including registry insertion. let failed_vm = kernel::types::ScopeGuard::new_with_data(vm.clone(), |vm| { if let Err(error) = vm.unmap_user_ranges(hw::USER_RANGE.clone(), kernel_range) { pr_err!("G16: closing unpublished VM failed: {:?}\n", error); @@ -440,7 +489,41 @@ pub(crate) fn new_vm( let status = vm.status().ok_or(EINVAL)?.clone(); let (mappings, reserved) = Registry::driver_mappings(&vm, aliases)?; vm.install_driver_mappings(KVec::new(), reserved)?; - // The context names the root only now: everything above is already visible to the walker. + let idle = IdleVm { + vm: vm.clone(), + status, + mappings: Arc::new(mappings, GFP_KERNEL)?, + place, + }; + let node = RBTreeNode::new(id, idle, GFP_KERNEL)?; + // Identifiers are never reused, so nothing is replaced. + let replaced = registry.idle.lock().insert(node); + drop(replaced); + drop(failed_vm.dismiss()); + Ok(vm) +} + +/// Binds the idle VM `vm` to a TTBAT slot for its first queue. The caller holds +/// [`Registry::binding`]; a failure leaves the VM idle. +fn bind_idle( + gpu: &Gpu, + registry: &Arc, + factory: object::Factory, + id: u64, +) -> Result> { + let (vm, status, mappings, place) = { + let idle = registry.idle.lock(); + let idle = idle.get(&id).ok_or(ENOENT)?; + ( + idle.vm.clone(), + idle.status.clone(), + idle.mappings.clone(), + idle.place.clone(), + ) + }; + let reservation = registry.reserve()?; + // The context names the root only now: the driver mappings and everything the client mapped + // so far are already visible to the walker. let bind = gpu.uat.bind(&vm)?; let slot = bind.slot(); let generation = bind.generation(); @@ -451,8 +534,8 @@ pub(crate) fn new_vm( .write(LiveToken { registry: registry.clone(), bind: Some(bind), - file_id, - process: reservation.2, + _place: place, + process: reservation.1, }) .into(); reservation.into_state(); @@ -468,21 +551,35 @@ pub(crate) fn new_vm( generation, status, vm: vm.clone(), - context_mappings: mappings, + context_mappings: Some(mappings), resources: Some(resources), live, }; let state = Arc::new(VmState(crate::cleanup::Deferred::new(inner)?), GFP_KERNEL)?; // Registry storage was bounded and preallocated at backend startup. NOWAIT also keeps // an invariant failure from entering reclaim under a lock required by fail_all(). - registry.vms.lock().push(state, GFP_NOWAIT)?; - drop(failed_vm.dismiss()); + registry.vms.lock().push(state.clone(), GFP_NOWAIT)?; + let idle = registry.idle.lock().remove_node(&id); + drop(idle); + // A close that found neither: the VM was closed before its state was pushed. + if vm.is_closed() { + registry.close(id); + return Err(ENOENT); + } mod_pr_debug!("G16: VM {} context {}\n", id, slot); - Ok(vm) + Ok(state) } /// The state of a VM for a new queue. pub(crate) fn lookup(gpu: &Gpu, vm: &mmu::Vm) -> Result> { - let registry = gpu.shared.state.lock().as_ref().ok_or(ENODEV)?.vms.clone(); - registry.find(vm) + let (registry, factory) = { + let state = gpu.shared.state.lock(); + let firmware = state.as_ref().ok_or(ENODEV)?; + (firmware.vms.clone(), firmware.private_factory.clone()) + }; + let _binding = registry.binding.lock(); + match registry.find(vm) { + Err(error) if error == ENOENT => bind_idle(gpu, ®istry, factory, vm.id()), + found => found, + } } diff --git a/tools/asahi/g16-vm-share-tests.py b/tools/asahi/g16-vm-share-tests.py index 4e82135f52c24..6b4893d3ca20e 100755 --- a/tools/asahi/g16-vm-share-tests.py +++ b/tools/asahi/g16-vm-share-tests.py @@ -5,7 +5,7 @@ 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 +the bound 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: @@ -34,7 +34,7 @@ def item(source, signature): def before_share(): """The reservation as it was before VMs were shared per process.""" - return r'''fn reserve(&self, file_id: u64) -> Result> { + return r'''fn reserve(&self) -> Result> { self.prune(); let limit = if module_parameters::robust_isolation.value() != 0 { 1 } else { hw::sizes::MAX_VMS }; self.live @@ -45,27 +45,16 @@ def before_share(): 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)) + Ok(Reservation(Some(self), 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') + reserve = item(vm, 'fn reserve(&self) ->') + release = item(vm, 'fn release(&self, process:') if mutation == 'before-share': reserve = before_share() elif mutation == 'lone-takes-all': @@ -75,7 +64,6 @@ def fixture(mutation): 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 ( @@ -136,11 +124,11 @@ def fixture(mutation): 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); +''' + policy + '\n' + shares + r''' +struct Registry { live: AtomicU32, processes: Mutex } +struct Reservation<'a>(Option<&'a Registry>, usize); impl Drop for Reservation<'_> { - fn drop(&mut self) { if let Some(registry) = self.0 { registry.release(self.1, self.2); } } + fn drop(&mut self) { if let Some(registry) = self.0 { registry.release(self.1); } } } impl Registry { fn prune(&self) {} @@ -151,23 +139,18 @@ def fixture(mutation): 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. + let registry = Registry { live: AtomicU32::new(0), processes: Mutex(RefCell::new(Shares::new())) }; + // A compositor (process 1) has one VM bound. 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. + let compositor = registry.reserve().expect("compositor VM"); + // Process 2 creates VMs with a queue until it is refused, whatever files they are on. 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; } - } + loop { + match registry.reserve() { + 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); @@ -175,31 +158,29 @@ def fixture(mutation): 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"); + let late = registry.reserve().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"); + let second = registry.reserve().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")); + taken.push(registry.reserve().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) } - } + for _ in 0..max + 8 { + if let Ok(r) = registry.reserve() { 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"); + let after = registry.reserve().expect("FAIL line 6: a process started later gets no VM"); drop(after); drop(all); assert_eq!(registry.live.load(Ordering::Acquire), 0); 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 5fd0cdcfc25f4..ddddbdbe690b3 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-resources.py @@ -345,7 +345,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, process: 0 }, 0).unwrap(); + let token = Arc::new(LiveToken { registry, bind: Some(bind), _place: Arc::new(FilePlace, 0).unwrap(), 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)} @@ -360,7 +360,8 @@ def module(text, name): || self.vm.cache.as_ref().is_some_and(|cache| cache.renders_unpublished()) } } - pub struct Registry{pub live:std::sync::Arc}impl Registry{fn release(&self,_file:u64,_process:usize){self.live.fetch_sub(1,Ordering::AcqRel);}} + pub struct Registry{pub live:std::sync::Arc}impl Registry{fn release(&self,_process:usize){self.live.fetch_sub(1,Ordering::AcqRel);}} + pub struct FilePlace; __LIVE_TOKEN__ __LIVE_DROP__ pub fn test_live_token() -> (mmu::VmBind, Arc, std::sync::Arc) { @@ -368,14 +369,14 @@ 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.clone()), file_id: 0, process: 0 }, 0).unwrap(); + let token = Arc::new(LiveToken { registry, bind: Some(bind.clone()), _place: Arc::new(FilePlace, 0).unwrap(), process: 0 }, 0).unwrap(); (bind, token, released) } #[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,process:0,bind:Some(mmu::VmBind{live:count.clone(),released:released.clone()})},0).unwrap(); + let token=Arc::new(LiveToken{registry,_place:Arc::new(FilePlace,0).unwrap(),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 bd42929f117a4..ae51a0e690120 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 @@ -16,7 +16,7 @@ def item(marker,text=None): #![allow(dead_code,unused_variables,non_upper_case_globals)] extern crate self as kernel; use std::sync::{Arc,Mutex as StdMutex,atomic::{AtomicU32,Ordering}}; -type Result = std::result::Result;const ENOSPC:u32=28;const GFP_NOWAIT:u32=0; +type Result = std::result::Result;const ENOSPC:u32=28;const GFP_NOWAIT:u32=0;const GFP_KERNEL:u32=1; struct Mutex(StdMutex);implMutex{fn lock(&self)->std::sync::MutexGuard<'_,T>{self.0.lock().unwrap()}} struct KVec(Vec);implKVec{fn push(&mut self,v:T,_f:u32)->Result{self.0.push(v);Ok(())}fn remove(&mut self,i:usize)->Result{Ok(self.0.remove(i))}} implstd::ops::Deref for KVec{type Target=Vec;fn deref(&self)->&Vec{&self.0}} @@ -52,36 +52,49 @@ def item(marker,text=None): 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);}} +// The kernel's fallible constructor; the tests' own Arcs stay std's. +struct UniqueArc(T);struct Space(std::marker::PhantomData); +implUniqueArc{fn new_uninit(_f:u32)->Result>{Ok(Space(std::marker::PhantomData))}} +implSpace{fn write(self,v:T)->UniqueArc{UniqueArc(v)}} +implFrom>for Arc{fn from(v:UniqueArc)->Self{Arc::new(v.0)}} +// VMs without a queue are covered by test-vm-slots.py. +struct IdleVm;struct RBTree(std::collections::BTreeMap); +implRBTree{fn remove_node(&mut self,k:&K)->Option{self.0.remove(k)}} __REGISTRY__ -struct Reservation<'a>(Option<&'a Registry>,u64,usize); +__FILE_PLACE__ +__FILE_PLACE_DROP__ +struct Reservation<'a>(Option<&'a Registry>,usize); __RESERVATION_DROP__ impl Registry{ + __ADMIT__ + __LEAVE__ __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)))),processes:Mutex(StdMutex::new(queue_share::Shares::new()))}} + fn new_test()->Arc{Arc::new(Self{idle:Mutex(StdMutex::new(RBTree(Default::default()))),binding:Mutex(StdMutex::new(())),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(); - assert!(matches!(r.reserve(7),Err(ENOSPC)));let other=r.reserve(8).unwrap(); - drop(owners.pop());owners.push(r.reserve(7).unwrap());assert!(matches!(r.reserve(7),Err(ENOSPC))); + let r=Registry::new_test();let place=|file|Registry::admit(&r,file); + let mut owners:Vec<_>=(0..8).map(|_|(place(7).unwrap(),r.reserve().unwrap())).collect(); + assert!(matches!(place(7),Err(ENOSPC)));let other=(place(8).unwrap(),r.reserve().unwrap()); + drop(owners.pop());owners.push((place(7).unwrap(),r.reserve().unwrap()));assert!(matches!(place(7),Err(ENOSPC))); 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(){ // 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); + let r=Registry::new_test();let owners:Vec<_>=(0..63u64).map(|n|{as_process((n/8+1) as usize);r.reserve().unwrap()}).collect(); + as_process(100);assert!(matches!(r.reserve(),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. + // One process 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(); + let owners:Vec<_>=(0..56).map(|_|r.reserve().unwrap()).collect(); + assert!(matches!(r.reserve(),Err(ENOSPC)));assert_eq!(r.live.load(Ordering::Acquire),56); + as_process(2);let compositor=r.reserve().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); + 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)); @@ -108,7 +121,7 @@ def item(marker,text=None): assert_eq!(drops.load(Ordering::Acquire),1); } ''' -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)')]: +for tag,marker in [('REGISTRY','pub(crate) struct Registry'),('RESERVATION_DROP',"impl Drop for Reservation<'_>"),('FILE_PLACE','pub(crate) struct FilePlace'),('FILE_PLACE_DROP','impl Drop for FilePlace'),('ADMIT','fn admit('),('LEAVE','fn leave('),('RESERVE','fn reserve(&self)'),('RELEASE','fn release(&self, process:'),('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) diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-slots.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-slots.py new file mode 100644 index 0000000000000..8f108d77c074e --- /dev/null +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-slots.py @@ -0,0 +1,402 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Exercise when production VM creation and queue creation take a TTBAT slot, without a GPU.""" +from common import kernel_root, output_dir, rustc +import re, subprocess + +g16 = kernel_root() / 'drivers/gpu/drm/asahi/g16' +vm = (g16 / 'vm.rs').read_text() +hw = (g16 / 'hw.rs').read_text() +qs = (g16.parent / 'queue_share.rs').read_text() + + +def item(text, marker): + start = text.index(marker) + i = text.index('{', start) + 1 + depth = 1 + while depth: + depth += (text[i] == '{') - (text[i] == '}') + i += 1 + return text[start:i] + + +def constant(name): + """A `usize`/`u32` constant of hw.rs, following sums of other such constants.""" + value = re.search(r'pub\(crate\) const %s: (?:usize|u32) = ([^;]+);' % name, hw).group(1) + return sum(int(v) if v.isdigit() else constant(v) for v in value.split(' + ')) + + +# Everything from the VM state on, without what builds the mappings and the registry's locks. +code = vm[vm.index('/// G16 state of one user VM'):] +for marker in (' pub(crate) fn new() -> Result>', ' fn driver_mappings(', + 'pub(crate) fn reserved_ranges('): + code = code.replace(item(code, marker), '') +code = code.replace('#[pin_data]\n', '').replace(' #[pin]\n', '') +per_file = re.search(r'const MAX_VMS_PER_FILE: u32 = \d+;', vm).group(0) + +# Fields of the registry that only some versions of vm.rs have. +registry = item(code, 'pub(crate) struct Registry') +fields = ''.join(text for name, text in ( + ('idle:', 'idle: Mutex::new(RBTree::new()),'), + ('binding:', 'binding: Mutex::new(()),'), +) if name in registry) + +source = r''' +#![allow(dead_code, unused_variables, unused_imports, unused_macros)] +use std::{collections::BTreeMap, ops::Range, sync::{Mutex as StdMutex, MutexGuard}}; +type Result = std::result::Result; +type Error = u32; +const ENOENT: u32 = 2; const EIO: u32 = 5; const ENOMEM: u32 = 12; const EBUSY: u32 = 16; +const ENODEV: u32 = 19; const EINVAL: u32 = 22; const ENOSPC: u32 = 28; +const GFP_KERNEL: u32 = 0; const GFP_NOWAIT: u32 = 1; +macro_rules! mod_pr_debug { ($($t:tt)*) => {}; } +macro_rules! pr_err { ($($t:tt)*) => {}; } + +struct Mutex(StdMutex); +impl Mutex { + fn new(v: T) -> Self { Self(StdMutex::new(v)) } + // A held lock means the code under test would deadlock. + fn lock(&self) -> MutexGuard<'_, T> { self.0.try_lock().expect("lock held") } +} +struct Arc(std::sync::Arc); +impl Arc { fn new(v: T, _f: u32) -> Result { Ok(Self(std::sync::Arc::new(v))) } } +impl Clone for Arc { fn clone(&self) -> Self { Self(self.0.clone()) } } +impl std::ops::Deref for Arc { type Target = T; fn deref(&self) -> &T { &self.0 } } +struct UniqueArc(T); +struct Space(std::marker::PhantomData); +impl UniqueArc { + fn new_uninit(_f: u32) -> Result> { Ok(Space(std::marker::PhantomData)) } +} +impl Space { fn write(self, v: T) -> UniqueArc { UniqueArc(v) } } +impl From> for Arc { + fn from(v: UniqueArc) -> Self { Self(std::sync::Arc::new(v.0)) } +} +struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn with_capacity(n: usize, _f: u32) -> Result { Ok(Self(Vec::with_capacity(n))) } + fn push(&mut self, v: T, _f: u32) -> Result { self.0.push(v); Ok(()) } + fn remove(&mut self, i: usize) -> Result { Ok(self.0.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 RBTree(BTreeMap); +struct RBTreeNode(K, V); +impl RBTreeNode { fn new(k: K, v: V, _f: u32) -> Result { Ok(Self(k, v)) } } +impl RBTree { + fn new() -> Self { Self(BTreeMap::new()) } + fn insert(&mut self, n: RBTreeNode) -> Option { self.0.insert(n.0, n.1) } + fn get(&self, k: &K) -> Option<&V> { self.0.get(k) } + fn remove_node(&mut self, k: &K) -> Option { self.0.remove(k) } + fn values(&self) -> impl Iterator { self.0.values() } +} +mod kernel { pub mod types { + pub struct ScopeGuard(Option<(T, F)>); + impl ScopeGuard { + pub fn new_with_data(v: T, f: F) -> Self { Self(Some((v, f))) } + pub fn dismiss(mut self) -> T { self.0.take().unwrap().0 } + } + impl ScopeGuard<(), fn(())> { + pub fn new(f: F) -> ScopeGuard<(), impl FnOnce(())> { + ScopeGuard(Some(((), move |()| f()))) + } + } + impl Drop for ScopeGuard { + fn drop(&mut self) { if let Some((v, f)) = self.0.take() { f(v) } } + } +} } +mod module_parameters { + pub struct Param; + impl Param { pub fn value(&self) -> u32 { 0 } } + #[allow(non_upper_case_globals)] pub static robust_isolation: Param = Param; +} +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(pub BTreeMap); + impl Shares { + pub fn take_current(&mut self, max: u32, _f: u32) -> Result { + let key = CURRENT.with(|c| c.get()); + let held = self.0.get(&key).copied().unwrap_or(0); + if !may_take_held(held, self.0.values().sum(), max) { return Err(EBUSY); } + *self.0.entry(key).or_default() += 1; + Ok(key) + } + pub fn give_back(&mut self, key: usize) -> Option { + let held = self.0.get_mut(&key)?; + *held -= 1; + if *held != 0 { return None; } + self.0.remove(&key); + Some(key) + } + } +} +mod memacct { pub struct Client; } +// The production cleanup is asynchronous; releasing at once only makes reuse earlier. +mod cleanup { + pub struct Deferred(T); + impl Deferred { pub fn new(v: T) -> super::Result { Ok(Self(v)) } } + impl std::ops::Deref for Deferred { type Target = T; fn deref(&self) -> &T { &self.0 } } +} +mod mmu { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + pub struct KernelMapping; + #[derive(Clone)] + pub struct Vm { id: u64, closed: std::sync::Arc, status: Option> } + impl Vm { + pub fn with_tracked_status(mut self) -> Result { + self.status = Some(Arc::new(vm::VmStatus::default(), 0)?); + Ok(self) + } + pub fn with_memory_client(self, _c: Arc) -> Self { self } + pub fn id(&self) -> u64 { self.id } + pub fn status(&self) -> Option<&Arc> { self.status.as_ref() } + pub fn is_closed(&self) -> bool { self.closed.load(Ordering::Acquire) } + pub fn install_driver_mappings(&self, _m: KVec, _r: KVec>) -> Result { Ok(()) } + pub fn unmap_user_ranges(&self, _u: Range, _k: Range) -> Result { + self.closed.store(true, Ordering::Release); + Ok(()) + } + pub fn bo_deferred_cleanup(&self) {} + } + /// TTBAT user slots 1..=63 and their users: a slot is free only without any. + pub struct Uat { pub users: std::sync::Arc>>, pub on_bind: StdMutex>> } + impl Uat { + pub fn new_vm(&self, id: u64, _k: Range) -> Result { + Ok(Vm { id, closed: Default::default(), status: None }) + } + pub fn bind(&self, vm: &Vm) -> Result { + if let Some(f) = self.on_bind.lock().unwrap().take() { f(vm); } + let mut users = self.users.lock().unwrap(); + // The slot allocator would wait here: the registry must never let it come to that. + let slot = (1..=super::hw::sizes::MAX_VMS).find(|s| !users.contains_key(s)).expect("no free slot"); + users.insert(slot, 1); + Ok(VmBind { slot, users: self.users.clone() }) + } + } + pub struct VmBind { slot: u32, users: std::sync::Arc>> } + impl VmBind { + pub fn slot(&self) -> u32 { self.slot } + pub fn generation(&self) -> u8 { 1 } + } + impl Clone for VmBind { + fn clone(&self) -> Self { + *self.users.lock().unwrap().get_mut(&self.slot).unwrap() += 1; + Self { slot: self.slot, users: self.users.clone() } + } + } + impl Drop for VmBind { + fn drop(&mut self) { + let mut users = self.users.lock().unwrap(); + let n = users.get_mut(&self.slot).unwrap(); + *n -= 1; + if *n == 0 { users.remove(&self.slot); } + } + } +} +mod hw { + pub const USER_RANGE: std::ops::Range = 0..1; + pub mod sizes { pub const MAX_VMS: u32 = __MAX_VMS__; pub const MAX_CLIENT: usize = 1; } +} +mod object { + #[derive(Clone)] pub struct Factory; + pub struct Objects; +} +mod resources { + use super::*; + thread_local! { pub static FAIL: std::cell::Cell = std::cell::Cell::new(false); } + pub struct Cache(mmu::VmBind, Arc); + impl Cache { + pub fn new(_f: object::Factory, b: mmu::VmBind, l: Arc, _s: std::sync::Arc) -> Result> { + if FAIL.with(|f| f.replace(false)) { return Err(ENOMEM); } + Arc::new(Self(b, l), 0) + } + pub fn close(&self) {} + pub fn renders_unpublished(&self) -> bool { false } + } +} +pub struct Firmware { objects: object::Objects, vms: Arc, private_factory: object::Factory } +pub struct Shared { crashed: std::sync::atomic::AtomicBool, state: Mutex> } +struct Ids { vm: Sequence } +struct Sequence(std::sync::atomic::AtomicU64); +impl Sequence { fn next(&self) -> u64 { self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } } +pub struct Gpu { shared: std::sync::Arc, uat: mmu::Uat, ids: Ids } +mod vm { + use super::*; + use std::sync::atomic::{AtomicU32, Ordering}; + #[derive(Default)] pub struct VmStatus(std::sync::atomic::AtomicU32); + impl VmStatus { + pub fn record(&self, e: u32) { self.0.store(e, Ordering::Release); } + pub fn get(&self) -> u32 { self.0.load(Ordering::Acquire) } + } + struct ClientAlias; + impl ClientAlias { fn collect(_o: &object::Objects, _a: &mut KVec) -> Result { Ok(()) } } + __PER_FILE__ + __CODE__ + impl Registry { + fn driver_mappings(_vm: &mmu::Vm, _a: KVec) -> Result<(KVec, KVec>)> { + Ok((KVec::new(), KVec::new())) + } + fn new_test() -> Arc { + Arc::new(Self { + vms: Mutex::new(KVec::new()), live: AtomicU32::new(0), files: Mutex::new(KVec::new()), + processes: Mutex::new(queue_share::Shares(BTreeMap::new())), __FIELDS__ + }, 0).unwrap() + } + fn idle_files(&self) -> bool { self.files.lock().is_empty() && self.processes.lock().0.is_empty() } + } + fn gpu() -> Gpu { + Gpu { + shared: std::sync::Arc::new(Shared { + crashed: Default::default(), + state: Mutex::new(Some(Firmware { objects: object::Objects, vms: Registry::new_test(), private_factory: object::Factory })), + }), + uat: mmu::Uat { users: Default::default(), on_bind: Default::default() }, + ids: Ids { vm: Sequence(1.into()) }, + } + } + fn registry(g: &Gpu) -> Arc { g.shared.state.lock().as_ref().unwrap().vms.clone() } + fn create(g: &Gpu, file: u64) -> Result { + queue_share::CURRENT.with(|c| c.set(file as usize)); + new_vm(g, 0..1, file, None) + } + // What file::Vm does when the client's handle goes. + fn close(g: &Gpu, vm: &mmu::Vm) { + vm.unmap_user_ranges(0..1, 0..1).unwrap(); + registry(g).close(vm.id()); + } + fn slots_in_use(g: &Gpu) -> usize { g.uat.users.lock().unwrap().len() } + /// A Vulkan process: its physical device's VM, which never gets a queue, and its logical + /// device's VM with one. + fn vulkan(g: &Gpu, file: u64) -> Result<([mmu::Vm; 2], Arc)> { + let physical = create(g, file)?; + let logical = create(g, file)?; + let state = lookup(g, &logical)?; + Ok(([physical, logical], state)) + } + + /// gpubench compute.light procs d=16, pass 2 (linux#3340): every pipe and slot that keeps its + /// newest owner until another one displaces it keeps the VM of a process that has exited. + #[test] + fn exited_clients_on_every_pipe_leave_slots_for_sixteen_processes() { + let g = gpu(); + let desktop: Vec<_> = (0..9).map(|n| { let vm = create(&g, n).unwrap(); (lookup(&g, &vm).unwrap(), vm) }).collect(); + let mut leases = Vec::new(); + for n in 0..__PINNED__ { + let (vms, state) = vulkan(&g, 100 + n).unwrap(); + for vm in &vms { close(&g, vm); } + leases.push(state); + } + assert_eq!(slots_in_use(&g), desktop.len() + leases.len()); + let clients: Vec<_> = (0..16).map(|n| { + vulkan(&g, 200 + n).unwrap_or_else(|e| panic!("process {n}: errno {e}, {} slots in use", slots_in_use(&g))) + }).collect(); + // The slots of the exited clients are still leased: none of them was handed out again. + let mut slots: Vec = desktop.iter().map(|d| d.0.slot).chain(leases.iter().map(|s| s.slot)) + .chain(clients.iter().map(|c| c.1.slot)).collect(); + assert_eq!(slots.len(), slots_in_use(&g)); + slots.sort(); slots.dedup(); + assert_eq!(slots.len(), slots_in_use(&g)); + } + #[test] + fn a_leased_slot_is_not_reused_until_its_last_owner_goes() { + let g = gpu(); + let (vms, lease) = vulkan(&g, 1).unwrap(); + for vm in &vms { close(&g, vm); } + // Fill the rest; the process share keeps some free for others, so use many processes. + let mut held = Vec::new(); + let full = loop { + match vulkan(&g, 2 + held.len() as u64) { + Ok(client) => { assert_ne!(client.1.slot, lease.slot); held.push(client) } + Err(e) => break e, + } + }; + assert_eq!(full, ENOSPC); + assert_eq!(held.len() as u32, hw::sizes::MAX_VMS - 1); + let slot = lease.slot; + drop(lease); + assert_eq!(vulkan(&g, 1000).unwrap().1.slot, slot); + } + #[test] + fn a_vm_is_bound_once_for_all_its_queues() { + let g = gpu(); + let vm = create(&g, 1).unwrap(); + assert_eq!(slots_in_use(&g), 0); + let (a, b) = (lookup(&g, &vm).unwrap(), lookup(&g, &vm).unwrap()); + assert!(std::sync::Arc::ptr_eq(&a.0, &b.0)); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (1, (1, 1))); + close(&g, &vm); + drop(a); + assert_eq!(slots_in_use(&g), 1); + drop(b); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (0, (0, 0))); + assert!(registry(&g).idle_files()); + assert!(matches!(lookup(&g, &vm), Err(ENOENT))); + } + #[test] + fn a_failed_binding_leaves_the_vm_for_another_queue() { + let g = gpu(); + let vm = create(&g, 1).unwrap(); + resources::FAIL.with(|f| f.set(true)); + assert!(matches!(lookup(&g, &vm), Err(ENOMEM))); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (0, (0, 0))); + let state = lookup(&g, &vm).unwrap(); + assert_eq!(slots_in_use(&g), 1); + close(&g, &vm); + drop(state); + assert_eq!(slots_in_use(&g), 0); + assert!(registry(&g).idle_files()); + } + #[test] + fn a_vm_closed_while_it_is_bound_keeps_nothing() { + let g = gpu(); + let vm = create(&g, 1).unwrap(); + let r = registry(&g); + *g.uat.on_bind.lock().unwrap() = Some(Box::new(move |vm| { + vm.unmap_user_ranges(0..1, 0..1).unwrap(); + r.close(vm.id()); + })); + assert!(matches!(lookup(&g, &vm), Err(ENOENT))); + assert_eq!((slots_in_use(&g), registry(&g).counts()), (0, (0, 0))); + assert!(registry(&g).idle_files()); + } + #[test] + fn the_file_quota_counts_vms_with_and_without_a_queue() { + let g = gpu(); + let mut vms: Vec<_> = (0..MAX_VMS_PER_FILE).map(|_| create(&g, 7).unwrap()).collect(); + let state = lookup(&g, &vms[0]).unwrap(); + assert!(matches!(create(&g, 7), Err(ENOSPC))); + assert!(create(&g, 8).is_ok()); + // Closing an unbound VM gives its place back at once, a bound one with its last owner. + close(&g, &vms.pop().unwrap()); + vms.push(create(&g, 7).unwrap()); + close(&g, &vms[0]); + assert!(matches!(create(&g, 7), Err(ENOSPC))); + drop(state); + assert!(create(&g, 7).is_ok()); + } + #[test] + fn fail_stop_reaches_vms_without_a_queue() { + let g = gpu(); + let (idle, bound) = (create(&g, 1).unwrap(), create(&g, 2).unwrap()); + let state = lookup(&g, &bound).unwrap(); + registry(&g).fail_all(EIO); + assert_eq!((idle.status().unwrap().get(), state.status.get()), (EIO, EIO)); + } +} +''' +# The newest owner of every compute pipe, of the render slots, and of every PB slot. +pinned = constant('COMPUTE_PIPES') + 1 + constant('PB_SLOTS') +for tag, text in (('QS_RESERVE', 'pub ' + item(qs, 'fn reserve(max: u32)')), + ('QS_MAY_TAKE_HELD', 'pub ' + item(qs, 'fn may_take_held(')), + ('MAX_VMS', str(constant('MAX_VMS'))), ('PINNED', str(pinned)), + ('PER_FILE', per_file), ('FIELDS', fields), ('CODE', code)): + source = source.replace('__%s__' % tag, text) +out = output_dir() +path = out / 'vm_slots.rs' +path.write_text(source) +subprocess.run(rustc() + ['--edition=2021', '--test', str(path), '-o', str(out / 'vm_slots')], check=True) +subprocess.run([str(out / 'vm_slots')], check=True)