diff --git a/drivers/gpu/drm/asahi/Makefile b/drivers/gpu/drm/asahi/Makefile index 11564c2302e3d..29d03365d7e54 100644 --- a/drivers/gpu/drm/asahi/Makefile +++ b/drivers/gpu/drm/asahi/Makefile @@ -9,6 +9,6 @@ aurora-$(CONFIG_DRM_ASAHI_UAT_ADOPTION) += g15/uat_glue.o aurora-$(CONFIG_DRM_ASAHI_G16) += g16/glue.o -aurora-y += retain.o sleep_pd.o cpu_capacity.o g17/mesh_tvb_floor.o rtkit_dump.o +aurora-y += memcg_scope.o retain.o sleep_pd.o cpu_capacity.o g17/mesh_tvb_floor.o rtkit_dump.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/sync_input.o aurora-$(CONFIG_DRM_ASAHI_G18) += g18/demand.o diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 75d0b5990eb37..adbca7864df25 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -201,6 +201,24 @@ pub(crate) struct FirmwarePages { _qos: Arc, } +/// One compute command of an owner, from before its SUBMIT provisions the owner's compute backing +/// until the command is dropped. While any is held, what the owner was given back for its +/// publications is kept for them ([`Context::compute_claimed`]). +pub(crate) struct ComputeClaim(Arc); + +impl ComputeClaim { + pub(crate) fn new(context: &Arc) -> Self { + context.compute_claims.fetch_add(1, Ordering::AcqRel); + Self(context.clone()) + } +} + +impl Drop for ComputeClaim { + fn drop(&mut self) { + self.0.compute_claims.fetch_sub(1, Ordering::AcqRel); + } +} + pub(crate) struct Context { /// The GPU runs the M5 firmware's protocol. m5: bool, @@ -226,6 +244,9 @@ pub(crate) struct Context { /// Advisory count of bound compute channels: publication still checks the physical binding /// under the device mutex. Zero skips an inline attempt known to need admission. compute_bindings: AtomicU32, + /// This owner's compute commands from before their SUBMIT provisioned them until they are + /// dropped ([`ComputeClaim`]): while there are any, the owner's spare compute backing stays. + compute_claims: AtomicU32, /// Shared monotonic compute completion ordinal / submit sequence across an M5 multi-channel /// context's physical compute queues. compute_ordinal: AtomicU32, @@ -386,6 +407,7 @@ impl Context { closed_generation: AtomicU64::new(u64::MAX), closed_for_open_client: AtomicBool::new(false), compute_bindings: AtomicU32::new(0), + compute_claims: AtomicU32::new(0), compute_ordinal: AtomicU32::new(0), render_seen: AtomicBool::new(false), render_active: AtomicU32::new(0), @@ -431,6 +453,10 @@ impl Context { self.render_seen.store(true, Ordering::Release); } } + /// Whether a compute command of this owner holds a [`ComputeClaim`]. + pub(crate) fn compute_claimed(&self) -> bool { + self.compute_claims.load(Ordering::Acquire) != 0 + } /// Active (published and unretired) render count for this context. pub(crate) fn render_active(&self) -> u32 { self.render_active.load(Ordering::Acquire) diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index 017f6d03b2013..91dac5a0131be 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -334,6 +334,20 @@ impl Drop for Pages { LOWER_FREED.fetch_add(1, Ordering::AcqRel); } } +impl super::queue::compute::reserve::Capacity for Pages { + fn fits(&self, required: ComputeCapacity) -> bool { + self.fits_capacity(required) + } + fn covers(&self, other: &Self) -> bool { + match (self.layout, other.layout) { + (PageLayout::Neo { blocks, .. }, PageLayout::Neo { blocks: other, .. }) => blocks >= other, + (PageLayout::M5(geometry), PageLayout::M5(other)) => + geometry.block_bytes() == other.block_bytes() && geometry.blocks >= other.blocks, + _ => false, + } + } +} + impl Pages { fn new(alloc: &Allocator<'_>, blocks: usize, runs: RunLayout) -> Result { let size = TABLE_SIZE + blocks * FREE_LIST_BLOCK_SIZE; @@ -394,8 +408,9 @@ impl Pages { let (backing, charge) = match client { Some(client) => { let commit = crate::memacct::LEDGER.admit(client, size as u64)?; - let backing = alloc.lower_user_charged(size, mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_SHARED_RW)?; + let backing = client.charging(|| alloc.lower_user_charged( + size, mmu::UAT_PGSZ as u64, mmu::PROT_GPU_SHARED_RW, + ))?; let charge = crate::memacct::Charge::user(commit, None); charge.set_held(true); (backing, Some(charge)) @@ -455,6 +470,19 @@ impl Pages { _ => false, } } + /// Writes the tables of fresh backing again, for reuse by the owner that gave this backing + /// back. The caller has seen the firmware consume the pool's release. + pub(crate) fn reset(&mut self) -> Result { + match self.layout { + PageLayout::Neo { blocks, runs } => { + let base = self.backing.gpu_va(); + self.backing.initialize::(0, |tables| tables.init(base, blocks, runs))?; + } + PageLayout::M5(_) => self.populate_m5()?, + } + fence(Ordering::SeqCst); + Ok(()) + } fn is_m5(&self) -> bool { matches!(self.layout, PageLayout::M5(_)) } pub(crate) fn page_list_va(&self) -> u64 { self.backing.gpu_va() } fn run_list_va(&self) -> u64 { @@ -1043,6 +1071,23 @@ impl Submitted<'_> { /// that VM's work, so a view of it in another VM is refused /// ([`Self::map_client`]). Another VM gets the queue only after the backing /// was given back and fresh, zeroed backing installed ([`Self::rearm`]). +/// The control and state objects of a compute pool, allocated before a QID is reserved for it. +pub(crate) struct PoolObjects { + control: KernelObject, + state: KernelObject, +} +impl PoolObjects { + pub(crate) fn new(alloc: &Allocator<'_>) -> Result { + let object = || alloc.kernel( + CONTROL_SIZE, + mmu::UAT_PGSZ as u64, + mmu::PROT_GPU_FW_SHARED_RW, + CpuMap::WriteCombined, + ); + Ok(Self { control: object()?, state: object()? }) + } +} + pub(crate) struct ComputePool { pages: Option, /// The VM (`mmu::Vm::id`) the backing serves, from its first client view @@ -1059,33 +1104,22 @@ impl ComputePool { self.pages.as_ref().is_some_and(|pages| pages.fits_capacity(required)) } - /// A pool at the admitted capacity, in the capacity's family format. - pub(crate) fn new(alloc: &Allocator<'_>, qid: u8, required: ComputeCapacity, - client: Option<&Arc>) -> Result { - if qid > super::fw::kick::QID_MAX { - return Err(EINVAL); - } - let pages = Pages::for_compute(alloc, required, client)?; + /// Binds `objects` and `pages` to the pool slot of `qid`: stores only. + pub(crate) fn prepare(objects: &mut PoolObjects, qid: u8, pages: &Pages) -> Result { + if qid > super::fw::kick::QID_MAX { return Err(EINVAL); } + Self::initialize_control(&mut objects.control, pages, Self::slot(qid), objects.state.gpu_va(), [0; 8])?; + fence(Ordering::SeqCst); + Ok(()) + } + + pub(crate) fn bind(objects: PoolObjects, qid: u8, pages: Pages, client_vm: u64) -> Self { + let PoolObjects { control, state } = objects; let m5 = pages.is_m5(); - Self::with_pages(alloc, qid, m5, pages) + Self { pages: Some(pages), client_vm, control, state, id: Self::slot(qid), m5 } } - fn with_pages(alloc: &Allocator<'_>, qid: u8, m5: bool, pages: Pages) -> Result { - let id = u16::from(qid) + 1; - let mut control = alloc.kernel( - CONTROL_SIZE, - mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_FW_SHARED_RW, - CpuMap::WriteCombined, - )?; - let state = alloc.kernel( - CONTROL_SIZE, - mmu::UAT_PGSZ as u64, - mmu::PROT_GPU_FW_SHARED_RW, - CpuMap::WriteCombined, - )?; - Self::initialize_control(&mut control, &pages, id, state.gpu_va(), [0; 8])?; - fence(Ordering::SeqCst); - Ok(Self { pages: Some(pages), client_vm: 0, control, state, id, m5 }) + /// The pool slot (buffer slot) of `qid`'s pool. + pub(crate) fn slot(qid: u8) -> u16 { + u16::from(qid) + 1 } fn initialize_control(control: &mut KernelObject, pages: &Pages, id: u16, submitted: u64, completed: [u8; 8]) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/fw/compute.rs b/drivers/gpu/drm/asahi/g17/fw/compute.rs index dd27fdb54aefd..5a25ca7c29018 100644 --- a/drivers/gpu/drm/asahi/g17/fw/compute.rs +++ b/drivers/gpu/drm/asahi/g17/fw/compute.rs @@ -35,6 +35,12 @@ pub(crate) enum ComputeProgram { V25F84, } +impl ComputeProgram { + pub(crate) fn needs_shared_aperture(self) -> bool { + matches!(self, Self::G17P) + } +} + const V25F84_REGISTERS: usize = 36; const V25F84_REGISTERS_MAX: usize = V25F84_REGISTERS + 1; const V25F84_CHECKPOINTS: [u16; 4] = [34, 35, 35, V25F84_REGISTERS as u16]; diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index cec4cb5e09a83..520d0ef9077aa 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -129,6 +129,8 @@ pub(crate) struct Packet { pub(crate) order: Order, pub(crate) completion: Arc, pub(crate) footprint: Option>, + /// A compute command's hold on its owner's spare compute backing. + _claim: Option, /// Number of render passes in the submit ioctl that created this packet. pub(crate) batch_renders: u16, inputs: KVec, @@ -168,6 +170,7 @@ impl Packet { batch_renders: u16, inputs: KVec, producers: Option, + claim: Option, ) -> Result> { let footprint = match &command { Validated::Render { attachments, pass, .. } => { @@ -185,6 +188,7 @@ impl Packet { order, completion, footprint, + _claim: claim, batch_renders, inputs, producers, diff --git a/drivers/gpu/drm/asahi/g17/kick.rs b/drivers/gpu/drm/asahi/g17/kick.rs index 7f365425f5d78..9f51096513da0 100644 --- a/drivers/gpu/drm/asahi/g17/kick.rs +++ b/drivers/gpu/drm/asahi/g17/kick.rs @@ -622,11 +622,14 @@ impl PreparedKick<'_> { } } -impl Queue { - pub(crate) fn compute(alloc: &Allocator<'_>, id: Id) -> Result { - if id.engine != DataMaster::Compute { - return Err(EINVAL); - } +/// Storage of a compute queue's kick ring, allocated before a QID is reserved for it. +pub(crate) struct ComputeRing { + high: mmu::KernelMapping, + low: KernelObject, +} + +impl ComputeRing { + pub(crate) fn new(alloc: &Allocator<'_>) -> Result { let low = alloc.lower( KICK_RING_SIZE, mmu::UAT_PGSZ as u64, @@ -641,12 +644,24 @@ impl Queue { mmu::PROT_FW_SHARED_RW, )?; fence(Ordering::SeqCst); - Ok(Self { + Ok(Self { high, low }) + } + + pub(crate) fn map_client(&self, vm: &mmu::Vm) -> Result { + self.low.map_alias(vm, self.low.gpu_va(), CLIENT_KICK_PROT) + } +} + +impl Queue { + /// Binds `ring` to the QID of `id`: stores only. + pub(crate) fn compute(ring: ComputeRing, id: Id) -> Self { + let ComputeRing { high, low } = ring; + Self { backing: Backing::Compute { high, low }, id, timestamp: KickTimestamp::FIRST, previous: None, - }) + } } /// Retired storage of a never-written ring is reused first. The returned view of the ring diff --git a/drivers/gpu/drm/asahi/g17/mod.rs b/drivers/gpu/drm/asahi/g17/mod.rs index 2720f5146715c..ef929c124721f 100644 --- a/drivers/gpu/drm/asahi/g17/mod.rs +++ b/drivers/gpu/drm/asahi/g17/mod.rs @@ -91,14 +91,13 @@ use kernel::{ IoSysMap, Region, // }, - new_condvar, new_delayed_work, new_mutex, new_work, platform, + new_delayed_work, new_mutex, new_work, platform, prelude::*, soc::apple::rtkit, sync::{ aref::ARef, Arc, ArcBorrow, - CondVar, Mutex, // }, time::{ @@ -1309,39 +1308,6 @@ const GOVERNOR_WORK: u64 = 6; /// `HOUSEKEEPING_NS`. const HOUSEKEEPING_WORK: u64 = 7; -/// `CondVar` wrapper that tracks active waiters so `notify_all()` skips the waitqueue lock -/// in the common zero-waiter steady state. -#[pin_data] -struct TrackedCondVar { - #[pin] - condvar: CondVar, - waiters: AtomicU32, -} - -impl TrackedCondVar { - fn wait_timeout( - &self, - guard: &mut kernel::sync::MutexGuard<'_, T>, - timeout: kernel::time::Jiffies, - ) -> kernel::sync::CondVarTimeoutResult { - struct Waiter<'a>(&'a AtomicU32); - impl Drop for Waiter<'_> { - fn drop(&mut self) { - self.0.fetch_sub(1, Ordering::Release); - } - } - self.waiters.fetch_add(1, Ordering::SeqCst); - let _waiter = Waiter(&self.waiters); - self.condvar.wait_timeout(guard, timeout) - } - - fn notify_all(&self) { - if self.waiters.load(Ordering::SeqCst) != 0 { - self.condvar.notify_all(); - } - } -} - /// Device state shared with the coprocessor callbacks and the event worker. #[pin_data] struct Shared { @@ -1386,6 +1352,8 @@ struct Shared { #[pin] feed_work: Work, preparations: Arc, + #[pin] + compute_provision: Mutex<()>, /// Compute admission waiting for a physical channel: signalled when a channel becomes /// reusable or shareable, a QID or slot is returned, or a pool vacancy is witnessed. channels: Arc, @@ -1475,8 +1443,6 @@ struct Shared { /// fan boost. Never taken with `state` held. #[pin] actuators: Mutex, - #[pin] - changed: TrackedCondVar, /// The port of the session in `state`; null before boot and once detachment begins. port: core::sync::atomic::AtomicPtr, } @@ -1799,7 +1765,6 @@ impl Shared { /// Wakes the waiters for a returned pair, binding or capacity change. fn note_changed(&self) { - self.changed.notify_all(); self.renders.notify(); } @@ -2325,11 +2290,8 @@ impl Gpu { reclaim <- new_mutex!(reclaim, "g17::Shared::reclaim"), stop <- new_mutex!((), "g17::Shared::stop"), state <- new_mutex!(None, "g17::Shared::state"), + compute_provision <- new_mutex!((), "g17 compute provisioning"), actuators <- new_mutex!(thermal::Actuators::new(), "g17::Shared::actuators"), - changed <- pin_init!(TrackedCondVar { - condvar <- new_condvar!("g17::Shared::changed"), - waiters: AtomicU32::new(0), - }), port: core::sync::atomic::AtomicPtr::new(core::ptr::null_mut()), }), GFP_KERNEL, diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index 846a1582b2d96..7904feb9d8569 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -134,6 +134,42 @@ impl KernelObject { Ok(object) } + /// [`Self::backing`] that `client`'s queues need, charged to it whatever the limits: counted + /// as its held memory instead of kernel memory, and its pages charged to the client's memory + /// cgroup, until the object is dropped, also after the client is gone. Without a client it is + /// kernel memory, as [`Self::backing`]. + pub(crate) fn queue_backing( + dev: &AsahiDrmDevice, + size: usize, + cpu: CpuMap, + client: Option<&kernel::sync::Arc>, + ) -> Result { + let Some(client) = client else { + return Self::backing(dev, size, cpu); + }; + let bytes = gem::checked_object_size(size)? as u64; + Self::charged(dev, size, cpu, client, crate::memacct::LEDGER.commit(client, bytes)) + } + + fn charged( + dev: &AsahiDrmDevice, + size: usize, + cpu: CpuMap, + client: &kernel::sync::Arc, + commit: crate::memacct::Commit, + ) -> Result { + let obj = match cpu { + CpuMap::WriteBack => gem::new_kernel_object_user_charged(dev, size)?, + CpuMap::WriteCombined => gem::new_kernel_object_wc_user_charged(dev, size)?, + }; + // `with_object()` populates the pages. + let mut object = client.charging(|| Self::with_object(obj, size))?; + let charge = crate::memacct::Charge::user(commit, None); + charge.set_held(true); + object.charge = Some(charge); + Ok(object) + } + fn with_object(mut obj: gem::ObjectRef, size: usize) -> Result { let vmap = obj.vmap()?; let ptr = NonNull::new(vmap.addr.cast::()).ok_or(ENOMEM)?; @@ -385,12 +421,32 @@ impl KernelObject { /// Allocation domains shared by the G17 resource builders. Dynamic objects /// retain a guard page; aliases keep the existing backing and its exact VA. +/// `client`, if there is one, is the client whose queues the objects are for; they are charged +/// to it ([`KernelObject::queue_backing`]). pub(crate) struct Allocator<'a> { pub(crate) dev: &'a AsahiDrmDevice, pub(crate) uat: &'a mmu::Uat, + pub(crate) client: Option<&'a kernel::sync::Arc>, } impl Allocator<'_> { + /// Allocates fresh backing, charged to the allocator's client. + pub(crate) fn backing(&self, size: usize, cpu: CpuMap) -> Result { + KernelObject::queue_backing(self.dev, size, cpu, self.client) + } + + /// [`KernelObject::new`] with backing charged to the allocator's client. + pub(crate) fn object( + &self, + vm: &mmu::Vm, + placement: Placement, + size: usize, + prot: mmu::Prot, + cpu: CpuMap, + ) -> Result { + self.backing(size, cpu)?.placed(vm, placement, prot) + } + /// Allocates in the dynamic part of the firmware's upper address space. pub(crate) fn kernel( &self, @@ -400,14 +456,7 @@ impl Allocator<'_> { cpu: CpuMap, ) -> Result { let range = self.uat.kernel_dynamic_range(); - KernelObject::new( - self.dev, - self.uat.kernel_vm(), - Placement::In(range, align), - size, - prot, - cpu, - ) + self.object(self.uat.kernel_vm(), Placement::In(range, align), size, prot, cpu) } /// Allocates a canonical low mapping, which can be aliased at the same @@ -419,8 +468,7 @@ impl Allocator<'_> { prot: mmu::Prot, cpu: CpuMap, ) -> Result { - KernelObject::new( - self.dev, + self.object( self.uat.kernel_lower_vm(), Placement::In(self.uat.kernel_lower_dynamic_range(), align), size, @@ -459,7 +507,7 @@ impl Allocator<'_> { if size == 0 || size % mmu::UAT_PGSZ != 0 { return Err(EINVAL); } - let mut object = KernelObject::backing(self.dev, size, cpu)?; + let mut object = self.backing(size, cpu)?; let mut range = self.uat.kernel_lower_dynamic_range(); let mut searching = false; loop { @@ -830,6 +878,8 @@ impl Pool { for (index, entry) in inner.returned[begin..begin + POOL_SLOTS].iter().enumerate() { let Some(entry) = entry.as_ref().filter(|entry| { !entry.poisoned + && alloc.client.is_none() + && entry.object.charge.is_none() && entry.object.size() == size && entry.prefix == prefix && entry.cpu == cpu @@ -900,7 +950,10 @@ impl Pool { result.defer = Some(self.clone()); return Ok(result); } - if prefix == 0 { + // Converted mappings can retain firmware cache state until processor stop. + // Keep client pages uncached so a release witness suffices to unmap them + // and drop both their ledger charge and their physical memcg charge. + if prefix == 0 || alloc.client.is_some() { return Ok(result); } let (proof, mutated) = match result.mapping.as_ref() { @@ -977,6 +1030,8 @@ impl Pool { order, fence, }); + drop(inner); + self.reap_deferred(super::channel::control_witnessed()); return; } } @@ -1047,7 +1102,18 @@ impl Pool { } /// Unmaps the deferred objects whose fence the firmware has met. - fn reap_deferred(&self, witnessed: u64) { + pub(super) fn reap_deferred(&self, witnessed: u64) { + loop { + let mut inner = self.inner.lock(); + let Some(index) = inner.returned.iter().position(|slot| { + slot.as_ref().is_some_and(|entry| entry.object.charge.is_some() && entry.ready(witnessed)) + }) else { break }; + let entry = inner.returned[index].take().unwrap(); + inner.reserved[index / POOL_SLOTS] -= 1; + inner.bytes -= entry.object.size(); + drop(inner); + drop(entry); + } loop { let entry = { let mut inner = self.inner.lock(); diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 0b26a25b36f11..5c2ffbfd0d9b6 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -6,6 +6,7 @@ pub(crate) mod exit; mod activation; mod configuration; +pub(crate) mod reserve; pub(crate) mod retirement; use crate::g17::{ @@ -77,9 +78,35 @@ static_assert!(core::mem::offset_of!(GraphLayout, items) == ITEMS); /// mutex. Field order drops each client alias before the storage it names. pub(crate) struct Vacated { _alias: Option, - _pages: Option, + pages: Option, _descriptors: Option, - _ring: Option, + ring: Option, + /// A spare kit freed with the rest. + _kit: Option, + /// The owner whose backing the pages and ring are, which they go back to while it has + /// compute commands ([`reserve`]). + owner: Option, +} + +impl Vacated { + /// Spare backing to free off the device mutex. + pub(crate) fn spares(pages: Option, ring: Option, + kit: Option) -> Self { + Self { _alias: None, pages, _descriptors: None, ring, _kit: kit, owner: None } + } + /// The owner the pages and ring go back to. + pub(crate) fn returns_to(&self) -> Option { + self.owner + } + /// The pages and ring, to keep for their owner. Whatever is put back is freed with the rest. + pub(crate) fn backing(&mut self) -> (&mut Option, &mut Option) { + (&mut self.pages, &mut self.ring) + } + /// Drops the client views of the backing now. + pub(crate) fn drop_aliases(&mut self) { + drop(self._alias.take()); + drop(self._descriptors.take()); + } } pub(crate) struct Binding { @@ -135,6 +162,13 @@ impl DescriptorRing { )?; Ok(Self { low, object }) } + + /// Clears the ring for its owner's next queue, as the pool clears a reused object. The caller + /// has seen the firmware consume the release of the queue that held it. + pub(crate) fn clear(&mut self) { + self.object.bytes_mut().fill(0); + fence(Ordering::SeqCst); + } } /// Firmware-shared storage of one compute QID, separate from its common kick ring. @@ -168,17 +202,27 @@ struct Graph { mcache: bool, } -impl Graph { +/// The firmware-shared objects of one compute QID but its descriptor ring, allocated before a +/// QID is reserved for them. None names an owner yet. +pub(crate) struct GraphObjects { + preempt: KernelObject, + usage: KernelObject, + operand: KernelObject, + support: KernelObject, + m5_timestamps: Option>, + graph: KernelObject, + context_low: Option, + context_high: Option, + records: KernelObject, + cached_records: PooledObject, +} + +impl GraphObjects { fn new( alloc: &Allocator<'_>, objects: &Arc, - context: &Context, - pointers: PointerLayout, operand_state: &'static OperandState, - board: Option<&'static Board>, - program: ComputeProgram, m5: bool, - mcache: bool, ) -> Result { let page = mmu::UAT_PGSZ as u64; // The kernel's mappings of the queue's records sit in the upper half, which every @@ -188,7 +232,6 @@ impl Graph { // The kernel lower VM is context 0's alone. let lower = mmu::PROT_GPU_FW_SHARED_RW; let cpu = CpuMap::WriteCombined; - let ring = DescriptorRing::new(alloc, objects)?; let preempt = alloc.kernel(0x4000, page, prot, cpu)?; let usage = alloc.kernel(mmu::UAT_PGSZ, page, prot, cpu)?; let operand = alloc.lower(operand_state.size, page, lower, cpu)?; @@ -209,7 +252,34 @@ impl Graph { // so dirty firmware lines would revert host updates. An installed // compute graph lives until firmware stop and does not need the reuse // pool. - let mut graph = alloc.kernel(GRAPH_SIZE + mmu::UAT_PGSZ, page, prot, cpu)?; + let graph = alloc.kernel(GRAPH_SIZE + mmu::UAT_PGSZ, page, prot, cpu)?; + let (context_low, context_high) = if m5 { (None, None) } else { + (Some(alloc.lower(CONTEXT_SIZE, page, lower, cpu)?), + Some(alloc.kernel(CONTEXT_SIZE, page, prot, cpu)?)) + }; + let records = alloc.kernel(RECORD_SLOTS * RECORD_STRIDE, page, prot, cpu)?; + let m5_timestamps = if m5 { + Some(Arc::new(alloc.kernel(RECORD_SLOTS * 16, page, mmu::PROT_GPU_FW_SHARED_RW, cpu)?, + GFP_KERNEL)?) + } else { None }; + let cached_records = objects.allocate( + alloc, + Family::QueueConfig, + RECORD_SLOTS * CACHED_RECORD_STRIDE, + RECORD_SLOTS * CACHED_RECORD_STRIDE, + prot, + cpu, + )?; + Ok(Self { + preempt, usage, operand, support, m5_timestamps, graph, context_low, context_high, + records, cached_records, + }) + } +} + +impl Graph { + /// Writes `context`'s queue record into `objects`: stores only. + fn initialize(graph: &mut KernelObject, context: &Context, pointers: PointerLayout, m5: bool) -> Result { let graph_va = graph.gpu_va(); graph.initialize::(0, |view| { view.pointers = PointerBlock::new(&pointers)?; @@ -235,24 +305,24 @@ impl Graph { } else { graph.write(0, QueueRecord::new(&record))?; } - let (context_low, context_high) = if m5 { (None, None) } else { - (Some(alloc.lower(CONTEXT_SIZE, page, lower, cpu)?), - Some(alloc.kernel(CONTEXT_SIZE, page, prot, cpu)?)) - }; - let records = alloc.kernel(RECORD_SLOTS * RECORD_STRIDE, page, prot, cpu)?; - let m5_timestamps = if m5 { - Some(Arc::new(alloc.kernel(RECORD_SLOTS * 16, page, mmu::PROT_GPU_FW_SHARED_RW, cpu)?, - GFP_KERNEL)?) - } else { None }; - let cached_records = objects.allocate( - alloc, - Family::QueueConfig, - RECORD_SLOTS * CACHED_RECORD_STRIDE, - RECORD_SLOTS * CACHED_RECORD_STRIDE, - prot, - cpu, - )?; - Ok(Self { + Ok(()) + } + + fn new( + objects: GraphObjects, + ring: DescriptorRing, + pointers: PointerLayout, + operand_state: &'static OperandState, + board: Option<&'static Board>, + program: ComputeProgram, + m5: bool, + mcache: bool, + ) -> Self { + let GraphObjects { + preempt, usage, operand, support, m5_timestamps, graph, context_low, context_high, + records, cached_records, + } = objects; + Self { m5, ring: Some(ring), preempt, @@ -272,7 +342,7 @@ impl Graph { board, program, mcache, - }) + } } /// All fallible mapping work finishes before replacing a physical queue's logical owner. @@ -281,23 +351,32 @@ impl Graph { context: Arc, kick_alias: mmu::KernelMapping, pool_alias: Option, + ) -> Result { + Self::map_binding( + self.m5, self.ring.as_ref().ok_or(EAGAIN)?, &self.preempt, &self.usage, + &self.operand, self.context_low.as_ref(), context, kick_alias, pool_alias, + ) + } + + fn map_binding( + m5: bool, ring: &DescriptorRing, preempt: &KernelObject, usage: &KernelObject, + operand: &KernelObject, context_low: Option<&KernelObject>, context: Arc, + kick_alias: mmu::KernelMapping, pool_alias: Option, ) -> Result { if !context.is_current() { return Err(EFAULT); } let vm = context.vm(); - let descriptors = self.descriptor_alias(vm)?; - let prot = if self.m5 { mmu::PROT_GPU_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }; + let descriptors = ring.object.map_alias(vm, ring.low.iova(), mmu::PROT_GPU_SHARED_RO)?; + let prot = if m5 { mmu::PROT_GPU_SHARED_RW } else { mmu::PROT_GPU_FW_SHARED_RW }; let page = mmu::UAT_PGSZ as u64; let private = vm.client_private_range(); - let preempt = self - .preempt + let preempt = preempt .alias_in(vm, private.clone(), page, prot)?; - let usage = self.usage.alias_in(vm, private.clone(), page, prot)?; - let operand = self - .operand + let usage = usage.alias_in(vm, private.clone(), page, prot)?; + let operand = operand .alias_in(vm, private.clone(), page, prot)?; - let queue_context = self.context_low.as_ref() + let queue_context = context_low .map(|context| context.alias_in(vm, private.clone(), page, prot)).transpose()?; Ok(Binding { _kick_alias: kick_alias, @@ -595,39 +674,34 @@ struct ConfigIdentity { context: u32, } -/// A private physical pool whose descriptor row is installed before allocating its kick ring. -/// The QID remains unpublished throughout construction. -pub(crate) struct PoolBacking { - pool: ComputePool, - id: kick::Id, +/// Everything a fresh compute queue needs but its pool pages and descriptor ring: the pool's +/// control and state, the kick ring and the graph's objects. Allocated before a QID is reserved +/// for it; [`Queue::new_channel`] binds it to one with stores only. Device memory: an installed +/// queue keeps it until processor stop, past its first owner. +pub(crate) struct Kit { + pool: crate::g17::freelist::PoolObjects, + kick: kick::ComputeRing, + graph: GraphObjects, } -impl PoolBacking { - pub(crate) fn new(alloc: &Allocator<'_>, id: kick::Id, required: ComputeCapacity, - client: Option<&Arc>) -> Result { - let pool = ComputePool::new(alloc, id.qid(), required, client)?; - Ok(Self { pool, id }) - } - - /// Fresh page-pool row data, installed once while the QID is still unpublished. - pub(crate) fn pool_descriptor(&self) -> Result { - self.pool.descriptor() +impl Kit { + pub(crate) fn new( + alloc: &Allocator<'_>, + objects: &Arc, + operand_state: &'static OperandState, + m5: bool, + ) -> Result { + Ok(Self { + pool: crate::g17::freelist::PoolObjects::new(alloc)?, + kick: kick::ComputeRing::new(alloc)?, + graph: GraphObjects::new(alloc, objects, operand_state, m5)?, + }) } } -/// A physical pool and kick ring prepared before the device-global compute scheduler and -/// descriptor graph. No logical VM aliases or firmware publication exist at this stage. -pub(crate) struct Backing { - pool: ComputePool, - kick: kick::Queue, -} - -impl Backing { - pub(crate) fn new(alloc: &Allocator<'_>, backing: PoolBacking) -> Result { - let PoolBacking { pool, id } = backing; - let kick = kick::Queue::compute(alloc, id)?; - Ok(Self { pool, kick }) - } +/// The page-pool row of a fresh queue's pool at QID `qid`, installed before the queue is built. +pub(crate) fn pool_descriptor(pages: &crate::g17::freelist::Pages, qid: u8) -> Result { + pages.descriptor(ComputePool::slot(qid)) } /// Installed graph and its exact logical owner. A released idle graph may change owners only @@ -717,6 +791,9 @@ pub(crate) struct Queue { /// The owner re-arming this vacant queue: only it builds the fresh backing, so concurrent /// waiters do not each build a pool for the same queue. rearm_for: Option, + /// The owner whose compute backing (pool pages, descriptor ring) this queue holds: it goes + /// back to that owner when the queue gives it back. None once the owner closed. + backing_owner: Option, configuration: Option, m5_install: Option, /// Bit `p` set once a work slot of priority class `p` named this queue. @@ -756,44 +833,14 @@ pub(crate) struct Queue { impl Queue { /// The caller reserves a QID first, cancels it on construction failure, and retains every /// successfully installed queue until processor stop. Shared VM apertures precede this call. - pub(crate) fn new( - alloc: &Allocator<'_>, - objects: &Arc, - backing: Backing, - owner: u64, - context: Arc, - pointers: PointerLayout, - operand_state: &'static OperandState, - board: Option<&'static Board>, - program: ComputeProgram, - m5: bool, - mcache: bool, - ) -> Result { - Self::new_channel( - alloc, - objects, - backing, - owner, - context, - pointers, - operand_state, - board, - program, - m5, - mcache, - 0, - ) - } - #[expect( clippy::too_many_arguments, reason = "A sibling compute queue takes the same physical graph inputs plus its channel \ identity." )] pub(crate) fn new_channel( - alloc: &Allocator<'_>, - objects: &Arc, - backing: Backing, + backing: &mut Option<(Kit, crate::g17::freelist::Pages, DescriptorRing)>, + id: kick::Id, owner: u64, context: Arc, pointers: PointerLayout, @@ -803,19 +850,33 @@ impl Queue { m5: bool, mcache: bool, channel_index: u8, - ) -> Result { - let Backing { mut pool, mut kick } = backing; + install_row: impl FnOnce(PoolDescriptor) -> Result, + ) -> Result> { + let (kit, pages, ring) = backing.as_mut().ok_or(ENOSPC)?; + if id.engine() != DataMaster::Compute { return Err(EINVAL); } + let boxed = KBox::::new_uninit(GFP_KERNEL)?; let (active, replays) = (Fifo::new()?, Fifo::new()?); let pending_failed = KVec::with_capacity(IN_FLIGHT, GFP_KERNEL)?; - let mut graph = - Graph::new(alloc, objects, &context, pointers, operand_state, board, program, m5, mcache)?; - let kick_alias = kick.map_client(context.vm())?; - let pool_alias = Some(pool.map_client(context.vm())?); - let binding = graph.bind(context.clone(), kick_alias, pool_alias)?; + let source_readers = Arc::new(core::sync::atomic::AtomicU32::new(0), GFP_KERNEL)?; + ComputePool::prepare(&mut kit.pool, id.qid(), pages)?; + Graph::initialize(&mut kit.graph.graph, &context, pointers, m5)?; + let kick_alias = kit.kick.map_client(context.vm())?; + let pool_alias = Some(pages.map_client(context.vm())?); + let binding = Graph::map_binding( + m5, ring, &kit.graph.preempt, &kit.graph.usage, &kit.graph.operand, + kit.graph.context_low.as_ref(), context.clone(), kick_alias, pool_alias, + )?; + // Until the row is visible a failure returns the original backing to + // its owner. Every remaining step is an infallible ownership transfer. + install_row(pool_descriptor(pages, id.qid())?)?; + let (kit, pages, ring) = backing.take().expect("borrowed fresh backing"); + let pool = ComputePool::bind(kit.pool, id.qid(), pages, context.vm().id()); + let kick = kick::Queue::compute(kit.kick, id); + let graph = Graph::new(kit.graph, ring, pointers, operand_state, board, program, m5, mcache); context.mark_published(); context.note_compute_binding(true); crate::g17::trace::bind(crate::g17::trace::COMPUTE, kick.id().qid(), context.id(), 0); - Ok(Self { + Ok(boxed.write(Self { owner: Some(owner), channel_index, binding_noted: true, @@ -846,6 +907,7 @@ impl Queue { kill_wait: None, installed: false, rearm_for: None, + backing_owner: Some(owner), configuration: None, m5_install: None, outer_started: 0, @@ -870,9 +932,9 @@ impl Queue { quarantine_error: None, failure_status_pending: false, retirement_proved: false, - source_readers: Arc::new(core::sync::atomic::AtomicU32::new(0), GFP_KERNEL)?, + source_readers, source_hint: crate::g17::sync_input::ReaderHint::new(), - }) + })) } /// The firmware failed the command whose completion stamp is `stamp`. It writes a /// zero-duration completion record for it, which quarantines the queue, but stores no @@ -2058,6 +2120,41 @@ impl Queue { pub(crate) fn bind_owner(&mut self, owner: u64, context: Arc) -> Result { self.bind_owner_channel(owner, context, 0) } + /// The owner whose compute backing this queue holds. + pub(crate) fn backing_owner(&self) -> Option { + self.backing_owner + } + /// Only the provisioning owner can retain the charged pages and ring across a rebind. + pub(crate) fn backing_free_for(&self, owner: u64) -> bool { + self.backing_owner == Some(owner) + } + /// Whether the pool pages this queue holds, given back or not, serve `required`. + pub(crate) fn backing_fits(&self, required: ComputeCapacity) -> bool { + self.pool.fits_capacity(required) + } + /// `owner` closed: its backing here is no longer kept for it. + pub(crate) fn untag_backing(&mut self, owner: u64) { + if self.backing_owner == Some(owner) { + self.backing_owner = None; + } + } + /// Takes the backing of a queue that was never published, before the queue is dropped, so + /// that it goes back to its owner. + pub(crate) fn take_backing(&mut self) -> Vacated { + let binding = self.binding.as_mut(); + let (alias, descriptors) = match binding { + Some(binding) => (binding.pool_alias.take(), binding.descriptors.take()), + None => (None, None), + }; + Vacated { + _alias: alias, + pages: self.pool.take_pages(), + _descriptors: descriptors, + ring: self.graph.vacate_ring(), + _kit: None, + owner: self.backing_owner.take(), + } + } /// Binds a reusable physical queue with its own dedicated compute pool as an additional /// compute channel of `owner`. pub(crate) fn bind_sibling( @@ -2077,7 +2174,7 @@ impl Queue { context: Arc, channel_index: u8, ) -> Result { - if !self.reusable() { + if !self.reusable() || !self.backing_free_for(owner) { return Err(EBUSY); } self.source_hint.reset_for_owner(&self.source_readers)?; @@ -2160,6 +2257,10 @@ impl Queue { if same_vm { 2 } else { 1 }, ); self.owner = Some(owner); + // A closed owner's backing is the binding owner's from now on. + if self.pool.populated() { + self.backing_owner.get_or_insert(owner); + } self.channel_index = channel_index; self.heavy_run = 0; self.rearm_for = None; @@ -2251,9 +2352,11 @@ impl Queue { let ring = self.graph.vacate_ring(); Some(Vacated { _alias: None, - _pages: None, + pages: None, _descriptors: descriptors, - _ring: ring, + ring, + _kit: None, + owner: self.backing_owner.take(), }) } /// An idle retained queue whose USC backing may be given back. @@ -2438,9 +2541,11 @@ impl Queue { self.release_sent_ns = None; Ok(Some(Vacated { _alias: alias, - _pages: pages, + pages, _descriptors: descriptors, - _ring: ring, + ring, + _kit: None, + owner: self.backing_owner.take(), })) } /// Installs fresh backing into a vacant pool; returns the descriptor row data @@ -2448,6 +2553,7 @@ impl Queue { /// ring to drop off-lock. pub(crate) fn rearm( &mut self, + owner: u64, pages: crate::g17::freelist::Pages, ring: DescriptorRing, ) -> Result<(PoolDescriptor, Option)> { @@ -2473,10 +2579,13 @@ impl Queue { self.needs_fresh_backing = false; let vacated = (old_ring.is_some() || descriptors.is_some()).then_some(Vacated { _alias: None, - _pages: None, + pages: None, _descriptors: descriptors, - _ring: old_ring, + ring: old_ring, + _kit: None, + owner: self.backing_owner, }); + self.backing_owner = Some(owner); Ok((self.pool.descriptor()?, vacated)) } pub(crate) fn pool_fits(&self, required: ComputeCapacity) -> bool { @@ -2551,11 +2660,15 @@ impl Queue { self.release_sent_ns = None; self.growing = false; self.growth = None; + let owner = self.backing_owner; + self.backing_owner = self.owner; Ok(Vacated { _alias: old_alias, - _pages: pages.take(), + pages: pages.take(), _descriptors: None, - _ring: None, + ring: None, + _kit: None, + owner, }) } diff --git a/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs new file mode 100644 index 0000000000000..c0b323b35aec2 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! The spare compute backing of one logical queue (owner). +//! +//! An owner's compute sets (pool pages and a descriptor ring) are allocated in its SUBMIT ioctl, +//! charged to its client, and are its own until it closes: a physical queue holds one while the +//! owner is bound to it, and gives it back here when the queue is taken from the owner. A +//! publication takes from here and never allocates. A fresh queue also takes a [`Kit`] from here. +//! +//! [`Kit`]: super::Kit + +use crate::g17::freelist::ComputeCapacity; +use kernel::prelude::*; + +/// Spare pages an owner keeps at most: with more, one is covered by another (pages of one family +/// are ordered by size, and M5 has two block sizes), and the covered one is freed. +const PAGES: usize = 4; +/// Spare descriptor rings an owner keeps at most: one for each compute channel it may hold. +const RINGS: usize = crate::g17::pairs::COMPUTE_CHANNELS_MAX; + +/// Pool pages as a spare: what they can serve. +pub(crate) trait Capacity { + /// Whether these pages serve `required`. + fn fits(&self, required: ComputeCapacity) -> bool; + /// Whether these pages serve everything `other` serves. + fn covers(&self, other: &Self) -> bool; +} + +/// The spares of one owner: pages, descriptor rings and at most one kit. +pub(crate) struct Spares { + pages: [Option

; PAGES], + rings: [Option; RINGS], + kit: Option, +} + +impl Spares { + pub(crate) fn new() -> Self { + Self { pages: Default::default(), rings: Default::default(), kit: None } + } + + /// Whether spare pages serve `required`. + pub(crate) fn fits(&self, required: ComputeCapacity) -> bool { + self.pages.iter().flatten().any(|pages| pages.fits(required)) + } + + pub(crate) fn has_ring(&self) -> bool { + self.rings.iter().any(Option::is_some) + } + + pub(crate) fn has_kit(&self) -> bool { + self.kit.is_some() + } + + /// Whether nothing is spare. + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn is_empty(&self) -> bool { + self.pages.iter().all(Option::is_none) && !self.has_ring() && self.kit.is_none() + } + + /// The smallest spare pages that serve `required`: larger ones stay for larger needs. + pub(crate) fn take_pages(&mut self, required: ComputeCapacity) -> Option

{ + let pages = &self.pages; + let index = (0..PAGES) + .filter(|&i| pages[i].as_ref().is_some_and(|p| p.fits(required))) + .min_by(|&a, &b| { + let (a, b) = (pages[a].as_ref(), pages[b].as_ref()); + match (a, b) { + (Some(a), Some(b)) if b.covers(a) && !a.covers(b) => core::cmp::Ordering::Less, + (Some(a), Some(b)) if a.covers(b) && !b.covers(a) => core::cmp::Ordering::Greater, + _ => core::cmp::Ordering::Equal, + } + })?; + self.pages[index].take() + } + + pub(crate) fn take_ring(&mut self) -> Option { + self.rings.iter_mut().find_map(Option::take) + } + + pub(crate) fn take_kit(&mut self) -> Option { + self.kit.take() + } + + /// Keeps `pages`; returns what to free instead: nothing while a slot is free, else spare + /// pages another spare (or `pages`) covers, else `pages` itself. + pub(crate) fn put_pages(&mut self, pages: P) -> Option

{ + if let Some(slot) = self.pages.iter_mut().find(|slot| slot.is_none()) { + *slot = Some(pages); + return None; + } + let covered = |i: usize| { + let Some(candidate) = self.pages[i].as_ref() else { return false }; + pages.covers(candidate) + || (0..PAGES).any(|j| j != i && self.pages[j].as_ref().is_some_and(|p| p.covers(candidate))) + }; + match (0..PAGES).find(|&i| covered(i)) { + Some(i) => self.pages[i].replace(pages), + None => Some(pages), + } + } + + /// Keeps `ring`; returns it if every slot is taken. + pub(crate) fn put_ring(&mut self, ring: R) -> Option { + match self.rings.iter_mut().find(|slot| slot.is_none()) { + Some(slot) => { + *slot = Some(ring); + None + } + None => Some(ring), + } + } + + /// Keeps `kit`; returns it if one is kept already. + pub(crate) fn put_kit(&mut self, kit: K) -> Option { + if self.kit.is_some() { + return Some(kit); + } + self.kit = Some(kit); + None + } + + /// Takes some spares out, for freeing: one each of pages, ring and kit at most. None once + /// nothing is spare. + #[allow(clippy::type_complexity)] + pub(crate) fn take_any(&mut self) -> Option<(Option

, Option, Option)> { + let item = (self.pages.iter_mut().find_map(Option::take), self.take_ring(), self.kit.take()); + (item.0.is_some() || item.1.is_some() || item.2.is_some()).then_some(item) + } + + /// Takes everything out, for freeing. + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn take_all(&mut self) -> Self { + core::mem::replace(self, Self::new()) + } +} + +#[kunit_tests(asahi_g17_compute_reserve)] +mod tests { + use super::*; + use core::sync::atomic::{AtomicUsize, Ordering}; + + /// Test items freed so far. KUnit runs a suite's cases one after another. + static FREED: AtomicUsize = AtomicUsize::new(0); + + /// Pages of `0` blocks; `1` tells sizes that do not compare apart (M5's two block sizes). + struct Pages(usize, u8); + impl Drop for Pages { + fn drop(&mut self) { + FREED.fetch_add(1, Ordering::Relaxed); + } + } + impl Capacity for Pages { + fn fits(&self, required: ComputeCapacity) -> bool { + matches!(required, ComputeCapacity::Blocks(blocks) if self.1 == 0 && self.0 >= blocks) + } + fn covers(&self, other: &Self) -> bool { + self.1 == other.1 && self.0 >= other.0 + } + } + struct Ring; + impl Drop for Ring { + fn drop(&mut self) { + FREED.fetch_add(1, Ordering::Relaxed); + } + } + struct Kit; + impl Drop for Kit { + fn drop(&mut self) { + FREED.fetch_add(1, Ordering::Relaxed); + } + } + type Test = Spares; + + fn freed() -> usize { + FREED.load(Ordering::Relaxed) + } + + #[test] + fn moving_spares_frees_nothing() { + let before = freed(); + let mut spares = Test::new(); + assert!(spares.is_empty()); + assert!(spares.put_pages(Pages(21, 0)).is_none()); + assert!(spares.put_ring(Ring).is_none()); + assert!(spares.put_kit(Kit).is_none()); + assert!(spares.fits(ComputeCapacity::Blocks(21)) && spares.has_ring() && spares.has_kit()); + assert!(!spares.fits(ComputeCapacity::Blocks(22))); + let (pages, ring, kit) = (spares.take_pages(ComputeCapacity::Blocks(21)), spares.take_ring(), + spares.take_kit()); + assert!(pages.is_some() && ring.is_some() && kit.is_some()); + assert!(spares.is_empty()); + // Back again, as a queue taken from its owner gives them back: still nothing freed. + assert!(spares.put_pages(pages.unwrap()).is_none()); + assert!(spares.put_ring(ring.unwrap()).is_none()); + assert!(spares.put_kit(kit.unwrap()).is_none()); + assert_eq!(freed(), before); + drop(spares); + // Each spare is freed once. + assert_eq!(freed(), before + 3); + } + + #[test] + fn the_smallest_fitting_pages_are_taken() { + let mut spares = Test::new(); + for blocks in [30, 21, 24] { + assert!(spares.put_pages(Pages(blocks, 0)).is_none()); + } + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(22)).map(|p| p.0), Some(24)); + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(31)).map(|p| p.0), None); + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(21)).map(|p| p.0), Some(21)); + assert_eq!(spares.take_pages(ComputeCapacity::Blocks(21)).map(|p| p.0), Some(30)); + assert!(spares.is_empty()); + } + + #[test] + fn a_full_owner_frees_only_covered_pages() { + let mut spares = Test::new(); + // Two sizes that do not compare apart, two of each. + for pages in [Pages(21, 0), Pages(21, 1), Pages(24, 1), Pages(30, 0)] { + assert!(spares.put_pages(pages).is_none()); + } + // Full: a covered spare goes, never one that serves a need nothing else serves. + let freed = spares.put_pages(Pages(40, 0)).unwrap(); + // Never one that serves a need nothing else serves. + assert!(freed.1 == 0 || freed.0 == 21); + assert!(spares.fits(ComputeCapacity::Blocks(40))); + // Pages a spare covers are themselves what goes. + let freed = spares.put_pages(Pages(21, 1)).unwrap(); + assert_eq!((freed.0, freed.1), (21, 1)); + assert!(spares.put_ring(Ring).is_none() && spares.put_ring(Ring).is_none() + && spares.put_ring(Ring).is_none()); + // Rings beyond the channels are freed. + assert!(spares.put_ring(Ring).is_some()); + assert!(spares.put_kit(Kit).is_none() && spares.put_kit(Kit).is_some()); + } + + #[test] + fn taking_all_frees_each_spare_once() { + let mut spares = Test::new(); + assert!(spares.put_pages(Pages(21, 0)).is_none()); + assert!(spares.put_ring(Ring).is_none()); + let before = freed(); + let all = spares.take_all(); + assert!(spares.is_empty()); + assert_eq!(freed(), before); + drop(all); + assert_eq!(freed(), before + 2); + drop(spares); + assert_eq!(freed(), before + 2); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index fa089b3a49030..2e0ce042ff18a 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -267,6 +267,10 @@ impl Queue { } self.prune_frontier(index); self.prune_frontier(other); + // Claimed before the SUBMIT provisions this command's compute backing, so nothing it was + // given back for it is freed before the command is dropped. + let claim = (engine == Engine::Compute) + .then(|| super::context::ComputeClaim::new(&self.context)); if engine == Engine::Compute { self.ensure_compute(&command)?; } @@ -469,6 +473,7 @@ impl Queue { batch_renders, checked_inputs, producers, + claim, )?; let scheduler = match engine { Engine::Render => &mut self.render, diff --git a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs index b2848b35b418b..33ef37d497f03 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/generation.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/generation.rs @@ -104,8 +104,7 @@ impl Generation { let (placement, layout) = if alloc.uat.is_m5() { (PairObject::SlotState.placement()?, Layout::m5(board.ok_or(EINVAL)?)) } else { (Placement::In(vm.client_private_range(), cfg::TVB_PAGE), Layout::NEO) }; - KernelObject::new(alloc.dev, vm, placement, layout.bytes, - mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined) + alloc.object(vm, placement, layout.bytes, mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined) } #[inline(never)] diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index 921577f322bb0..5a9392651614a 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -342,7 +342,7 @@ impl Compact { /// M5: a shared-RW object of `size` bytes mapped in the client's compact window as `object`. fn m5(alloc: &Allocator<'_>, vm: &mmu::Vm, object: PairObject, size: usize) -> Result { let size = size.checked_next_multiple_of(mmu::UAT_PGSZ).ok_or(EOVERFLOW)?; - let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; + let backing = alloc.backing(size, CpuMap::WriteCombined)?; let mapping = object.map(&backing, vm, 0..size, mmu::PROT_GPU_SHARED_RW)?; Ok(Self { address: mapping.iova(), mapping: Some(mapping), _backing: backing }) } @@ -351,7 +351,7 @@ impl Compact { if alloc.uat.is_m5() { return Err(EINVAL); } - let backing = KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)?; + let backing = alloc.backing(size, CpuMap::WriteCombined)?; let mapping = buffer::compact_alias( &backing, vm, @@ -432,8 +432,7 @@ pub(super) struct NeoGeneration { } impl NeoGeneration { fn allocate_state(alloc: &Allocator<'_>, vm: &mmu::Vm) -> Result { - KernelObject::new( - alloc.dev, + alloc.object( vm, crate::g17::object::Placement::In(vm.client_private_range(), cfg::TVB_PAGE), storage::STATE_SIZE, @@ -637,8 +636,7 @@ impl Memory { ) })?; } - let registers = if m5 { None } else { Some(KernelObject::new( - alloc.dev, + let registers = if m5 { None } else { Some(alloc.object( vm, crate::g17::object::Placement::In(vm.client_private_range(), mmu::UAT_PGSZ as u64), mmu::UAT_PGSZ, diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index de80ebe197537..ee4dd581eda10 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -255,6 +255,61 @@ impl Drop for ComputeSlot { } } +/// A logical queue's spare compute backing ([`compute::reserve`]): pool pages and descriptor rings +/// charged to its client, and a kit of device memory for a fresh queue. +pub(super) struct OwnerReserve { + owner: u64, + context: Arc, + spares: compute::reserve::Spares, + /// A sibling channel found no backing: the next SUBMIT provisions some, if it can. + wants_sibling: bool, +} + +impl OwnerReserve { + pub(super) fn new(owner: u64, context: Arc) -> Self { + Self { owner, context, spares: compute::reserve::Spares::new(), wants_sibling: false } + } +} + +/// What an owner's publication at some capacity would lack ([`Registry::compute_lacks`]). +#[derive(Clone, Copy, Default)] +pub(super) struct Lacks { + pages: bool, + ring: bool, + kit: bool, + /// A sibling's backing, provisioned if it can be. + sibling: bool, +} + +impl Lacks { + fn any(&self) -> bool { + self.pages || self.ring || self.kit || self.sibling + } +} + +/// Keeps the pages and ring a queue gave back for their owner while it has compute commands +/// ([`Context::compute_claimed`]); what is not kept stays in `vacated`, to be freed with it. An +/// owner without commands is idle: its backing is freed, as before it had a reserve. +fn keep_backing(reserves: &mut KVec>, vacated: &mut compute::Vacated) { + let Some(owner) = vacated.returns_to() else { return }; + let Some(reserve) = reserves.iter_mut().find(|reserve| reserve.owner == owner) else { return }; + if !reserve.context.compute_claimed() { + return; + } + let (pages, ring) = vacated.backing(); + if let Some(mut returned) = pages.take() { + // Unreset tables would hand the firmware the old free list. + *pages = match returned.reset() { + Ok(()) => reserve.spares.put_pages(returned), + Err(_) => Some(returned), + }; + } + if let Some(mut returned) = ring.take() { + returned.clear(); + *ring = reserve.spares.put_ring(returned); + } +} + pub(super) struct Registry { pub(super) qids: kick::QueueIds, pub(super) buffers: BufferIds, @@ -264,8 +319,14 @@ pub(super) struct Registry { render: render::RenderState, identities: queue::Identities, compute: KVec>, - pub(super) compute_building: bool, - compute_scheduler_building: bool, + /// G17P's device-wide compute aperture and scheduler, allocated by a compute SUBMIT while + /// not installed ([`Backend::provision_compute`]) and installed by the first publication that + /// needs them: a publication never allocates them. + prepared_shared: Option, + prepared_scheduler: Option, + /// The spare compute backing of each logical queue that submitted compute work, from its + /// first compute SUBMIT until it closes ([`compute::reserve`]). + reserves: KVec>, replay_outer_wait: Option, /// A compute replay waits for its owner's renders to park or idle (compute_replay). replay_consumer_wait: Option, @@ -317,8 +378,9 @@ impl Registry { } compute }, - compute_building: false, - compute_scheduler_building: false, + prepared_shared: None, + prepared_scheduler: None, + reserves: KVec::with_capacity(kick::queue_limit(variant.qid_floor) as usize, GFP_KERNEL)?, replay_outer_wait: None, replay_consumer_wait: None, observations: compute::retirement::Batch::new()?, @@ -432,7 +494,7 @@ impl Registry { continue; } &mut vacant - } else if queue.pool_serves(vm) { + } else if queue.pool_serves(vm) && queue.backing_free_for(owner) { if queue.needs_fresh_backing() || !queue.pool_fits(required) || !queue.has_ring() { continue; } @@ -561,6 +623,162 @@ impl Registry { Ok(()) } + fn owner_reserve(&mut self, owner: u64) -> Option<&mut OwnerReserve> { + self.reserves.iter_mut().find(|reserve| reserve.owner == owner).map(|reserve| &mut **reserve) + } + + fn spares(&self, owner: u64) -> Option<&compute::reserve::Spares> { + self.reserves.iter().find(|reserve| reserve.owner == owner).map(|reserve| &reserve.spares) + } + + /// What a publication of `owner` at `required` would lack: its spares, and the backing its + /// queues hold (also while they give it back), serve it otherwise. + pub(super) fn compute_lacks(&self, owner: u64, required: super::freelist::ComputeCapacity) -> Lacks { + let spares = self.spares(owner); + let queues = || self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()); + let held = || queues().filter(|queue| queue.backing_owner() == Some(owner)); + let pages = !spares.is_some_and(|spares| spares.fits(required)) + && !held().any(|queue| queue.backing_fits(required)); + let ring = !spares.is_some_and(|spares| spares.has_ring()) && !held().any(|queue| queue.has_ring()); + // A kit for an owner without a queue of its own: a QID that frees up later is built on + // without allocating. One with a queue gets a channel through an existing queue, which + // stays until processor stop. + let kit = !spares.is_some_and(|spares| spares.has_kit()) + && !queues().any(|queue| queue.backing_owner() == Some(owner) || queue.owner() == Some(owner)); + let sibling = self.reserves.iter().any(|reserve| reserve.owner == owner && reserve.wants_sibling); + Lacks { pages, ring, kit, sibling } + } + + /// Keeps what `owner`'s SUBMIT provisioned, in `reserve` if the owner has none yet. Returns + /// what is not kept, to free off the device mutex. + pub(super) fn stock( + &mut self, + owner: u64, + mut reserve: Option>, + pages: Option, + ring: Option, + kit: Option, + ) -> (compute::Vacated, Option>) { + if self.owner_reserve(owner).is_none() { + if let Some(new) = reserve.take() { + if let Err(rejected) = self.reserves.push_within_capacity(new) { + reserve = Some(rejected.0); + } + } + } + let Some(target) = self.owner_reserve(owner) else { + return (compute::Vacated::spares(pages, ring, kit), reserve); + }; + target.wants_sibling = false; + let pages = pages.and_then(|pages| target.spares.put_pages(pages)); + let ring = ring.and_then(|ring| target.spares.put_ring(ring)); + let kit = kit.and_then(|kit| target.spares.put_kit(kit)); + (compute::Vacated::spares(pages, ring, kit), reserve) + } + + /// Takes `owner`'s spare pages that serve `required` and a ring, for a queue it re-arms: + /// both or neither. + fn take_set(&mut self, owner: u64, required: super::freelist::ComputeCapacity) + -> Option<(super::freelist::Pages, compute::DescriptorRing)> { + let spares = &mut self.owner_reserve(owner)?.spares; + if !spares.fits(required) || !spares.has_ring() { + return None; + } + Some((spares.take_pages(required)?, spares.take_ring()?)) + } + + fn has_kit(&self, owner: u64) -> bool { + self.spares(owner).is_some_and(|spares| spares.has_kit()) + } + + /// Whether `owner`'s spares build a fresh queue at `required` ([`Self::take_fresh`]). + fn can_build_fresh(&self, owner: u64, required: super::freelist::ComputeCapacity) -> bool { + self.spares(owner) + .is_some_and(|spares| spares.has_kit() && spares.has_ring() && spares.fits(required)) + } + + fn take_fresh(&mut self, owner: u64, required: super::freelist::ComputeCapacity) + -> Option<(compute::Kit, super::freelist::Pages, compute::DescriptorRing)> { + if !self.can_build_fresh(owner, required) { + return None; + } + let spares = &mut self.owner_reserve(owner)?.spares; + Some((spares.take_kit()?, spares.take_pages(required)?, spares.take_ring()?)) + } + + fn take_pages(&mut self, owner: u64, required: super::freelist::ComputeCapacity) + -> Option { + self.owner_reserve(owner)?.spares.take_pages(required) + } + + /// Gives `owner` back what one of its publications took and did not use. Returns what is + /// not kept, to free off the device mutex. + fn put_back( + &mut self, + owner: u64, + pages: Option, + ring: Option, + kit: Option, + ) -> compute::Vacated { + match self.owner_reserve(owner) { + Some(reserve) => compute::Vacated::spares( + pages.and_then(|pages| reserve.spares.put_pages(pages)), + ring.and_then(|ring| reserve.spares.put_ring(ring)), + kit.and_then(|kit| reserve.spares.put_kit(kit)), + ), + None => compute::Vacated::spares(pages, ring, kit), + } + } + + /// A sibling channel of `owner` found no backing: its next SUBMIT provisions some. + fn want_sibling(&mut self, owner: u64) { + if let Some(reserve) = self.owner_reserve(owner) { + reserve.wants_sibling = true; + } + } + + /// Keeps what a queue gave back for its owner ([`keep_backing`]). + fn keep_returned(&mut self, vacated: &mut compute::Vacated) { + keep_backing(&mut self.reserves, vacated); + } + + /// Asks the idle queues holding `owner`'s backing that serves `required` to give it back: a + /// pool pass releases them, and the owner keeps the backing. Whether any does. + fn recall_backing(&mut self, owner: u64, required: super::freelist::ComputeCapacity) -> bool { + let mut recalled = false; + for mut queue in self.compute.iter_mut().flatten() + .filter_map(|entry| entry.queue.as_deref_mut()) + .filter(|queue| queue.backing_owner() == Some(owner) && queue.reusable() + && !queue.pool_vacant() && queue.backing_fits(required)) + { + queue.require_fresh_backing(); + recalled = true; + } + recalled + } + + /// `owner` closed: the backing its queues hold is no longer kept for it, and its spares are + /// returned, to be freed off the device mutex. + pub(super) fn close_reserve(&mut self, owner: u64) -> Option> { + for mut queue in self.compute.iter_mut().flatten().filter_map(|entry| entry.queue.as_deref_mut()) { + queue.untag_backing(owner); + } + let index = self.reserves.iter().position(|reserve| reserve.owner == owner)?; + Some(self.reserves.swap_remove(index)) + } + + /// The spares of owners without compute commands go to `deferred`, to be freed: an idle + /// owner's next SUBMIT provisions again. + fn trim_reserves(&mut self, deferred: &mut DeferredBatch) { + for reserve in self.reserves.iter_mut().filter(|reserve| !reserve.context.compute_claimed()) { + while deferred.vacated_room() { + let Some((pages, ring, kit)) = reserve.spares.take_any() else { break }; + deferred.defer_vacated(compute::Vacated::spares(pages, ring, kit)); + } + } + } + /// Picks the bound compute channel of `owner` for `packet`. A command with cross-queue input /// sources always takes the primary channel, so a chain of semaphore hops between queues /// stays on one ring per queue. Dependent commands stay on the sole active channel when only @@ -723,7 +941,8 @@ impl Registry { if let Some(rebind) = self.bind_reusable(owner, context, required, admission)? { return Ok(rebind); } - if self.compute_qid_fits() { + // A fresh queue is built from the kit the owner's SUBMIT provisioned. + if self.compute_qid_fits() && self.has_kit(owner) { return Ok(Rebind::Fresh); } if self.compute.iter().flatten().filter_map(|entry| entry.queue.as_deref()) @@ -740,7 +959,8 @@ impl Registry { .iter() .flatten() .filter_map(|entry| entry.queue.as_deref()) - .filter(|queue| queue.reusable() && !queue.pool_vacant() && !queue.pool_serves(vm)) + .filter(|queue| queue.reusable() && !queue.pool_vacant() + && (!queue.pool_serves(vm) || !queue.backing_free_for(owner))) .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound))) .map(|queue| (queue.released_at(), queue.qid())) .min_by_key(|(key, _)| *key) @@ -757,7 +977,8 @@ impl Registry { .filter(|queue| queue.shareable()) .filter(|queue| !queue.context().is_some_and(|bound| teardown.releasing(bound))) // A channel serving the requester's VM first, then the best fit, then the longest idle. - .map(|queue| ((!queue.pool_serves(vm), !queue.pool_fits(required), queue.last_published()), queue.qid())) + .map(|queue| ((!queue.pool_serves(vm) || !queue.backing_free_for(owner), + !queue.pool_fits(required), queue.last_published()), queue.qid())) .min_by_key(|(key, _)| *key) .map(|(_, qid)| qid); let Some(qid) = idle else { return Err(ENOSPC); }; @@ -773,8 +994,9 @@ impl Registry { if !queue.share_idle()? { return Err(ENOSPC); } - if !queue.pool_serves(vm) { - // Its backing holds another VM's scratch: vacate it, then re-arm fresh. + if !queue.pool_serves(vm) || !queue.backing_free_for(owner) { + // Its backing holds another VM's scratch, or another open owner's backing, + // which goes back to it: vacate it, then re-arm fresh. queue.require_fresh_backing(); return Err(ENOSPC); } @@ -858,7 +1080,11 @@ impl Registry { } continue; } - if !queue.pool_fits(required) || !queue.pool_serves(context.vm()) { continue; } + if !queue.pool_fits(required) || !queue.pool_serves(context.vm()) + || !queue.backing_free_for(owner) + { + continue; + } queue.bind_owner(owner, context.clone())?; return Ok(Some(Rebind::Done)); } @@ -878,6 +1104,7 @@ impl Registry { pub(super) fn rearm_compute( &mut self, qid: u8, + owner: u64, pages: crate::g17::freelist::Pages, ring: compute::DescriptorRing, ) -> Result<(super::freelist::PoolDescriptor, Option)> { @@ -888,7 +1115,7 @@ impl Registry { .filter_map(|entry| entry.queue.as_deref_mut()) .find(|queue| queue.qid() == qid) .ok_or(EAGAIN)?; - queue.rearm(pages, ring) + queue.rearm(owner, pages, ring) } /// Reserves the vacant queue `qid` for `owner`'s re-arm, as [`Self::bind_reusable`] does for a @@ -1028,7 +1255,8 @@ impl Registry { .filter_map(|entry| entry.queue.as_deref_mut()) { if !deferred.vacated_room() { break; } - if let Some(vacated) = queue.observe_vacancy(consumer, producer)? { + if let Some(mut vacated) = queue.observe_vacancy(consumer, producer)? { + keep_backing(&mut self.reserves, &mut vacated); deferred.defer_vacated(vacated); freed += 1; } @@ -1128,22 +1356,6 @@ impl Registry { Ok(entry) } - /// The caller checked its preparation epoch and retained the same device - /// session before placing this graph where publication can find it. - pub(super) fn install_compute( - &mut self, - reservation: ComputeReservation, - queue: &mut Option>, - ) -> Result { - let built = queue.as_ref().ok_or(EINVAL)?; - if built.qid() != reservation.id.qid() || built.owner() != Some(reservation.owner) { - return Err(EIO); - } - let entry = self.reserved(reservation)?; - entry.queue.put(queue.take()); - Ok(()) - } - pub(super) fn cancel_compute(&mut self, reservation: ComputeReservation) -> Result { self.reserved(reservation)?; self.qids.cancel_unpublished(reservation.id)?; @@ -1520,9 +1732,12 @@ impl Backend { } }; let dev = shared.drm()?; + // QUEUE_CREATE builds the context here, in the client's ioctl: a failure comes back from + // it, so the context's objects are charged to the client. let alloc = super::object::Allocator { dev: &dev, uat: &uat, + client: vm.memory_client(), }; let owner_pid = u32::try_from(kernel::current!().group_leader().pid()).map_err(|_| EOVERFLOW)?; @@ -1587,151 +1802,51 @@ impl Backend { Ok(PublicationBatch { batch, spare: &self.spare_batch }) } - /// The shared aperture has exactly one builder. Other queues sleep without - /// holding the device mutex; recovery joins its lease before closing roots. + /// Installs the shared aperture this owner's SUBMIT prepared, if no publication did yet, and + /// maps it into the owner's VM. Recovery joins the lease before closing roots. fn shared_compute(&self, admission: &Admission<'_>) -> Result { // The shared aperture is G17P compute state. M5 compute queues need only // their own pools, and the objects it would install are not M5's. - if self.context.is_m5() { + if !self.shared.variant.compute.needs_shared_aperture() { return Ok(()); } - loop { - admission.check()?; - let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; - let uat = { - let mut state = self.shared.state.lock(); - loop { - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if self - .shared - .crashed - .load(core::sync::atomic::Ordering::Acquire) - { - return Err(EIO); - } - if !lease.is_current() { - return Err(EAGAIN); - } - if firmware.init.has_compute_shared() { - return firmware.init.cache_compute_vm(self.context.vm()); - } - if !firmware.queues.compute_building { - firmware.queues.compute_building = true; - break firmware.uat.clone(); - } - let _ = self.shared.changed.wait_timeout( - &mut state, kernel::time::msecs_to_jiffies(admission.slice_ms()?) - ); - } - }; - let alloc = super::object::Allocator { - dev: &dev, - uat: &uat, - }; - let mut built = Some(super::initdata::ComputeShared::new(&alloc)); - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() { - Err(EAGAIN) - } else { - built - .take() - .ok_or(EIO)? - .and_then(|built| firmware.init.install_compute_shared(built)) - .and_then(|()| firmware.init.cache_compute_vm(self.context.vm())) - } - }; - drop(built); - { - let mut state = self.shared.state.lock(); - (*state) - .as_deref_mut() - .ok_or(ENODEV)? - .queues - .compute_building = false; - } - self.shared.note_changed(); - drop(lease); - if result != Err(EAGAIN) { - return result; - } + admission.check()?; + let lease = self.shared.preparations.enter_until(admission)?; + let mut state = self.shared.state.lock(); + admission.check()?; + let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; + if self.shared.crashed.load(Ordering::Acquire) { + return Err(EIO); } - } - - /// Uses the queue builder's existing lease. Entering another closed epoch - /// here would make recovery wait for the very builder blocked on reopening. - fn compute_scheduler( - &self, - alloc: &super::object::Allocator<'_>, - lease: &super::preparation::Lease, - admission: &Admission<'_>, - ) -> Result { - { - let mut state = self.shared.state.lock(); - loop { - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { - return Err(EAGAIN); - } - if firmware.init.has_compute_scheduler() { - return Ok(()); - } - if !firmware.queues.compute_scheduler_building { - firmware.queues.compute_scheduler_building = true; - break; - } - let _ = self.shared.changed.wait_timeout( - &mut state, kernel::time::msecs_to_jiffies(admission.slice_ms()?) - ); - } + if !lease.is_current() { + return Err(EAGAIN); } - let mut built = Some(super::initdata::ComputeScheduler::new(alloc)); - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() { - Err(EAGAIN) - } else { - built - .take() - .ok_or(EIO)? - .and_then(|built| firmware.init.install_compute_scheduler(built)) - } - }; - drop(built); - { - let mut state = self.shared.state.lock(); - (*state) - .as_deref_mut() - .ok_or(ENODEV)? - .queues - .compute_scheduler_building = false; + if !firmware.init.has_compute_shared() { + // This command's SUBMIT left it prepared; only an install takes it. + let shared = firmware.queues.prepared_shared.take().ok_or(EIO)?; + firmware.init.install_compute_shared(shared)?; } - self.shared.note_changed(); - result + firmware.init.cache_compute_vm(self.context.vm()) } /// The caller keeps its preparation lease through this two-phase rollback. /// An empty registry entry prevents reusing the QID/free-list identity while /// its old aliases still occupy canonical or client addresses. Recovery joins /// this lease before removing the session, even if its epoch was invalidated. + /// The queue's backing goes back to its owner ([`keep_backing`]). fn finish_uninstalled_compute( &self, retired: Option<(ComputeReservation, KBox)>, ) -> Result { - let Some((reservation, queue)) = retired else { return Ok(()); }; + let Some((reservation, mut queue)) = retired else { return Ok(()); }; + let mut backing = queue.take_backing(); drop(queue); + backing.drop_aliases(); let mut state = self.shared.state.lock(); let firmware = state.as_deref_mut().ok_or(ENODEV)?; firmware.queues.cancel_compute(reservation)?; + firmware.queues.keep_returned(&mut backing); drop(state); + drop(backing); // The slot and its never-published QID are free again. self.shared.channels.notify(); Ok(()) @@ -1746,6 +1861,53 @@ impl Backend { }) } + /// Builds and installs a fresh compute queue for `reservation` as this owner's channel + /// `channel_index`, from the kit and backing its SUBMIT provisioned: under the device mutex, + /// allocating no device memory. Publish the pool row only after the channel and aliases + /// are ready. On failure, cancel the QID and restore all three spares to the owner. + fn install_fresh( + &self, + firmware: &mut super::Firmware, + reservation: ComputeReservation, + required: super::freelist::ComputeCapacity, + channel_index: u8, + ) -> (Result, Option, compute::Vacated) { + let none = || compute::Vacated::spares(None, None, None); + let mut backing = firmware.queues.take_fresh(self.owner, required); + let installed = (|| { + if backing.is_none() { return Err(ENOSPC); } + if self.shared.variant.compute.needs_shared_aperture() && !firmware.init.has_compute_scheduler() { + let scheduler = firmware.queues.prepared_scheduler.take().ok_or(EIO)?; + firmware.init.install_compute_scheduler(scheduler)?; + } + let entry = firmware.queues.reserved(reservation)?; + let queue = compute::Queue::new_channel( + &mut backing, + reservation.id, + self.owner, + self.context.clone(), + self.shared.variant.pointers, + self.shared.operand_state, + self.shared.m5_board, + self.shared.variant.compute, + self.context.is_m5(), + self.shared.variant.mcache, + channel_index, + |row| firmware.init.install_compute_pool(row), + )?; + entry.queue.put(Some(queue)); + Ok(()) + })(); + if installed.is_err() { + let _ = firmware.queues.cancel_compute(reservation); + if let Some((kit, pages, ring)) = backing { + let unused = firmware.queues.put_back(self.owner, Some(pages), Some(ring), Some(kit)); + return (installed, None, unused); + } + } + (installed, None, none()) + } + fn grow_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; { @@ -1769,12 +1931,10 @@ impl Backend { } } let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; - let uat = self.shared.state.lock().as_ref().ok_or(ENODEV)?.uat.clone(); - let alloc = super::object::Allocator { dev: &dev, uat: &uat }; - let mut pages = Some(super::freelist::Pages::for_compute(&alloc, required, - self.context.vm().memory_client())?); - let mut alias = Some(pages.as_mut().ok_or(EIO)?.map_client(self.context.vm())?); + // This owner's own pages, which its SUBMIT provisioned or a queue gave back, taken once + // growth needs them. + let mut pages = None; + let mut alias = None; let mut deferred = DeferredBatch::publication()?; let mut growth = None; // Set when the owner holds no queue any more. Until growth begins, its queue is an idle @@ -1784,7 +1944,8 @@ impl Backend { let mut unbound = false; let result = (|| loop { // Growth waits for this queue's retirement and for firmware to consume the pool - // release; both are progress the event worker reports. + // release; both are progress the event worker reports. So does the return of this + // owner's pages from a queue that gives them back. let observed = self.shared.progress.observe(); let mut retired_siblings: PerChannel = Default::default(); let result = (|| { @@ -1797,11 +1958,31 @@ impl Backend { // Release sibling channels before growing the primary channel so undersized // sibling pools are detached and later re-acquired at the grown capacity. firmware.queues.drain_compute_siblings(self.owner, &mut retired_siblings)?; + let fits = match firmware.queues.compute_primary(self.owner) { + Some(queue) => queue.pool_fits(required), + None => { + unbound = true; + return Err(EAGAIN); + } + }; + if fits { + return Ok(None); + } + if pages.is_none() { + pages = firmware.queues.take_pages(self.owner, required); + if pages.is_none() { + // An idle queue holds them: the next pool pass gives them back. + firmware.queues.recall_backing(self.owner, required); + return Err(EAGAIN); + } + } + if alias.is_none() { + alias = Some(pages.as_mut().ok_or(EIO)?.map_client(self.context.vm())?); + } let Some(mut queue) = firmware.queues.compute_primary(self.owner) else { unbound = true; return Err(EAGAIN); }; - if queue.pool_fits(required) { return Ok(None); } if growth.is_none() { let notify = queue.begin_growth(&firmware.init, required)?; // Capture physical identity before any following fallible @@ -1812,7 +1993,11 @@ impl Backend { firmware.primary.notify(crate::g17::MSG_CONTROL_NOTIFY)?; } } - queue.finish_growth(&firmware.init, &mut pages, &mut alias).map(Some) + let mut old = queue.finish_growth(&firmware.init, &mut pages, &mut alias)?; + drop(queue); + // The smaller pages stay this owner's while it has compute commands. + firmware.queues.keep_returned(&mut old); + Ok(Some(old)) })(); self.finish_retired_compute(&mut retired_siblings)?; deferred.finish(); @@ -1827,9 +2012,9 @@ impl Backend { Err(error) => return Err(error), } })(); + let mut retired = None; if result.is_err() { if let Some(token) = growth { - let mut retired = None; let mut state = self.shared.state.lock(); if let Some(firmware) = state.as_deref_mut() { for index in 0..firmware.queues.compute.len() { @@ -1844,42 +2029,39 @@ impl Backend { } } } - drop(state); - // Tentative replacement mappings also belong to this builder. - // Discard them before a fresh QID can acquire a successor. - drop(alias.take()); - drop(pages.take()); - self.finish_uninstalled_compute(retired)?; - self.shared.queue_events(); } } + // Tentative replacement mappings also belong to this builder. Discard them before a + // fresh QID can acquire a successor; unused pages stay this owner's. + drop(alias.take()); + if let Some(unused) = pages.take() { + let mut state = self.shared.state.lock(); + let unused = state.as_deref_mut() + .map(|firmware| firmware.queues.put_back(self.owner, Some(unused), None, None)); + drop(state); + drop(unused); + } + if growth.is_some() && result.is_err() { + self.finish_uninstalled_compute(retired)?; + self.shared.queue_events(); + } result } - /// Re-arms the vacant queue `qid` reserved for this owner with fresh zeroed backing, built - /// without the device mutex, and binds it as compute channel `channel_index` (0: the primary; - /// a sibling only while that index is still the owner's next free one). Some(true): bound; - /// Some(false): retry (the preparation epoch changed, the queue is no longer re-armable or - /// the sibling index was taken); None: no memory for the backing now. + /// Re-arms the vacant queue `qid` reserved for this owner with its own spare backing, and + /// binds it as compute channel `channel_index` (0: the primary; a sibling only while that + /// index is still the owner's next free one). Allocates nothing: the owner's SUBMIT + /// provisioned the backing, or a queue gave it back. Some(true): bound; Some(false): retry + /// (the preparation epoch changed, the queue is no longer re-armable or the sibling index + /// was taken); None: the owner's backing is not back yet, or a sibling has none. fn rearm_vacant( &self, qid: u8, channel_index: u8, required: super::freelist::ComputeCapacity, - alloc: &super::object::Allocator<'_>, - objects: &Arc, lease: &super::preparation::Lease, admission: &Admission<'_>, ) -> Result> { - let built = (|| -> Result<_> { - let pages = crate::g17::freelist::Pages::for_compute(alloc, required, - self.context.vm().memory_client())?; - Ok((pages, compute::DescriptorRing::new(alloc, objects)?)) - })(); - let (pages, ring) = match built { - Err(error) if error == ENOSPC => return Ok(None), - result => result?, - }; let mut state = self.shared.state.lock(); admission.check()?; let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; @@ -1887,8 +2069,6 @@ impl Backend { return Ok(Some(false)); } if let Err(error) = self.admission_open() { drop(state); return Err(error); } - // Leave rejected backing local so it is dropped after the device guard, not in - // rearm(). let ready = firmware.queues.compute.iter().flatten() .filter_map(|entry| entry.queue.as_deref()) .any(|queue| queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)) @@ -1896,10 +2076,21 @@ impl Backend { || firmware.queues.next_sibling_index(self.owner, self.compute_channels) == Some(channel_index)); if !ready { drop(state); return Ok(Some(false)); } - let (descriptor, vacated) = match firmware.queues.rearm_compute(qid, pages, ring) { + let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else { + if channel_index != 0 { + firmware.queues.want_sibling(self.owner); + } + return Ok(None); + }; + let (descriptor, mut vacated) = match firmware.queues.rearm_compute(qid, self.owner, pages, ring) { Err(error) if error == EAGAIN => return Ok(Some(false)), result => result?, }; + // A ring the queue still held goes back to its owner; the rest is dropped after the + // device guard. + if let Some(vacated) = vacated.as_mut() { + firmware.queues.keep_returned(vacated); + } // The firmware consumed this slot's release before the backing // was dropped; the row is rewritten before the queue is kicked. firmware.init.install_compute_pool(descriptor)?; @@ -1926,9 +2117,8 @@ impl Backend { // Sampled before any capacity check of this attempt. let observed = self.shared.channels.observe(); let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; let mut reclaimed = None; - let (uat, objects, reservation) = { + let built = { let mut state = self.shared.state.lock(); admission.check()?; let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; @@ -1952,8 +2142,15 @@ impl Backend { match rebound { Rebind::Done => return Ok(()), Rebind::Grow => { drop(state); drop(lease); return self.grow_compute(required, admission); } - Rebind::Rearm(qid) => (firmware.uat.clone(), firmware.pool.clone(), Err(qid)), + Rebind::Rearm(qid) => Err(qid), Rebind::Fresh => { + // This owner's backing may still be on its way back from a queue. + if !firmware.queues.can_build_fresh(self.owner, required) { + drop(state); + drop(lease); + self.wait_channels(observed, admission, true)?; + continue; + } let reservation = match firmware .queues .reserve_compute_reclaiming(self.owner, &mut reclaimed) @@ -1985,22 +2182,17 @@ impl Backend { } Err(error) => return Err(error), }; - (firmware.uat.clone(), firmware.pool.clone(), Ok(reservation)) + Ok(self.install_fresh(firmware, reservation, required, 0)) } } }; drop(reclaimed); - let alloc = super::object::Allocator { - dev: &dev, - uat: &uat, - }; - let reservation = match reservation { - Ok(reservation) => reservation, + let (result, retired, unused) = match built { + Ok(built) => built, Err(qid) => { // bind_reusable reserved `qid` for this owner: any outcome but binding it // ends the reservation, so another owner may re-arm it. - let result = - self.rearm_vacant(qid, 0, required, &alloc, &objects, &lease, admission); + let result = self.rearm_vacant(qid, 0, required, &lease, admission); if !matches!(result, Ok(Some(true))) { if let Some(firmware) = self.shared.state.lock().as_deref_mut() { firmware.queues.release_rearm(qid, self.owner); @@ -2017,71 +2209,11 @@ impl Backend { } } }; - let built = (|| { - let pool = compute::PoolBacking::new(&alloc, reservation.id, required, - self.context.vm().memory_client())?; - { - let mut state = self.shared.state.lock(); - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { - return Err(EAGAIN); - } - self.admission_open()?; - firmware.queues.reserved(reservation)?; - firmware.init.install_compute_pool(pool.pool_descriptor()?)?; - } - let backing = compute::Backing::new(&alloc, pool)?; - // The global scheduler is created after pool/kick backing and - // retained even if this queue's later descriptor graph fails. - // It is G17P compute state; M5 has none. - if !self.context.is_m5() { - self.compute_scheduler(&alloc, &lease, admission)?; - } - let queue = compute::Queue::new( - &alloc, - &objects, - backing, - self.owner, - self.context.clone(), - self.shared.variant.pointers, - self.shared.operand_state, - self.shared.m5_board, - self.shared.variant.compute, - alloc.uat.is_m5(), - self.shared.variant.mcache, - )?; - Ok(KBox::new(queue, GFP_KERNEL)?) - })(); - let (mut built, build_error) = match built { - Ok(queue) => (Some(queue), None), - Err(error) => (None, Some(error)), - }; - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() { - Err(EAGAIN) - } else if let Some(error) = build_error { - Err(error) - } else { - admission.check().and_then(|()| firmware.queues.install_compute(reservation, &mut built)) - } - }; + drop(unused); // The old aliases must disappear before a waiting constructor can // reuse the QID and its queue-local free-list identity. Keep the // preparation lease until both mappings and reservation are gone. - drop(built); - if result.is_err() { - let mut state = self.shared.state.lock(); - (*state) - .as_mut() - .ok_or(ENODEV)? - .queues - .cancel_compute(reservation)?; - } + self.finish_uninstalled_compute(retired)?; drop(lease); if result == Err(ENOSPC) { self.wait_channels(observed, admission, true)?; @@ -2093,11 +2225,12 @@ impl Backend { /// Best-effort acquisition of an additional compute channel with its own dedicated compute /// pool for a multi-channel M5 owner, from the source [`Registry::sibling_source`] names: a - /// warm reusable queue is bound at once, a vacant one is re-armed with fresh backing and - /// bound as [`Self::rearm_vacant`] re-arms a primary's, a fresh QID gets a new queue, and an - /// idle queue still holding another VM's pool is given back for the next attempt. An owner - /// waiting for its first channel goes first. Never blocks or fails the submission if no - /// sibling is available. + /// warm reusable queue is bound at once, a vacant one is re-armed with the owner's spare + /// backing and bound as [`Self::rearm_vacant`] re-arms a primary's, a fresh QID gets a new + /// queue from the owner's spares, and an idle queue still holding another VM's (or another + /// owner's) pool is given back for the next attempt. An owner waiting for its first channel + /// goes first. Never blocks or fails the submission if no sibling is available; without + /// spare backing, the owner's next SUBMIT provisions some. fn try_add_compute_sibling( &self, required: super::freelist::ComputeCapacity, @@ -2108,8 +2241,7 @@ impl Backend { } admission.check()?; let lease = self.shared.preparations.enter_until(admission)?; - let dev = self.shared.drm()?; - let (uat, objects, source, channel_index) = { + let (source, channel_index) = { let mut state = self.shared.state.lock(); admission.check()?; let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; @@ -2154,35 +2286,32 @@ impl Backend { firmware.queues.reserve_rearm(qid, self.owner)?; Err(qid) } - Some(SiblingSource::Fresh) => match firmware - .queues - .reserve_compute_channel(self.owner, self.compute_channels) - { - Ok(reservation) => Ok(reservation), - Err(_) => return Ok(false), - }, + Some(SiblingSource::Fresh) => { + if !firmware.queues.can_build_fresh(self.owner, required) { + firmware.queues.want_sibling(self.owner); + return Ok(false); + } + match firmware + .queues + .reserve_compute_channel(self.owner, self.compute_channels) + { + Ok(reservation) => { + Ok(self.install_fresh(firmware, reservation, required, channel_index)) + } + Err(_) => return Ok(false), + } + } }; - ( - firmware.uat.clone(), - firmware.pool.clone(), - source, - channel_index, - ) + (source, channel_index) }; - let alloc = super::object::Allocator { - dev: &dev, - uat: &uat, - }; - let reservation = match source { - Ok(reservation) => reservation, + let (result, retired, unused) = match source { + Ok(built) => built, Err(qid) => { // The reservation ends with any outcome but binding the queue. let result = self.rearm_vacant( qid, channel_index, required, - &alloc, - &objects, &lease, admission, ); @@ -2198,65 +2327,9 @@ impl Backend { return Ok(bound); } }; - let built = (|| { - let pool = compute::PoolBacking::new( - &alloc, - reservation.id, - required, - self.context.vm().memory_client(), - )?; - { - let mut state = self.shared.state.lock(); - admission.check()?; - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if !lease.is_current() { - return Err(EAGAIN); - } - self.admission_open()?; - firmware.queues.reserved(reservation)?; - firmware.init.install_compute_pool(pool.pool_descriptor()?)?; - } - let backing = compute::Backing::new(&alloc, pool)?; - let queue = compute::Queue::new_channel( - &alloc, - &objects, - backing, - self.owner, - self.context.clone(), - self.shared.variant.pointers, - self.shared.operand_state, - self.shared.m5_board, - self.shared.variant.compute, - true, - self.shared.variant.mcache, - channel_index, - )?; - Ok(KBox::new(queue, GFP_KERNEL)?) - })(); - let (mut built, build_error) = match built { - Ok(queue) => (Some(queue), None), - Err(error) => (None, Some(error)), - }; - let result = { - let mut state = self.shared.state.lock(); - let firmware = (*state).as_deref_mut().ok_or(ENODEV)?; - if let Err(error) = admission.check() { - Err(error) - } else if !lease.is_current() || self.admission_open().is_err() { - Err(EAGAIN) - } else if let Some(error) = build_error { - Err(error) - } else { - firmware.queues.install_compute(reservation, &mut built) - } - }; - drop(built); - if result.is_err() { - let mut state = self.shared.state.lock(); - if let Some(firmware) = (*state).as_deref_mut() { - let _ = firmware.queues.cancel_compute(reservation); - } - } + drop(unused); + // Best effort, as the sibling itself. + let _ = self.finish_uninstalled_compute(retired); drop(lease); Ok(result.is_ok()) } @@ -2266,6 +2339,7 @@ impl Backend { /// The physical namespace bounds the batch independently of open logical queues. /// Collection failure leaves the engine's Active owner intact for a stopped retry. pub(super) struct DeferredBatch { + object_pool: Option>, has_source_completions: bool, values: KVVec, /// Exited owners detached from idle retained compute queues and the backing @@ -2306,6 +2380,7 @@ impl DeferredBatch { /// No room at all: allocates nothing. fn empty() -> Self { Self { + object_pool: None, has_source_completions: false, values: KVVec::new(), bindings: KVVec::new(), @@ -2316,7 +2391,8 @@ impl DeferredBatch { } /// Holds nothing: finished, or never used. pub(super) fn is_idle(&self) -> bool { - !self.has_source_completions + self.object_pool.is_none() + && !self.has_source_completions && self.values.is_empty() && self.bindings.is_empty() && self.vacated.is_empty() @@ -2330,6 +2406,7 @@ impl DeferredBatch { 0 }; Ok(Self { + object_pool: None, has_source_completions: false, values: KVVec::with_capacity(capacity, GFP_KERNEL)?, bindings: KVVec::with_capacity(detached, GFP_KERNEL)?, @@ -2456,6 +2533,9 @@ impl DeferredBatch { for release in self.tvb.drain_all() { drop(release); } + if let Some(pool) = self.object_pool.take() { + pool.reap_deferred(super::channel::control_witnessed()); + } } } @@ -3173,6 +3253,121 @@ impl Backend { .map(ComputeCapacity::Blocks) } + /// In the SUBMIT ioctl of a compute command: allocates what its publication will install + /// and must not allocate, so that a refusal is this ioctl's error (ENOMEM, or ENOSPC for + /// address space). The caller holds the command's [`super::context::ComputeClaim`]. + pub(super) fn provision_compute(&self, required: super::freelist::ComputeCapacity) -> Result { + self.provision_shared()?; + self.provision_backing(required) + } + + /// G17P's device-wide compute aperture and scheduler, until installed. + fn provision_shared(&self) -> Result { + if !self.shared.variant.compute.needs_shared_aperture() { + return Ok(()); + } + let needed = |firmware: &super::Firmware| ( + !firmware.init.has_compute_shared() && firmware.queues.prepared_shared.is_none(), + !firmware.init.has_compute_scheduler() && firmware.queues.prepared_scheduler.is_none(), + ); + { + let state = self.shared.state.lock(); + if needed(state.as_deref().ok_or(ENODEV)?) == (false, false) { + return Ok(()); + } + } + // No device mutex is held across allocation. Recovery joins this + // lease before replacing the firmware or tearing down its roots. + let _builder = self.shared.compute_provision.lock(); + let lease = self.shared.preparations.enter(true)?; + let (uat, (shared, scheduler)) = { + let state = self.shared.state.lock(); + let firmware = state.as_deref().ok_or(ENODEV)?; + (firmware.uat.clone(), needed(firmware)) + }; + if !shared && !scheduler { + return Ok(()); + } + let dev = self.shared.drm()?; + // Device memory: installed, they serve every client until processor stop. + let alloc = super::object::Allocator { dev: &dev, uat: &uat, client: None }; + let (mut shared, mut scheduler) = crate::memacct::device_memory(|| -> Result<_> { + Ok((shared.then(|| super::initdata::ComputeShared::new(&alloc)).transpose()?, + scheduler.then(|| super::initdata::ComputeScheduler::new(&alloc)).transpose()?)) + })?; + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + if !lease.is_current() { return Err(EAGAIN); } + let (want_shared, want_scheduler) = needed(firmware); + if want_shared { + firmware.queues.prepared_shared = shared.take(); + } + if want_scheduler { + firmware.queues.prepared_scheduler = scheduler.take(); + } + drop(state); + // Drop any unused allocation off the device mutex. + drop((shared, scheduler)); + Ok(()) + } + + /// This owner's compute backing for a publication at `required`, unless its spares or its + /// queues hold some ([`Registry::compute_lacks`]): pool pages and a descriptor ring charged + /// to its client, and for an owner without a queue of its own a kit of device memory. A + /// sibling channel that found none gets a set too, if it can be allocated. + fn provision_backing(&self, required: super::freelist::ComputeCapacity) -> Result { + let (uat, objects, lacks, reserved) = { + let state = self.shared.state.lock(); + let firmware = state.as_deref().ok_or(ENODEV)?; + let reserved = firmware.queues.reserves.iter().any(|reserve| reserve.owner == self.owner); + (firmware.uat.clone(), firmware.pool.clone(), + firmware.queues.compute_lacks(self.owner, required), reserved) + }; + if !lacks.any() && reserved { + return Ok(()); + } + let dev = self.shared.drm()?; + let client = self.context.vm().memory_client(); + let charged = super::object::Allocator { dev: &dev, uat: &uat, client }; + let device = super::object::Allocator { dev: &dev, uat: &uat, client: None }; + let reserve = (!reserved) + .then(|| KBox::new(OwnerReserve::new(self.owner, self.context.clone()), GFP_KERNEL)) + .transpose()?; + let mut pages = lacks.pages + .then(|| super::freelist::Pages::for_compute(&charged, required, client)).transpose()?; + let mut ring = lacks.ring + .then(|| compute::DescriptorRing::new(&charged, &objects)).transpose()?; + // A kit outlives the owner in the queue it builds: device memory. + let new_kit = || crate::memacct::device_memory(|| compute::Kit::new( + &device, &objects, self.shared.operand_state, self.context.is_m5())); + let mut kit = lacks.kit.then(&new_kit).transpose()?; + if lacks.sibling && !lacks.pages && !lacks.ring { + // Best effort, as the sibling: a refusal fails nothing. + pages = super::freelist::Pages::for_compute(&charged, required, client).ok(); + ring = compute::DescriptorRing::new(&charged, &objects).ok(); + kit = kit.or_else(|| new_kit().ok()); + } + let mut state = self.shared.state.lock(); + let firmware = state.as_deref_mut().ok_or(ENODEV)?; + // A queue that closed meanwhile keeps nothing. + let closed = self.closed.load(Ordering::Acquire); + let (unused, reserve) = if closed { + (compute::Vacated::spares(pages, ring, kit), reserve) + } else { + firmware.queues.stock(self.owner, reserve, pages, ring, kit) + }; + let stocked = closed || firmware.queues.reserves.iter().any(|reserve| reserve.owner == self.owner); + drop(state); + drop((unused, reserve)); + // Every logical queue has room for a reserve; without one, the command must not be queued. + if !stocked { + return Err(ENOSPC); + } + // A publication of this owner may be waiting for its backing. + self.shared.channels.notify(); + Ok(()) + } + fn ensure_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { admission.check()?; let mut deferred = DeferredBatch::publication()?; @@ -4439,7 +4634,8 @@ impl super::Firmware { queue.recycle_killed()?; queue.recycle_quarantined_idle()?; if deferred.vacated_room() { - if let Some(vacated) = queue.take_recycled_ring() { + if let Some(mut vacated) = queue.take_recycled_ring() { + keep_backing(&mut self.queues.reserves, &mut vacated); deferred.defer_vacated(vacated); freed = true; } @@ -4450,7 +4646,9 @@ impl super::Firmware { freed |= busy && queue.channel_free(); releasing |= queue.pool_release_pending(); } + deferred.object_pool = Some(self.pool.clone()); freed |= self.queues.observe_pool_releases(&self.init, deferred)? != 0; + self.queues.trim_reserves(deferred); let shared = &self.primary.state.shared; // Edge notifications cover the transitions this driver makes; every // event pass also rechecks the level, so capacity that appeared through diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index 1679b1fd52ab6..527f08debbeb9 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -116,7 +116,10 @@ impl Backend { firmware.queues.sync_render_holds(); firmware.queues.admission.release_owner(self.owner); } + // Its spare compute backing is freed; what its queues hold is no longer kept for it. + let reserve = firmware.queues.close_reserve(self.owner); drop(state); + drop(reserve); // Its idle channel, or its slot and never-published QID, is free. self.shared.channels.notify(); self.shared.queue_events(); @@ -289,7 +292,8 @@ impl job::Backend for Backend { // A reverse timeline chain must be submitted before the host signal. // Validate here, but do not consume physical capacity behind unsignalled // DRM dependencies. compute_packet admits it when the job can run. - self.compute_capacity(command).map(|_| ()) + // What its publication would allocate is allocated now, so a refusal is this SUBMIT's. + self.compute_capacity(command).and_then(|required| self.provision_compute(required)) } fn fail_vm(&self, error: Error) { diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs index 3478e844f1677..8a83a935aa9af 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/direct.rs @@ -485,6 +485,7 @@ impl Backend { let alloc = Allocator { dev: &dev, uat: &loan.uat, + client: None, }; pair.prepare( &alloc, diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 8b4ca024ec222..83827ee24d175 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -134,6 +134,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; let pool = match existing { Some(pool) => pool, @@ -239,6 +240,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; pool.ensure_backing(&alloc, &resources.global, client) } @@ -315,6 +317,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; if resources.uat.is_m5() { return self.prepare_pool_backing( @@ -395,6 +398,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &resources.uat, + client: None, }; let fresh_graph = match &build { Build::Fresh(..) | Build::Parked { .. } => true, @@ -935,6 +939,7 @@ impl super::super::Backend { let alloc = Allocator { dev: &dev, uat: &uat, + client: None, }; let mut growth = None; let busy = matches!(growth_target, Some((_, _, None))); diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs b/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs index 6c1d0a2037c55..c4f85e18b14b7 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/replay.rs @@ -185,6 +185,7 @@ impl Firmware { let alloc = Allocator { dev: &dev, uat: &uat, + client: None, }; pair.prepare(&alloc, &packet, addresses, 0) }); diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index e5f60c14e2eb5..c23ea2b131d4e 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -32,8 +32,14 @@ //! out-of-device-memory, instead of pushing the machine into a global OOM. //! //! Imported dma-bufs are charged to their exporter and are not counted here. -//! Kernel objects (firmware structures, per-queue buffers and the global heaps) -//! count towards the device total and its limit, but are attributed to no process. +//! Kernel objects a client's ioctls build for its queues (on G17, its context at queue +//! creation, and its compute pool pages and descriptor rings at a compute SUBMIT) are +//! charged to that client as its held memory, whatever the limits, and their pages to its +//! memory cgroup ([`Client::charging`]). Kernel objects built later, when a submission is +//! published, and device memory (firmware heaps and boot structures, and objects that +//! outlive the client that caused them, [`device_memory`]) count towards the device total +//! and its limit, but are attributed to no process: a failure after a submission was +//! accepted would lose the device. use core::sync::atomic::{ AtomicBool, @@ -51,6 +57,16 @@ use kernel::{ sync::{aref::ARef, Arc}, }; +use core::ffi::c_void; + +unsafe extern "C" { + fn asahi_memcg_get() -> *mut c_void; + fn asahi_memcg_root() -> *mut c_void; + fn asahi_memcg_put(memcg: *mut c_void); + fn asahi_memcg_enter(memcg: *mut c_void) -> *mut c_void; + fn asahi_memcg_leave(old: *mut c_void); +} + use crate::module_parameters; /// Device-wide GPU memory totals, in bytes. @@ -217,6 +233,19 @@ impl Ledger { }) } + /// Commits `bytes` of kernel memory that `client`'s queues need, whatever the limits: the + /// bytes count against both limits for the client's later objects, and are given back + /// when the returned [`Commit`] is dropped. + pub(crate) fn commit(&'static self, client: &Arc, bytes: u64) -> Commit { + client.committed.fetch_add(bytes, Ordering::AcqRel); + self.user_committed.fetch_add(bytes, Ordering::AcqRel); + Commit { + ledger: self, + client: client.clone(), + bytes, + } + } + /// Adds `bytes` to `client`'s and the device's committed totals if both stay within their /// limits; otherwise counts a refusal and fails with `ENOMEM`, adding nothing. fn reserve(&self, client: &Client, bytes: u64) -> Result { @@ -316,6 +345,35 @@ pub(crate) struct Client { resident: AtomicU64, /// Bytes of the device's firmware timestamp window this client's bound buffers hold. timestamp_window: AtomicU64, + /// The memory cgroup of the task that opened the client, referenced (NULL without memory + /// cgroups). + memcg: *mut c_void, +} + +// SAFETY: `memcg` is a counted reference, which may be used and dropped on any thread; the +// rest are atomics. +unsafe impl Send for Client {} +// SAFETY: See `Send`; shared access never changes `memcg`. +unsafe impl Sync for Client {} + +impl Drop for Client { + fn drop(&mut self) { + // SAFETY: Drops the reference `asahi_memcg_get()` took in `Client::new()`. + unsafe { asahi_memcg_put(self.memcg) }; + } +} + +/// Runs `f` with the root memory cgroup as the one that pages populated in it are charged to: +/// device memory a client's ioctl allocates (objects that outlive the client and serve others) +/// is charged to no client's cgroup, as when a kernel thread allocates it. +pub(crate) fn device_memory(f: impl FnOnce() -> T) -> T { + // SAFETY: The root memory cgroup is never freed, and the previous cgroup is restored before + // returning. + let old = unsafe { asahi_memcg_enter(asahi_memcg_root()) }; + let result = f(); + // SAFETY: Restores what `asahi_memcg_enter()` replaced. + unsafe { asahi_memcg_leave(old) }; + result } impl Client { @@ -325,11 +383,26 @@ impl Client { committed: AtomicU64::new(0), resident: AtomicU64::new(0), timestamp_window: AtomicU64::new(0), + // SAFETY: Takes a reference to the current task's memory cgroup, which + // `Drop` gives back. + memcg: unsafe { asahi_memcg_get() }, }, GFP_KERNEL, )?) } + /// Runs `f` with the client's memory cgroup as the one that pages populated in it are + /// charged to, from any task. + pub(crate) fn charging(&self, f: impl FnOnce() -> T) -> T { + // SAFETY: `memcg` stays referenced while `self` exists, and the previous cgroup is + // restored before returning. + let old = unsafe { asahi_memcg_enter(self.memcg) }; + let result = f(); + // SAFETY: Restores what `asahi_memcg_enter()` replaced. + unsafe { asahi_memcg_leave(old) }; + result + } + pub(crate) fn committed(&self) -> u64 { self.committed.load(Ordering::Relaxed) } @@ -642,6 +715,74 @@ mod tests { Ok(()) } + static QUEUE: Ledger = Ledger::new(); + + #[test] + fn queue_objects_are_charged_to_their_client_and_released_once() -> Result { + QUEUE.set_limits(Limits { device: 64 * MIB, client: 32 * MIB }); + let a = Client::new()?; + let b = Client::new()?; + // A queue's kernel objects are charged whatever the limits, like memory that already + // exists. a is past its own limit afterwards. + let ring = Charge::user(QUEUE.commit(&a, 24 * MIB), None); + ring.set_held(true); + let state = Charge::user(QUEUE.commit(&a, 16 * MIB), None); + state.set_held(true); + assert_eq!((a.committed(), a.resident()), (40 * MIB, 40 * MIB)); + assert_eq!(QUEUE.kernel_resident.load(Ordering::Relaxed), 0); + // They count against the client's and the device's limits for its next objects. + assert_eq!(QUEUE.admit(&a, MIB).err(), Some(ENOMEM)); + assert_eq!(QUEUE.admit(&b, 32 * MIB).err(), Some(ENOMEM)); + let b1 = QUEUE.admit(&b, 24 * MIB)?; + // The client's file goes while the firmware still holds the objects: the charges stay + // until the objects are freed, and each is released once. + drop(a); + assert_eq!(QUEUE.user_resident.load(Ordering::Relaxed), 40 * MIB); + drop(ring); + assert_eq!(QUEUE.user_committed.load(Ordering::Relaxed), 40 * MIB); + drop(state); + drop(b1); + assert_eq!(QUEUE.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(QUEUE.user_resident.load(Ordering::Relaxed), 0); + Ok(()) + } + + #[test] + fn device_memory_is_charged_to_the_root_cgroup() -> Result { + let a = Client::new()?; + // Inside a client's scope too: device memory goes to the root cgroup, and both scopes + // are restored. + let active = a.charging(|| device_memory(|| { + // SAFETY: Reads the active memory cgroup by replacing it and at once restoring it. + let active = unsafe { asahi_memcg_enter(core::ptr::null_mut()) }; + // SAFETY: Restores it. + unsafe { asahi_memcg_leave(active) }; + active + })); + // SAFETY: As above. Without memory cgroups the root, like the active one, is null. + assert_eq!(active, unsafe { asahi_memcg_root() }); + // SAFETY: As above. + let old = unsafe { asahi_memcg_enter(core::ptr::null_mut()) }; + // SAFETY: Restores it. + unsafe { asahi_memcg_leave(old) }; + assert!(old.is_null()); + Ok(()) + } + + #[test] + fn charging_restores_the_memory_cgroup() -> Result { + let a = Client::new()?; + // Nested scopes restore what they replaced; a kernel thread's is none. + let inner = a.charging(|| a.charging(|| 7)); + assert_eq!(inner, 7); + // SAFETY: Replaces and at once restores the current task's active memory cgroup. + let old = unsafe { asahi_memcg_enter(core::ptr::null_mut()) }; + // SAFETY: Restores it. + unsafe { asahi_memcg_leave(old) }; + assert!(old.is_null()); + Ok(()) + } + static KERNEL: Ledger = Ledger::new(); #[test] diff --git a/drivers/gpu/drm/asahi/memcg_scope.c b/drivers/gpu/drm/asahi/memcg_scope.c new file mode 100644 index 0000000000000..9e0318506e409 --- /dev/null +++ b/drivers/gpu/drm/asahi/memcg_scope.c @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT +/* + * The memory cgroup of a GPU client, for kernel objects allocated on its + * behalf (memacct.rs). Their pages are charged to the active memory cgroup + * wherever they are populated, an ioctl of another process or a kernel + * thread among them. + */ + +#include +#include +#include + +#include "memcg_scope.h" + +/* The current task's memory cgroup, referenced; NULL without memory cgroups. */ +struct mem_cgroup *asahi_memcg_get(void) +{ + return get_mem_cgroup_from_mm(current->mm); +} + +/* + * The root memory cgroup, which device-wide objects a client's ioctl allocates are charged to; + * NULL without memory cgroups. + */ +struct mem_cgroup *asahi_memcg_root(void) +{ +#ifdef CONFIG_MEMCG + return root_mem_cgroup; +#else + return NULL; +#endif +} + +void asahi_memcg_put(struct mem_cgroup *memcg) +{ + mem_cgroup_put(memcg); +} + +/* Makes @memcg the one new pages are charged to; returns the previous one. */ +struct mem_cgroup *asahi_memcg_enter(struct mem_cgroup *memcg) +{ + return set_active_memcg(memcg); +} + +void asahi_memcg_leave(struct mem_cgroup *old) +{ + set_active_memcg(old); +} diff --git a/drivers/gpu/drm/asahi/memcg_scope.h b/drivers/gpu/drm/asahi/memcg_scope.h new file mode 100644 index 0000000000000..871624381e7a8 --- /dev/null +++ b/drivers/gpu/drm/asahi/memcg_scope.h @@ -0,0 +1,14 @@ +/* SPDX-License-Identifier: GPL-2.0-only OR MIT */ +#ifndef _ASAHI_MEMCG_SCOPE_H +#define _ASAHI_MEMCG_SCOPE_H + +struct mem_cgroup; + +/* Called from memacct.rs. */ +struct mem_cgroup *asahi_memcg_get(void); +struct mem_cgroup *asahi_memcg_root(void); +void asahi_memcg_put(struct mem_cgroup *memcg); +struct mem_cgroup *asahi_memcg_enter(struct mem_cgroup *memcg); +void asahi_memcg_leave(struct mem_cgroup *old); + +#endif diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 38bfdffc61e19..cf444e786ece2 100644 --- a/tools/asahi/g17-admission-order-tests.py +++ b/tools/asahi/g17-admission-order-tests.py @@ -47,7 +47,7 @@ def compute_order(): #![allow(dead_code)] use std::sync::atomic::{AtomicUsize,AtomicBool,Ordering}; type Result = std::result::Result; -const ECANCELED:i32=-125;const EIO:i32=-5;const EFAULT:i32=-14;const EINVAL:i32=-22; +const ECANCELED:i32=-125;const EIO:i32=-5;const EFAULT:i32=-14;const EINVAL:i32=-22;const ENOMEM:i32=-12; mod g17 { pub mod fw { pub mod compute_pool { @@ -72,7 +72,7 @@ def compute_order(): } pub mod runtime { use super::*; - use crate::{Result,ECANCELED,EIO,EFAULT,EINVAL}; + use crate::{Result,ECANCELED,EIO,EFAULT,EINVAL,ENOMEM}; use std::sync::atomic::{AtomicUsize,AtomicBool,Ordering}; pub struct Status(pub i32); impl Status {fn get(&self)->i32{self.0}} @@ -80,9 +80,10 @@ def compute_order(): impl Context {fn status(&self)->&Status{&self.status} fn is_current(&self)->bool{true} fn is_m5(&self)->bool{self.m5}} pub struct Shared {pub compute_blocks:usize,pub active_cores:u32,pub crashed:AtomicBool} pub struct Admission; - pub struct Backend {pub shared:Shared,pub physical:AtomicUsize,pub closed:AtomicBool,pub context:Context} + pub struct Backend {pub shared:Shared,pub physical:AtomicUsize,pub reserved:AtomicUsize,pub refuse:AtomicBool,pub closed:AtomicBool,pub context:Context} impl Backend { pub fn ensure_compute(&self,_:freelist::ComputeCapacity,_:&Admission)->Result {self.physical.fetch_add(1,Ordering::SeqCst);Ok(())} + pub fn provision_compute(&self,_:freelist::ComputeCapacity)->Result {if self.refuse.load(Ordering::SeqCst){return Err(ENOMEM);}self.reserved.fetch_add(1,Ordering::SeqCst);Ok(())} ''' + method('runtime.rs', 'pub(super) fn compute_capacity(').replace('pub(super) ', 'pub ', 1) + '\n' + method('runtime.rs', 'fn admission_open(').replace('fn ', 'pub fn ', 1) + r''' } pub trait Api {fn ensure_compute(&self,command:&command::Validated)->Result;} @@ -94,7 +95,7 @@ def compute_order(): use g17::{command::{ScratchRequest,Validated},freelist::ComputeCapacity,fw::m5::pool::PoolGeometry,render_resources::Plan,runtime::*}; fn compute(pages:u16)->Validated {Validated::Compute{plan:None,scratch:ScratchRequest(pages)}} fn backend(cores:u32,m5:bool)->Backend { - Backend{shared:Shared{compute_blocks:21,active_cores:cores,crashed:AtomicBool::new(false)},physical:AtomicUsize::new(0),closed:AtomicBool::new(false),context:Context{status:Status(0),m5}} + Backend{shared:Shared{compute_blocks:21,active_cores:cores,crashed:AtomicBool::new(false)},physical:AtomicUsize::new(0),reserved:AtomicUsize::new(0),refuse:AtomicBool::new(false),closed:AtomicBool::new(false),context:Context{status:Status(0),m5}} } fn main(){ let backend=backend(10,false); @@ -102,12 +103,18 @@ def compute_order(): // final host signal cannot be submitted if ioctl admission blocks on channels. for _client in 0..4 {for _queue in (0..9).rev() {::ensure_compute(&backend,&compute(0)).unwrap();}} assert_eq!(backend.physical.load(Ordering::SeqCst),0,"unsignalled work must not pin physical capacity"); + assert_eq!(backend.reserved.load(Ordering::SeqCst),36,"each SUBMIT reserves what its publication needs"); + // A reserve SUBMIT cannot fill is that SUBMIT's error. + backend.refuse.store(true,Ordering::SeqCst); + assert_eq!(::ensure_compute(&backend,&compute(0)),Err(ENOMEM),"a refused reserve must fail the SUBMIT"); + backend.refuse.store(false,Ordering::SeqCst); assert_eq!(backend.compute_capacity(&compute(3)),Ok(ComputeCapacity::Blocks(24))); Backend::ensure_compute(&backend,backend.compute_capacity(&compute(0)).unwrap(),&Admission).unwrap(); assert_eq!(backend.physical.load(Ordering::SeqCst),1); let invalid=self::backend(0,false); assert_eq!(::ensure_compute(&invalid,&compute(0)),Err(-22)); assert_eq!(invalid.physical.load(Ordering::SeqCst),0); + assert_eq!(invalid.reserved.load(Ordering::SeqCst),0,"invalid sizing reserves nothing"); assert_eq!(::ensure_compute(&backend,&Validated::Render),Err(EINVAL)); // M5 sizes a compute pool by its plan's geometry; that, too, admits nothing physical. let m5=self::backend(0,true); @@ -123,10 +130,10 @@ def compute_order(): println!("PASS closed builders cannot install after logical close; production ioctl sizing validates 36 reverse-order submissions without physical admission, on G17P and M5; invalid sizing consumes no channel"); } ''' - fixed = 'self.compute_capacity(command).map(|_| ())' + fixed = 'self.compute_capacity(command).and_then(|required| self.provision_compute(required))' assert code.count(fixed) == 1 with tempfile.TemporaryDirectory(prefix='g17-admission-order-') as tmp: - for name, source in [('fixed', code), ('eager-physical-admission', code.replace(fixed, 'self.compute_capacity(command).and_then(|required| Backend::ensure_compute(self, required, &Admission))')), ('ignore-logical-close', code.replace('self.closed.load(Ordering::Acquire)', 'false'))]: + for name, source in [('fixed', code), ('eager-physical-admission', code.replace(fixed, 'self.compute_capacity(command).and_then(|required| Backend::ensure_compute(self, required, &Admission))')), ('skip-reserve', code.replace(fixed, 'self.compute_capacity(command).map(|_| ())')), ('ignore-logical-close', code.replace('self.closed.load(Ordering::Acquire)', 'false'))]: path = Path(tmp) / (name + '.rs') binary = path.with_suffix('') path.write_text(source) @@ -136,7 +143,7 @@ def compute_order(): assert result.returncode == 0, result.stderr print(result.stdout.strip()) else: - assert result.returncode != 0 and ('must not pin physical capacity' if name == 'eager-physical-admission' else 'closed constructor must not install') in result.stderr, result.stderr + assert result.returncode != 0 and {'eager-physical-admission': 'must not pin physical capacity', 'skip-reserve': 'each SUBMIT reserves', 'ignore-logical-close': 'closed constructor must not install'}[name] in result.stderr, result.stderr print('PASS negative control:', name) @@ -558,6 +565,7 @@ def release_fixture(): } impl Registry { pub fn release_compute(&mut self, _: u64) -> Result { Ok(()) } + pub fn close_reserve(&mut self, _: u64) -> Option<()> { None } pub fn note_build_room(&self) {} """ + item(render_teardown, 'pub(in crate::g17::runtime) fn release_render(') + '\n' + runtime + r""" } diff --git a/tools/asahi/g17-compute-constructor-tests.py b/tools/asahi/g17-compute-constructor-tests.py index d5a3bbdeb44d2..a6959201e00e1 100644 --- a/tools/asahi/g17-compute-constructor-tests.py +++ b/tools/asahi/g17-compute-constructor-tests.py @@ -1,9 +1,15 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Execute both production shared-constructor waits and flag cleanup. +"""G17P's device-wide compute objects are allocated in SUBMIT and installed at publication. -Allocations, mappings, device locks and firmware are mocked. Real method bodies -must check the original admission after every wake and after off-lock creation. +Runs the production `Backend::provision_shared` (SUBMIT) and `Backend::shared_compute` +(publication) against mocked firmware state, allocations and leases: + +- SUBMIT allocates the shared aperture and the scheduler while neither is installed nor + prepared, as device memory (the root memory cgroup), and nothing on M5; an allocation + failure is the SUBMIT's error and leaves nothing prepared; +- publication installs the prepared aperture, never allocates, fails with EIO if none was + prepared, and checks the admission, the crash flag and its lease before installing. """ from pathlib import Path import os @@ -25,79 +31,115 @@ def item(text, signature): def fixture(): runtime = (ROOT / 'runtime.rs').read_text() - preparation = (ROOT / 'preparation.rs').read_text() - admission = (item(preparation, "pub(super) struct Admission<'a>") + '\n' + - item(preparation, "impl<'a> Admission<'a>")).replace('pub(super) ', '').replace('super::now_ns()', 'now_ns()').replace('super::timeout::', '') - # The admission's wait kinds and their count, which its struct names. - admission = ('#[derive(Clone,Copy,Debug,PartialEq)]\n' + item(preparation, 'pub(super) enum AdmissionWait').replace('pub(super) ', '') + '\n' - + next(line for line in preparation.splitlines() if 'const ADMISSION_WAITS:' in line).replace('pub(super) ', '') - + '\n' + admission) - methods = '\n'.join(item(runtime, sig) for sig in [' fn shared_compute(', ' fn compute_scheduler(']) - methods = methods.replace('super::object::Allocator', 'Allocator').replace('super::preparation::Lease', 'Lease').replace('super::initdata::', '') + methods = '\n'.join(item(runtime, sig) for sig in [' fn provision_shared(', ' fn shared_compute(']) + methods = (methods.replace('super::object::Allocator', 'Allocator').replace('super::initdata::', '') + .replace('super::freelist::ComputeCapacity', 'ComputeCapacity').replace('super::Firmware', 'Firmware') + .replace('crate::memacct::device_memory', 'device_memory').replace('pub(super) ', '')) return r''' #![allow(dead_code)] -use std::cell::Cell; -use std::sync::{Mutex,MutexGuard,atomic::{AtomicBool,AtomicU64,Ordering}}; +use std::sync::{Mutex,MutexGuard,atomic::{AtomicBool,AtomicUsize,Ordering}}; type Result = std::result::Result; -const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const EBUSY:i32=-16;const ECANCELED:i32=-125; -const RECOVERY_WAIT_MS:u32=26_000; -static NOW:AtomicU64=AtomicU64::new(0);static CANCEL:AtomicBool=AtomicBool::new(false);static ALLOCATE:AtomicBool=AtomicBool::new(false); -fn now_ns()->u64{NOW.load(Ordering::SeqCst)} -mod kernel{pub mod time{pub fn msecs_to_jiffies(ms:u32)->u32{ms}}} -''' + admission + r''' +const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const ENOMEM:i32=-12;const ECANCELED:i32=-125; +static ALLOCATED:AtomicUsize=AtomicUsize::new(0);static REFUSE:AtomicBool=AtomicBool::new(false); +static DEVICE_SCOPE:AtomicBool=AtomicBool::new(false);static CANCEL:AtomicBool=AtomicBool::new(false); +static CURRENT:AtomicBool=AtomicBool::new(true); +struct Admission<'a>(std::marker::PhantomData<&'a ()>); +const ADMISSION: Admission<'static> = Admission(std::marker::PhantomData); +impl Admission<'_>{fn check(&self)->Result{if CANCEL.load(Ordering::SeqCst){Err(ECANCELED)}else{Ok(())}}} struct Gate;struct Lease; -impl Gate{fn enter_until(&self,a:&Admission<'_>)->Result{a.check()?;Ok(Lease)}} -impl Lease{fn is_current(&self)->bool{true}} +impl Gate{fn enter(&self,_:bool)->Result{Ok(Lease)} fn enter_until(&self,a:&Admission<'_>)->Result{a.check()?;Ok(Lease)}} +impl Lease{fn is_current(&self)->bool{CURRENT.load(Ordering::SeqCst)}} struct State(Mutex>>); impl State{fn lock(&self)->MutexGuard<'_,Option>>{self.0.lock().unwrap()}} -struct Changed; -impl Changed{ - fn wait_timeout(&self,_:&mut MutexGuard<'_,T>,_:u32){NOW.fetch_add(1_000_000,Ordering::SeqCst);assert!(now_ns()<100_000_000,"constructor wait exceeded original budget");} - fn notify_all(&self){} -} -struct Shared{preparations:Gate,state:State,changed:Changed,crashed:AtomicBool} -impl Shared{fn drm(&self)->Result<()>{Ok(())} fn note_changed(&self){self.changed.notify_all();}} +struct Variant{compute:Layout} +struct Layout(bool);impl Layout{fn needs_shared_aperture(&self)->bool{self.0}} +struct Builder(Mutex<()>);impl Builder{fn lock(&self)->MutexGuard<'_,()>{self.0.lock().unwrap()}} +struct Shared{variant:Variant,compute_provision:Builder,preparations:Gate,state:State,crashed:AtomicBool} +impl Shared{fn drm(&self)->Result<()>{Ok(())}} struct Context{m5:bool}impl Context{fn vm(&self)->&(){&()} fn is_m5(&self)->bool{self.m5}} struct Backend{shared:Shared,context:Context} -struct Allocator<'a>{dev:&'a (),uat:&'a ()} -struct ComputeShared;struct ComputeScheduler; -fn allocate(){if ALLOCATE.load(Ordering::SeqCst){NOW.fetch_add(25_000_000,Ordering::SeqCst);}} -impl ComputeShared{fn new(_:&Allocator<'_>)->Result{allocate();Ok(Self)}} -impl ComputeScheduler{fn new(_:&Allocator<'_>)->Result{allocate();Ok(Self)}} -struct Init{shared:bool,scheduler:bool} +struct ComputeCapacity; +struct Allocator<'a>{dev:&'a (),uat:&'a (),client:Option<&'a ()>} +fn no_scope(f:impl FnOnce()->T)->T{f()} +fn device_memory(f:impl FnOnce()->T)->T{DEVICE_SCOPE.store(true,Ordering::SeqCst);let r=f();DEVICE_SCOPE.store(false,Ordering::SeqCst);r} +fn allocate()->Result{ + assert!(DEVICE_SCOPE.load(Ordering::SeqCst),"device-wide objects must be device memory"); + if REFUSE.load(Ordering::SeqCst){return Err(ENOMEM);}ALLOCATED.fetch_add(1,Ordering::SeqCst);Ok(()) +} +#[derive(Debug)]struct ComputeShared;#[derive(Debug)]struct ComputeScheduler; +impl ComputeShared{fn new(a:&Allocator<'_>)->Result{assert!(a.client.is_none());allocate()?;Ok(Self)}} +impl ComputeScheduler{fn new(a:&Allocator<'_>)->Result{assert!(a.client.is_none());allocate()?;Ok(Self)}} +struct Init{shared:bool,scheduler:bool,cached:usize} impl Init{ fn has_compute_shared(&self)->bool{self.shared} fn has_compute_scheduler(&self)->bool{self.scheduler} - fn cache_compute_vm(&self,_:&())->Result{Ok(())} + fn cache_compute_vm(&mut self,_:&())->Result{self.cached+=1;Ok(())} fn install_compute_shared(&mut self,_:ComputeShared)->Result{self.shared=true;Ok(())} - fn install_compute_scheduler(&mut self,_:ComputeScheduler)->Result{self.scheduler=true;Ok(())} } -struct Queues{compute_building:bool,compute_scheduler_building:bool} +struct Queues{prepared_shared:Option,prepared_scheduler:Option} struct Firmware{init:Init,uat:(),queues:Queues} impl Backend{ ''' + methods + r''' } +fn backend(m5:bool,shared:bool,scheduler:bool)->Backend{ + Backend{context:Context{m5},shared:Shared{variant:Variant{compute:Layout(!m5)},compute_provision:Builder(Mutex::new(())),preparations:Gate,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(), + init:Init{shared,scheduler,cached:0},queues:Queues{prepared_shared:None,prepared_scheduler:None}}))))}} +} +fn fw<'a>(b:&'a Backend)->MutexGuard<'a,Option>>{b.shared.state.lock()} fn main(){ - for scheduler in [false,true]{for cancel in [false,true]{for building in [false,true]{ - NOW.store(0,Ordering::SeqCst);CANCEL.store(cancel,Ordering::SeqCst);ALLOCATE.store(!building,Ordering::SeqCst); - let b=Backend{context:Context{m5:false},shared:Shared{preparations:Gate,changed:Changed,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(),init:Init{shared:false,scheduler:false},queues:Queues{compute_building:building,compute_scheduler_building:building}}))))}}; - let check=||{if CANCEL.load(Ordering::SeqCst)&&now_ns()>=10_000_000{Err(ECANCELED)}else{Ok(())}}; - let admission=Admission::new(20_000_000,&check); - let alloc=Allocator{dev:&(),uat:&()}; - let r=if scheduler{b.compute_scheduler(&alloc,&Lease,&admission)}else{b.shared_compute(&admission)}; - assert_eq!(r,Err(if cancel{ECANCELED}else{EBUSY}),"constructor must propagate deadline/cancel"); - assert_eq!(now_ns(),if building{if cancel{10_000_000}else{20_000_000}}else{25_000_000}); - let state=b.shared.state.lock();let fw=state.as_ref().unwrap(); - assert!(!fw.init.shared&&!fw.init.scheduler,"expired constructor must not install"); - if !building{assert!(!fw.queues.compute_building&&!fw.queues.compute_scheduler_building,"failed constructor must clear builder flag");} - }}} - // M5 compute queues need no shared aperture: nothing waits, builds or installs. - NOW.store(0,Ordering::SeqCst);CANCEL.store(false,Ordering::SeqCst);ALLOCATE.store(true,Ordering::SeqCst); - let b=Backend{context:Context{m5:true},shared:Shared{preparations:Gate,changed:Changed,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(),init:Init{shared:false,scheduler:false},queues:Queues{compute_building:true,compute_scheduler_building:false}}))))}}; - let check=||Ok(()); - assert_eq!(b.shared_compute(&Admission::new(20_000_000,&check)),Ok(())); - assert_eq!(now_ns(),0);assert!(!b.shared.state.lock().as_ref().unwrap().init.shared); - println!("PASS 8 production shared/scheduler constructor waits: expiry, cancellation, off-lock-build expiry, no installation and flag cleanup; M5 skips the G17P shared aperture"); + // SUBMIT: allocates what is neither installed nor prepared, once. + let b=backend(false,false,false); + let start=std::sync::Barrier::new(8); + std::thread::scope(|scope| { + for _ in 0..8 { + scope.spawn(|| { start.wait(); assert_eq!(b.provision_shared(),Ok(())); }); + } + }); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2); + assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_some()&&fw(&b).as_ref().unwrap().queues.prepared_scheduler.is_some()); + assert_eq!(b.provision_shared(),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2,"prepared objects must not be allocated again"); + // Publication installs the prepared aperture and allocates nothing. + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + {let g=fw(&b);let f=g.as_ref().unwrap();assert!(f.init.shared&&f.queues.prepared_shared.is_none()&&f.init.cached==1);} + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + assert_eq!(fw(&b).as_ref().unwrap().init.cached,2); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2,"publication must not allocate"); + // Installed objects are not prepared again. + let b=backend(false,true,true); + assert_eq!(b.provision_shared(),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),2); + // A refused allocation is the SUBMIT's error and prepares nothing. + let b=backend(false,false,false); + REFUSE.store(true,Ordering::SeqCst); + assert_eq!(b.provision_shared(),Err(ENOMEM),"a refused allocation must fail the SUBMIT"); + REFUSE.store(false,Ordering::SeqCst); + assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_none()); + // Publication without a prepared aperture fails and installs nothing; it never builds one. + assert_eq!(b.shared_compute(&ADMISSION),Err(EIO),"publication must not allocate an aperture SUBMIT did not prepare"); + assert!(!fw(&b).as_ref().unwrap().init.shared); + // A cancelled admission, a stale lease or a crash installs nothing. + assert_eq!(b.provision_shared(),Ok(())); + CANCEL.store(true,Ordering::SeqCst); + assert_eq!(b.shared_compute(&ADMISSION),Err(ECANCELED)); + CANCEL.store(false,Ordering::SeqCst); + CURRENT.store(false,Ordering::SeqCst); + assert_eq!(b.shared_compute(&ADMISSION),Err(EAGAIN)); + CURRENT.store(true,Ordering::SeqCst); + b.shared.crashed.store(true,Ordering::SeqCst); + assert_eq!(b.shared_compute(&ADMISSION),Err(EIO)); + b.shared.crashed.store(false,Ordering::SeqCst); + assert!(!fw(&b).as_ref().unwrap().init.shared&&fw(&b).as_ref().unwrap().queues.prepared_shared.is_some(),"a refused publication must keep the prepared aperture"); + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + assert!(fw(&b).as_ref().unwrap().init.shared); + // M5 has neither: nothing is allocated or installed. + let before=ALLOCATED.load(Ordering::SeqCst); + let b=backend(true,false,false); + assert_eq!(b.provision_shared(),Ok(())); + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before); + assert!(!fw(&b).as_ref().unwrap().init.shared); + println!("PASS G17P compute aperture and scheduler: SUBMIT prepares them once as device memory and fails on a refusal; publication installs the prepared aperture, never allocates, and keeps it on cancel, stale lease or crash; M5 has neither"); } ''' @@ -106,8 +148,15 @@ def main(): source = fixture() mutants = [ ('fixed', source, ''), - ('ignore-constructor-wakes', source.replace(' admission.check()?;\n let firmware', ' let firmware').replace(' admission.check()?;\n let firmware', ' let firmware').replace('admission.slice_ms()?', '10'), 'constructor wait exceeded'), - ('ignore-build-expiry', source.replace('if let Err(error) = admission.check() {', 'if let Err(error) = Ok::<(),i32>(()) {'), 'constructor must propagate'), + ('publication-builds', source.replace( + 'let shared = firmware.queues.prepared_shared.take().ok_or(EIO)?;', + 'let shared = firmware.queues.prepared_shared.take().map_or_else(|| device_memory(|| ComputeShared::new(&Allocator { dev: &(), uat: &(), client: None })), Ok)?;'), + 'publication must not allocate'), + ('charged-to-client', source.replace('= device_memory(|| -> Result<_>', '= no_scope(|| -> Result<_>'), + 'must be device memory'), + ('swallow-refusal', source.replace( + '(&alloc)).transpose()?', '(&alloc)).transpose().unwrap_or(None)'), + 'must fail the SUBMIT'), ] with tempfile.TemporaryDirectory(prefix='g17-compute-constructors-') as tmp: for name, code, expected in mutants: @@ -122,7 +171,7 @@ def main(): assert result.returncode == 0, result.stderr print(result.stdout.strip()) else: - assert result.returncode != 0 and expected in result.stderr, result.stderr + assert result.returncode != 0 and expected in result.stderr, (name, result.stderr) print('PASS negative control:', name) diff --git a/tools/asahi/g17-compute-growth-deadline-tests.py b/tools/asahi/g17-compute-growth-deadline-tests.py index 7ed4ca5c95277..727c839efc997 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -49,7 +49,7 @@ def fixture(): const EIO:i32=-5;const EAGAIN:i32=-11;const ENODEV:i32=-19;const EBUSY:i32=-16;const ECANCELED:i32=-125; const RECOVERY_WAIT_MS:u32=26_000; static NOW:AtomicU64=AtomicU64::new(0);static ALIAS:AtomicBool=AtomicBool::new(false);static PAGES:AtomicBool=AtomicBool::new(false); -static RESERVED:AtomicBool=AtomicBool::new(false);static ABORTED:AtomicBool=AtomicBool::new(false); +static RESERVED:AtomicBool=AtomicBool::new(false);static ABORTED:AtomicBool=AtomicBool::new(false);static RETURNED:AtomicBool=AtomicBool::new(false); fn now_ns()->u64{NOW.load(Ordering::SeqCst)} mod kernel{pub mod time{ pub struct Delta(pub u64);impl Delta{pub fn from_millis(ms:u64)->Self{Self(ms)}} @@ -70,7 +70,7 @@ def fixture(): // A G17P compute pool is sized in blocks; the sizes only flow through here. type ComputeCapacity=usize; struct Backend{shared:Shared,context:Context,owner:u64} -struct Allocator<'a>{dev:&'a (),uat:&'a ()} +struct Allocator<'a>{dev:&'a (),uat:&'a (),client:Option<&'a ()>} struct Pages;struct Alias; impl Pages{ fn for_compute(_:&Allocator<'_>,_:ComputeCapacity,_:Option<&()>)->Result{PAGES.store(true,Ordering::SeqCst);Ok(Self)} @@ -78,7 +78,9 @@ def fixture(): } impl Drop for Pages{fn drop(&mut self){PAGES.store(false,Ordering::SeqCst);}} impl Drop for Alias{fn drop(&mut self){ALIAS.store(false,Ordering::SeqCst);}} -mod compute{pub(crate) use crate::Queue;} +mod compute{pub(crate) use crate::{Queue,Vacated};} +// What a queue or a builder gives back to its owner. +struct Vacated;impl Vacated{fn drop_aliases(&mut self){}} const COMPUTE_CHANNELS_MAX:usize=3; ''' + aliases + r''' struct Queue{fresh:bool} @@ -87,7 +89,8 @@ def fixture(): fn pool_fits(&self,_:usize)->bool{false} fn begin_growth(&mut self,_:&(),_:usize)->Result{Ok(false)} fn growth_token(&self)->Option{Some(7)} - fn finish_growth(&mut self,_:&(),_:&mut Option,_:&mut Option)->Result{Err(EAGAIN)} + fn finish_growth(&mut self,_:&(),_:&mut Option,_:&mut Option)->Result{Err(EAGAIN)} + fn take_backing(&mut self)->Vacated{Vacated} fn abort_growth(&mut self,t:u64)->Result>{assert_eq!(t,7);ABORTED.store(true,Ordering::SeqCst);Ok(Some(self.fresh))} } impl Drop for Queue{fn drop(&mut self){if self.fresh{assert!(RESERVED.load(Ordering::SeqCst));assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst),"growth aliases must precede fresh QID return");}}} @@ -100,6 +103,12 @@ def fixture(): fn compute_primary(&mut self,owner:u64)->Option<&mut Queue>{self.compute_mut(owner)} fn drain_compute_siblings(&mut self,_:u64,_:&mut PerChannel)->Result{Ok(())} fn cancel_compute(&mut self,_:ComputeReservation)->Result{assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst));RESERVED.store(false,Ordering::SeqCst);Ok(())} + // The owner's spare pages: a SUBMIT provisioned them. + fn take_pages(&mut self,_:u64,_:ComputeCapacity)->Option{PAGES.store(true,Ordering::SeqCst);Some(Pages)} + fn recall_backing(&mut self,_:u64,_:ComputeCapacity)->bool{false} + fn keep_returned(&mut self,_:&mut Vacated){} + fn put_back(&mut self,_:u64,pages:Option,_:Option<()>,_:Option<()>)->Vacated{ + if let Some(pages)=pages{std::mem::forget(pages);PAGES.store(false,Ordering::SeqCst);RETURNED.store(true,Ordering::SeqCst);}Vacated} } struct Primary;impl Primary{fn notify(&self,_:u32)->Result{Ok(())}} struct Firmware{queues:Registry,uat:(),init:(),primary:Primary} @@ -115,7 +124,7 @@ def fixture(): } fn main(){ for fresh in [false,true]{for cancel in [false,true]{ - NOW.store(0,Ordering::SeqCst);ABORTED.store(false,Ordering::SeqCst);RESERVED.store(true,Ordering::SeqCst); + NOW.store(0,Ordering::SeqCst);ABORTED.store(false,Ordering::SeqCst);RESERVED.store(true,Ordering::SeqCst);RETURNED.store(false,Ordering::SeqCst); let b=Backend{owner:1,context:Context,shared:Shared{preparations:Gate,progress:Available,channels:Available,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(),init:(),primary:Primary,queues:Registry{compute:vec![Some(Entry{reservation:ComputeReservation,queue:Some(Box::new(Queue{fresh}))})]}}))))}}; let check=||{if cancel&&now_ns()>=10_000_000{Err(ECANCELED)}else{Ok(())}}; let admission=Admission::new(20_000_000,&check); @@ -123,8 +132,9 @@ def fixture(): assert_eq!(now_ns(),if cancel{10_000_000}else{20_000_000}); assert!(ABORTED.load(Ordering::SeqCst));assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst)); assert_eq!(RESERVED.load(Ordering::SeqCst),!fresh,"only unpublished QIDs may return without firmware release"); + assert!(RETURNED.load(Ordering::SeqCst),"unused growth pages must go back to their owner"); }} - println!("PASS 4 complete production growth waits: deadline, cancellation, installed retention, fresh rollback and tentative-alias/QID order"); + println!("PASS 4 complete production growth waits: deadline, cancellation, installed retention, fresh rollback, tentative-alias/QID order and unused pages back to their owner"); } ''' @@ -133,7 +143,8 @@ def main(): source = fixture() mutants = [('fixed', source, ''), ('ignore-shared-deadline', source.replace('if now_ns() >= self.deadline.get()', 'if false').replace('if remaining == 0 { return Err(EBUSY); }', ''), 'growth admission exceeded'), - ('keep-growth-alias', source.replace(' drop(alias.take());', ''), 'growth aliases must precede')] + ('keep-growth-alias', source.replace(' drop(alias.take());', ''), 'growth aliases must precede'), + ('drop-unused-pages', source.replace('firmware.queues.put_back(self.owner, Some(unused), None, None)', 'drop(unused)'), 'must go back to their owner')] with tempfile.TemporaryDirectory(prefix='g17-compute-growth-') as tmp: for name, code, expected in mutants: if name != 'fixed': diff --git a/tools/asahi/g17-compute-reserve-tests.py b/tools/asahi/g17-compute-reserve-tests.py new file mode 100644 index 0000000000000..b5356b54e84cc --- /dev/null +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -0,0 +1,346 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Compute publication allocates nothing: SUBMIT provisions, publication takes. + +A fresh G17 compute queue is built for a QID that publication reserves from +firmware state. Its objects (the pool's control and state, the kick ring, the +graph's objects: `compute::Kit`; the pool pages and descriptor ring) are +allocated without one, and binding them to the QID only stores: + +- `ComputePool::bind`, `kick::Queue::compute`, `Graph::new` and + `Queue::new_channel` allocate no device memory; +- `Kit::new` allocates the kit through an Allocator. + +A compute SUBMIT allocates them (`Backend::provision_compute`): the pool pages +and ring charged to the client, the kit as device memory. Its claim is taken +before, and the command is queued only after. Publication only takes from the +owner's spares, and what a queue gives back returns to its owner: + +- the publication paths (`shared_compute`, `build_compute`, `install_fresh`, + `rearm_vacant`, `grow_compute`, `try_add_compute_sibling`, + `finish_uninstalled_compute`) allocate no device memory; +- every place a queue gives backing back keeps it for its owner; close and the + pool pass free spares; another open owner's backing is never bound; +- compiled: the production `keep_backing`, `stock` and `trim_reserves` with the + production spare bookkeeping keep a claimed owner's backing, free an idle or + unknown owner's, and free every spare exactly once. + +--mutation allocating-bind / allocating-graph / publication-allocates / +claim-after-provision / free-returned / bind-other-owner / kit-needs-qid / +keep-idle inject a +fault and must be caught. +""" +import os +import subprocess +import tempfile +import argparse +import re +import sys +from pathlib import Path + +G17 = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' +# Calls that allocate device memory (or build an Allocator for it). +ALLOCATING = re.compile(r'\balloc\b|Allocator\s*\{|\.allocate\(|KernelObject::|for_compute\(|' + r'DescriptorRing::new\(|Kit::new\(|PoolObjects::new\(|ComputeRing::new\(|' + r'GraphObjects::new\(|ComputeShared::new\(|ComputeScheduler::new\(') + + +def item(text, signature): + start = text.index(signature) + begin = text.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[start:end] + + +def code(text): + return '\n'.join(l.split('//')[0] for l in text.split('\n')) + + +def sources(mutation): + files = {name: (G17 / name).read_text() for name in + ['freelist.rs', 'kick.rs', 'queue/compute.rs', 'runtime.rs', 'runtime/backend.rs', + 'queue/mod.rs', 'queue/compute/reserve.rs']} + if mutation == 'allocating-bind': + files['freelist.rs'] = files['freelist.rs'].replace( + ' let PoolObjects { control, state } = objects;', + ' let PoolObjects { control, state } = objects;\n' + ' let _ = alloc.kernel(CONTROL_SIZE, 0, mmu::PROT_GPU_FW_SHARED_RW, CpuMap::WriteCombined);', 1) + elif mutation == 'allocating-graph': + files['queue/compute.rs'] = files['queue/compute.rs'].replace( + ' let graph_va = graph.gpu_va();', + ' let ring = DescriptorRing::new(alloc, objects)?;\n let graph_va = graph.gpu_va();', 1) + elif mutation == 'publication-allocates': + files['runtime.rs'] = files['runtime.rs'].replace( + ' let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else {', + ' let pages = super::freelist::Pages::for_compute(&alloc, required, None)?;\n' + ' let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else {', 1) + elif mutation == 'claim-after-provision': + files['queue/mod.rs'] = files['queue/mod.rs'].replace( + ' .then(|| super::context::ComputeClaim::new(&self.context));\n' + ' if engine == Engine::Compute {\n self.ensure_compute(&command)?;\n }', + ' .then(|| ());\n if engine == Engine::Compute {\n self.ensure_compute(&command)?;\n' + ' }\n let claim = claim.map(|()| super::context::ComputeClaim::new(&self.context));', 1) + elif mutation == 'free-returned': + files['runtime.rs'] = files['runtime.rs'].replace( + ' keep_backing(&mut self.reserves, &mut vacated);\n', '', 1) + elif mutation == 'bind-other-owner': + files['runtime.rs'] = files['runtime.rs'].replace( + ' if !queue.pool_fits(required) || !queue.pool_serves(context.vm())\n' + ' || !queue.backing_free_for(owner)\n', + ' if !queue.pool_fits(required) || !queue.pool_serves(context.vm())\n', 1) + elif mutation == 'kit-needs-qid': + files['runtime.rs'] = files['runtime.rs'].replace( + '|| queue.owner() == Some(owner));', '|| queue.owner() == Some(owner))\n && self.compute_qid_fits();', 1) + elif mutation == 'keep-idle': + files['runtime.rs'] = files['runtime.rs'].replace( + ' if !reserve.context.compute_claimed() {\n return;\n }\n', '', 1) + return files + + +# (file, signature, why it must not allocate) +BINDS = [ + ('freelist.rs', 'pub(crate) fn bind(objects: PoolObjects', 'binding pool objects to a QID'), + ('kick.rs', 'pub(crate) fn compute(ring: ComputeRing', 'binding a kick ring to a QID'), + ('queue/compute.rs', 'fn initialize(graph: &mut KernelObject', "writing an owner's queue record"), + ('queue/compute.rs', 'fn new(\n objects: GraphObjects', 'assembling a fresh graph'), + ('queue/compute.rs', 'pub(crate) fn new_channel(', 'assembling a fresh queue'), +] + + +# Publication paths, which take from the owner's spares and allocate no device memory. +PUBLICATION = [' fn shared_compute(', ' fn install_fresh(', ' fn grow_compute(', ' fn rearm_vacant(', + ' fn build_compute(', ' fn try_add_compute_sibling(', ' fn finish_uninstalled_compute('] + + +def ordered(text, *parts): + position = 0 + for part in parts: + position = text.find(part, position) + if position < 0: + return False + position += len(part) + return True + + +def structure(files): + failures = [] + runtime = files['runtime.rs'] + for signature in PUBLICATION: + body = item(runtime, signature) + for m in ALLOCATING.finditer(code(body)): + failures.append(f'FAIL line {runtime.count(chr(10), 0, runtime.index(signature)) + 1}: runtime.rs: ' + f'publication {signature.strip()} allocates ({m.group(0)})') + backend = files['runtime/backend.rs'] + provision = item(runtime, ' fn provision_backing(') + channel = item(files['queue/compute.rs'], 'pub(crate) fn new_channel(') + fresh = item(runtime, ' fn install_fresh(') + checks = { + 'failed channel construction returns the kit, pages and ring to their owner': + ordered(channel, 'KBox::::new_uninit', 'Graph::map_binding(', 'install_row(', 'backing.take()') + and '?' not in channel.split('backing.take()', 1)[1], + 'a failed build restores the reservation': + ordered(fresh, 'Queue::new_channel(', 'cancel_compute(reservation)', 'put_back(self.owner, Some(pages), Some(ring), Some(kit))'), + 'M5 pool population uses the DRM opener': + 'client.charging(|| alloc.lower_user_charged(' in files['freelist.rs'], + 'charged backing from a closed owner cannot be rebound to a different client': + 'self.backing_owner == Some(owner)' in item(files['queue/compute.rs'], 'pub(crate) fn backing_free_for('), + 'SUBMIT provisions before validation returns': 'self.provision_compute(required)' in item(backend, ' fn ensure_compute('), + 'SUBMIT charges pages and ring to the client, the kit is device memory': ordered( + provision, 'let charged = super::object::Allocator { dev: &dev, uat: &uat, client };', + 'let device = super::object::Allocator { dev: &dev, uat: &uat, client: None };', + 'super::freelist::Pages::for_compute(&charged, required, client)', + 'compute::DescriptorRing::new(&charged, &objects)', + 'crate::memacct::device_memory(|| compute::Kit::new(', 'firmware.queues.stock('), + 'the claim precedes the SUBMIT provision, and the command is queued after it': ordered( + item(files['queue/mod.rs'], ' fn enqueue('), 'super::context::ComputeClaim::new(&self.context)', + 'self.ensure_compute(&command)?;', 'Packet::new(', 'claim,', '.enqueue(packet'), + 'given-back pools go to their owner': 'keep_backing(&mut self.reserves, &mut vacated);' in item(runtime, 'pub(super) fn observe_pool_releases('), + 'recycled rings go to their owner': 'keep_backing(&mut self.queues.reserves, &mut vacated);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), + 'the pool pass frees idle owners\' spares': 'self.queues.trim_reserves(deferred);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), + 'growth keeps the smaller pages': 'firmware.queues.keep_returned(&mut old);' in item(runtime, ' fn grow_compute('), + 'a never-published queue gives its backing back': ordered(item(runtime, ' fn finish_uninstalled_compute('), + 'queue.take_backing()', 'drop(queue);', 'backing.drop_aliases();', 'cancel_compute(reservation)?;', + 'firmware.queues.keep_returned(&mut backing);', 'drop(state);', 'drop(backing);'), + 'close frees the spares off the device mutex': ordered(item(backend, ' fn release_queue('), + 'firmware.queues.close_reserve(self.owner);', 'drop(state);', 'drop(reserve);'), + 'another open owner\'s backing is not bound': all( + '!queue.backing_free_for(owner)' in item(runtime, sig) for sig in + [' fn bind_reusable(', ' pub(super) fn rebind_compute(']) and + 'queue.pool_serves(vm) && queue.backing_free_for(owner)' in item(runtime, ' fn sibling_source('), + # Else a QID freed after SUBMIT would find the owner with no kit and no queue to share. + 'a queue-less owner always gets a kit': 'compute_qid_fits' not in item(runtime, ' pub(super) fn compute_lacks('), + 'a queue refuses another open owner\'s backing': '!self.backing_free_for(owner)' in item(files['queue/compute.rs'], ' fn bind_owner_channel('), + } + failures += [f'FAIL line 0: {name}' for name, ok in checks.items() if not ok] + return failures + + +def compiled(files): + """Runs the production give-back, stock and trim with the production spare bookkeeping.""" + runtime = files['runtime.rs'] + reserve = files['queue/compute/reserve.rs'] + spares = reserve[reserve.index('const PAGES'):reserve.index('#[kunit_tests')] + owner = item(runtime, 'pub(super) struct OwnerReserve {') + '\n' + item(runtime, 'impl OwnerReserve {') + methods = '\n'.join(item(runtime, sig) for sig in [' fn owner_reserve(', ' pub(super) fn stock(', + ' fn trim_reserves(']) + keep = item(runtime, 'fn keep_backing(') + replace = lambda text: (text.replace('pub(super) ', '').replace('super::freelist::Pages', 'Pages') + .replace('compute::reserve::Spares', 'Spares').replace('compute::DescriptorRing', 'Ring') + .replace('compute::Kit', 'Kit').replace('compute::Vacated', 'Vacated') + .replace('crate::g17::pairs::COMPUTE_CHANNELS_MAX', '3') + .replace('self.reserves.push_within_capacity(new)', 'push_within(&mut self.reserves, new)')) + source = r''' +#![allow(dead_code)] +use std::sync::{Arc, atomic::{AtomicUsize, AtomicU32, Ordering}}; +type KVec = Vec; +type KBox = Box; +type Result = std::result::Result; +#[derive(Clone, Copy)] enum ComputeCapacity { Blocks(usize) } +static MADE: AtomicUsize = AtomicUsize::new(0); +static FREED: AtomicUsize = AtomicUsize::new(0); +struct Pages(usize, bool); +impl Pages { + fn new(blocks: usize) -> Self { MADE.fetch_add(1, Ordering::SeqCst); Self(blocks, false) } + fn reset(&mut self) -> Result { self.1 = true; Ok(()) } +} +impl Drop for Pages { fn drop(&mut self) { FREED.fetch_add(1, Ordering::SeqCst); } } +struct Ring(bool); +impl Ring { + fn new() -> Self { MADE.fetch_add(1, Ordering::SeqCst); Self(false) } + fn clear(&mut self) { self.0 = true; } +} +impl Drop for Ring { fn drop(&mut self) { FREED.fetch_add(1, Ordering::SeqCst); } } +struct Kit; +impl Kit { fn new() -> Self { MADE.fetch_add(1, Ordering::SeqCst); Self } } +struct PushError(T); +fn push_within(v: &mut Vec, x: T) -> std::result::Result<(), PushError> { + if v.len() < v.capacity() { v.push(x); Ok(()) } else { Err(PushError(x)) } +} +impl Drop for Kit { fn drop(&mut self) { FREED.fetch_add(1, Ordering::SeqCst); } } +''' + replace(spares.replace('pub(crate) ', '')) + r''' +impl Capacity for Pages { + fn fits(&self, required: ComputeCapacity) -> bool { let ComputeCapacity::Blocks(b) = required; self.0 >= b } + fn covers(&self, other: &Self) -> bool { self.0 >= other.0 } +} +struct Context(AtomicU32); +impl Context { fn compute_claimed(&self) -> bool { self.0.load(Ordering::SeqCst) != 0 } } +/// What a queue gives back. +struct Vacated { pages: Option, ring: Option, kit: Option, owner: Option } +impl Vacated { + fn spares(pages: Option, ring: Option, kit: Option) -> Self { Self { pages, ring, kit, owner: None } } + fn returns_to(&self) -> Option { self.owner } + fn backing(&mut self) -> (&mut Option, &mut Option) { (&mut self.pages, &mut self.ring) } +} +struct DeferredBatch { vacated: Vec, room: usize } +impl DeferredBatch { + fn vacated_room(&self) -> bool { self.vacated.len() < self.room } + fn defer_vacated(&mut self, vacated: Vacated) { self.vacated.push(vacated) } +} +struct Registry { reserves: KVec> } +''' + replace(owner) + '\n' + replace(keep) + '\nimpl Registry {\n' + replace(methods) + r''' +} +fn back(owner: u64, blocks: usize) -> Vacated { + Vacated { pages: Some(Pages::new(blocks)), ring: Some(Ring::new()), kit: None, owner: Some(owner) } +} +fn main() { + let a = Arc::new(Context(AtomicU32::new(1))); + let b = Arc::new(Context(AtomicU32::new(1))); + let mut registry = Registry { reserves: Vec::with_capacity(2) }; + // SUBMIT stocks a new owner: its reserve and its first set. + let (unused, rest) = registry.stock(1, Some(Box::new(OwnerReserve::new(1, a.clone()))), + Some(Pages::new(21)), Some(Ring::new()), Some(Kit::new())); + assert!(rest.is_none() && unused.pages.is_none() && unused.ring.is_none() && unused.kit.is_none()); + drop(unused); + let (unused, _) = registry.stock(2, Some(Box::new(OwnerReserve::new(2, b.clone()))), Some(Pages::new(21)), None, None); + drop(unused); + assert_eq!(FREED.load(Ordering::SeqCst), 0, "stocking frees nothing"); + // A queue gives owner 1's backing back while it has commands: kept, reset, cleared. + let mut returned = back(1, 30); + keep_backing(&mut registry.reserves, &mut returned); + assert!(returned.pages.is_none() && returned.ring.is_none(), "a claimed owner's backing must be kept"); + drop(returned); + assert_eq!(FREED.load(Ordering::SeqCst), 0); + { + let spares = &mut registry.owner_reserve(1).unwrap().spares; + let pages = spares.take_pages(ComputeCapacity::Blocks(30)).unwrap(); + assert!(pages.1, "kept pages are reset"); + let (first, second) = (spares.take_ring().unwrap(), spares.take_ring().unwrap()); + assert!(first.0 != second.0, "the kept ring is cleared, the stocked one is fresh"); + spares.put_pages(pages); spares.put_ring(first); spares.put_ring(second); + } + // Owner 2 has no commands: what comes back is freed, as is an unknown owner's. + b.0.store(0, Ordering::SeqCst); + let mut idle = back(2, 30); + keep_backing(&mut registry.reserves, &mut idle); + assert!(idle.pages.is_some() && idle.ring.is_some(), "an idle owner's backing must be freed"); + drop(idle); + let mut unknown = back(9, 21); + keep_backing(&mut registry.reserves, &mut unknown); + assert!(unknown.pages.is_some()); + drop(unknown); + // The pool pass frees an idle owner's spares and keeps a claimed owner's. + let mut deferred = DeferredBatch { vacated: Vec::new(), room: 8 }; + registry.trim_reserves(&mut deferred); + assert!(registry.owner_reserve(2).unwrap().spares.is_empty(), "the pool pass must free idle spares"); + assert!(!registry.owner_reserve(1).unwrap().spares.is_empty(), "a claimed owner keeps its spares"); + drop(deferred); + // Close: owner 1 exits with its reserve unused; everything was freed exactly once. + let index = registry.reserves.iter().position(|reserve| reserve.owner == 1).unwrap(); + drop(registry.reserves.swap_remove(index)); + drop(registry); + assert_eq!(MADE.load(Ordering::SeqCst), FREED.load(Ordering::SeqCst), "every spare is freed exactly once"); + println!("PASS compute reserve: SUBMIT stocks, a claimed owner keeps what its queues give back (reset), an idle or unknown owner's backing and idle spares are freed, and close frees the rest, each once"); +} +''' + with tempfile.TemporaryDirectory(prefix='g17-compute-reserve-') as tmp: + path = Path(tmp) / 'reserve.rs' + path.write_text(source) + # The fixture slices in KUnit-only helpers (`is_empty`), so build it as KUnit does. + build = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-Awarnings', + '--cfg', 'CONFIG_KUNIT="y"', str(path), + '-o', str(path.with_suffix(''))], capture_output=True, text=True) + if build.returncode != 0: + return [f'FAIL line 0: compiled reserve fixture does not build:\n{build.stderr}'] + run = subprocess.run([str(path.with_suffix(''))], capture_output=True, text=True, timeout=30) + if run.returncode != 0: + return [f'FAIL line 0: compiled reserve: {run.stderr.strip()}'] + print(run.stdout.strip()) + return [] + + +def check(files): + failures = structure(files) + compiled(files) + for name, signature, why in BINDS: + text = files[name] + if signature not in text: + failures.append(f'FAIL line 0: {name}: {signature!r} is missing') + continue + body = item(text, signature) + for m in ALLOCATING.finditer(code(body)): + line = text.count('\n', 0, text.index(signature)) + code(body).count('\n', 0, m.start()) + 1 + failures.append(f'FAIL line {line}: {name}: {why} allocates ({m.group(0)})') + kit = files['queue/compute.rs'] + if 'impl Kit {' not in kit or 'GraphObjects::new(alloc' not in item(kit, 'impl Kit {'): + failures.append('FAIL line 0: queue/compute.rs: Kit::new does not allocate the graph objects') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['allocating-bind', 'allocating-graph', 'publication-allocates', + 'claim-after-provision', 'free-returned', 'bind-other-owner', + 'kit-needs-qid', 'keep-idle']) + args = parser.parse_args() + failures = check(sources(args.mutation)) + for f in failures: + print(f) + if failures: + sys.exit(1) + print('ok: compute objects are allocated in SUBMIT apart from their QID; publication only takes and binds') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-compute-retired-tests.py b/tools/asahi/g17-compute-retired-tests.py index 900fdee4c47b4..b71f817ae6f1d 100755 --- a/tools/asahi/g17-compute-retired-tests.py +++ b/tools/asahi/g17-compute-retired-tests.py @@ -167,7 +167,19 @@ def build_harness(mutation=None): log(format!("binding {}", self.0)); } } -mod compute { pub(super) use super::{Binding, Queue}; } +mod compute { pub(super) use super::{Binding, Queue, Vacated}; } +/// The backing a never-published queue gives back to its owner. +struct Vacated(u8); +impl Vacated { + fn drop_aliases(&mut self) { + assert!(!locked(), "aliases of qid {} dropped under the device mutex", self.0); + } +} +impl Drop for Vacated { + fn drop(&mut self) { + assert!(!locked(), "backing of qid {} freed under the device mutex", self.0); + } +} #[derive(Clone, Copy, PartialEq)] enum Rollback { Cancel, Displace, Keep, Fail } @@ -182,6 +194,7 @@ def build_harness(mutation=None): } impl Queue { fn owner(&self) -> Option { self.owner } + fn take_backing(&mut self) -> Vacated { Vacated(self.qid) } fn is_primary(&self) -> bool { self.primary } fn active_len(&self) -> u32 { self.active } fn has_replays(&self) -> bool { false } @@ -270,6 +283,9 @@ def build_harness(mutation=None): if error == ENOSPC { EAGAIN } else { error } } fn note_build_room(&mut self) {} + fn keep_returned(&mut self, vacated: &mut Vacated) { + assert!(locked(), "backing of qid {} kept off the device mutex", vacated.0); + } ''' + '\n'.join([drain, rollback, reserve, reserved, cancel]) + r''' } diff --git a/tools/asahi/g17-growth-tests.py b/tools/asahi/g17-growth-tests.py index f763fd5b5ff80..df73171e0d15e 100644 --- a/tools/asahi/g17-growth-tests.py +++ b/tools/asahi/g17-growth-tests.py @@ -39,13 +39,13 @@ def fixture(): pool_phase:PoolPhase,release_sent_ns:Option,pool:Pool,binding:Option,previous:Option,graph:Graph, active:Fifo,replays:Fifo,quarantined:bool,released:bool,retirement_ready:bool, retired_by_teardown:bool,released_at:u64,exit:Option<()>,needs_fresh_backing:bool, - source_hint:ReaderHint,source_readers:AtomicU32, + source_hint:ReaderHint,source_readers:AtomicU32,backing_owner:Option, } fn idle(live:&Arc)->Queue{Queue{owner:Some(1),channel_index:0,binding_noted:false,installed:true,growing:false,channel_error:false,growth:None, free_list_generation:0,configuration:None,retained_owner:None,pool_phase:PoolPhase::Populated,release_sent_ns:None,pool:Pool{pages:Some(Pages(10,21)),fail:false}, binding:Some(Binding{context:Context::new(live),pool_alias:Some(1),descriptors:Some(2)}),previous:None,graph:Graph, active:Fifo{len:0},replays:Fifo{len:0},quarantined:false,released:false,retirement_ready:true, - retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0)}} + retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0),backing_owner:Some(1)}} impl Queue { fn clear_binding_note(&mut self){if self.binding_noted{if let Some(binding)=&self.binding{binding.context.note_compute_binding(false);}self.binding_noted=false;}} fn clear_owner(&mut self,stamp:bool){self.clear_binding_note();self.owner=None;self.channel_index=0;if stamp{self.released_at=now_ns();}} @@ -92,7 +92,9 @@ def fixture(): enum ControlRecord {FreeListRelease(u64)} struct Rings; impl Rings {fn publish_control(_:&initdata::InitData,_:&ControlRecord)->Result{Ok(3)}} -struct Vacated {_alias:Option,_pages:Option,_descriptors:Option,_ring:Option} +struct Vacated {_alias:Option,pages:Option,_descriptors:Option,ring:Option,_kit:Option<()>,owner:Option} +// The owners' spare backing: what a queue gives back stays its owner's while it has commands. +fn keep_backing(_:&mut (),_:&mut Vacated){} impl Graph {fn vacate_ring(&mut self)->Option{Some(1)}} ''' + '#[derive(Clone, Copy)]\n' + item(source, 'pub(crate) struct Growth') + r''' impl Queue { @@ -100,7 +102,7 @@ def fixture(): ''' + methods + r''' } struct Entry {queue:Option>} -struct Registry {compute:Vec>} +struct Registry {compute:Vec>,reserves:()} struct DeferredBatch {vacated:Vec,capacity:usize} impl DeferredBatch { fn vacated_room(&self)->bool{self.vacated.len() bool {{ self.needs_fresh_backing }} fn pool_vacant(&self) -> bool {{ self.pool_vacant }} fn pool_serves(&self, vm: u32) -> bool {{ self.pool_vm == vm }} + // The backing of a closed owner, or of the asking one. + fn backing_free_for(&self, _: u64) -> bool {{ true }} fn pool_fits(&self, req: ComputeCapacity) -> bool {{ self.pool_cap >= req.0 }} fn has_ring(&self) -> bool {{ self.has_ring }} fn context(&self) -> Option<&Arc> {{ self.context.as_ref() }} diff --git a/tools/asahi/g17-m5-sibling-gate-tests.py b/tools/asahi/g17-m5-sibling-gate-tests.py index 719a29d0b905d..61406e4efd528 100755 --- a/tools/asahi/g17-m5-sibling-gate-tests.py +++ b/tools/asahi/g17-m5-sibling-gate-tests.py @@ -322,6 +322,8 @@ def build(mutation=None): fn released_at(&self) -> u64 { 0 } fn vacancy_pending(&self) -> bool { false } fn pool_serves(&self, vm: u32) -> bool { self.pool_vm == vm } + // The backing of a closed owner, or of the asking one. + fn backing_free_for(&self, _: u64) -> bool { true } fn pool_fits(&self, required: ComputeCapacity) -> bool { self.pool_cap >= required.0 } fn has_ring(&self) -> bool { true } fn context(&self) -> Option<&Arc> { None } diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index f690f4473cd17..9adb38d865de6 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -179,7 +179,7 @@ def build(mutation=None): 'pub(crate) fn observe_vacancy(', 'pub(crate) fn shareable(', 'pub(crate) fn owner(&self)', 'pub(crate) fn channel_index(&self)', 'pub(crate) fn is_primary(&self)', 'pub(crate) fn active_len(&self)', 'pub(crate) fn has_replays(&self)', 'pub(crate) fn configuring(&self)', 'pub(crate) fn context(&self)', - 'pub(crate) fn bind_sibling(', 'pub(crate) fn bind_owner(&mut self', + 'pub(crate) fn bind_sibling(', 'pub(crate) fn bind_owner(&mut self', 'pub(crate) fn backing_free_for(', ]).replace('pub(crate) ', 'pub ').replace('mmu::Vm', 'Vm') \ .replace('crate::g17::freelist::Pages', 'Pages').replace('crate::g17::initdata::InitData', 'InitData') \ .replace('crate::g17::now_ns()', 'now_ns()').replace('crate::g17::freelist::control_consumed', 'control_consumed') @@ -218,18 +218,19 @@ def build(mutation=None): 'Some(SiblingSource::Fresh) =>', 'reserve_compute_channel(self.owner, self.compute_channels)', 'Err(qid) => {', 'self.rearm_vacant(\n qid,\n channel_index,\n required,', 'if !bound {', 'firmware.queues.release_rearm(qid, self.owner);', 'admission.check()?;', - 'return Ok(bound);', 'compute::PoolBacking::new('), + 'return Ok(bound);', 'let _ = self.finish_uninstalled_compute(retired);'), 'a re-arm binds the channel it was reserved for, through the primary path': ordered_ok( - rearm_vacant, 'crate::g17::freelist::Pages::for_compute(', 'compute::DescriptorRing::new(', + rearm_vacant, 'let mut state = self.shared.state.lock();', 'if !lease.is_current()', 'self.admission_open()', 'queue.qid() == qid && queue.can_rearm() && queue.rearm_open(self.owner)', '&& (channel_index == 0\n || firmware.queues.next_sibling_index(self.owner, self.compute_channels)\n' ' == Some(channel_index));', - 'firmware.queues.rearm_compute(qid, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', + 'firmware.queues.take_set(self.owner, required)', + 'firmware.queues.rearm_compute(qid, self.owner, pages, ring)', 'firmware.init.install_compute_pool(descriptor)?;', 'firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?;'), 'the primary re-arms channel 0': 'self.rearm_vacant(qid, 0, required,' in build_compute, 'the primary gives back other VMs\' queues through the same helper': ordered_ok( - rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant() && !queue.pool_serves(vm))', + rebind, '.filter(|queue| queue.reusable() && !queue.pool_vacant()\n && (!queue.pool_serves(vm) || !queue.backing_free_for(owner)))', 'if let Some(qid) = foreign {', 'self.give_back_foreign(qid)?;', 'return Err(ENOSPC);'), } checks = '\n'.join(f' assert!({str(ok).lower()}, "structure: {name}");' for name, ok in structure.items()) @@ -284,7 +285,7 @@ def build(mutation=None): pub struct PoolDescriptor(u32); pub struct InitData { control_cursor: std::cell::Cell } pub struct KernelMapping; -pub struct Vacated { _alias: Option, _pages: Option, _descriptors: Option, _ring: Option } +pub struct Vacated { _alias: Option, pages: Option, _descriptors: Option, ring: Option, _kit: Option<()>, owner: Option } pub struct FreeListRelease; enum ControlRecord { FreeListRelease(FreeListRelease) } struct Rings; @@ -326,7 +327,7 @@ def build(mutation=None): previous: Option<()>, source_hint: SourceHint, source_readers: AtomicU32, rearm_for: Option, pool: Pool, graph: Graph, binding: Option, release_sent_ns: Option, free_list_generation: u64, released_at: u64, claims: u32, awaiting_witness: bool, - channel_index: u8, sustained: bool, + channel_index: u8, sustained: bool, backing_owner: Option, } impl Queue { @@QUEUE@@ @@ -405,13 +406,15 @@ def build(mutation=None): graph: Graph { ring: Some(DescriptorRing), m5: true }, binding: Some(Binding { context: context.clone(), pool_alias: None, descriptors: None }), release_sent_ns: None, free_list_generation: 1, released_at: 0, claims: 0, awaiting_witness: false, - channel_index: 0, sustained: true, + channel_index: 0, sustained: true, backing_owner: Some(owner), } } /// An idle queue whose owner released it at `released_at`; its pool still serves `vm`. fn released(qid: u8, vm: u32, released_at: u64) -> Queue { let mut queue = bound(qid, 0, &Context::new(1000 + u32::from(qid), vm), 0); queue.owner = None; + // Its owner closed: the backing is no longer kept for it. + queue.backing_owner = None; queue.released = true; queue.released_at = released_at; queue.sustained = false; @@ -442,8 +445,7 @@ def build(mutation=None): Some(SiblingSource::Fresh) => Ok(false), Some(SiblingSource::Vacant(qid)) => { reg.reserve_rearm(qid, owner)?; - // Off the device mutex: fresh pages and a descriptor ring; then, locked again, the - // production rearm_vacant() checks and steps. + // The production rearm_vacant() checks and steps, with the owner's spare pages and ring. let ready = { let queue = reg.queue(qid); queue.can_rearm() && queue.rearm_open(owner) @@ -452,7 +454,7 @@ def build(mutation=None): reg.release_rearm(qid, owner); return Ok(false); } - let (descriptor, _vacated) = reg.rearm_compute(qid, Pages(2), DescriptorRing)?; + let (descriptor, _vacated) = reg.rearm_compute(qid, owner, Pages(2), DescriptorRing)?; assert_eq!(descriptor, PoolDescriptor(u32::from(qid)), "the re-armed queue's row is written"); reg.bind_rearmed(qid, owner, context, channel_index)?; Ok(true) @@ -610,9 +612,12 @@ def build(mutation=None): reg.push(bound(10, B, &b, 2)); reg.push(released(12, 999, 6)); assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Fresh)); - // A warm same-VM queue comes before a vacant one. + // A closed owner's charge cannot follow the ring to another queue, even in the same VM. reg.push(vacant(11, 1)); reg.push(released(18, 200, 9)); + assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Vacant(11))); + // A warm same-VM queue retaining B's own backing comes before a vacant one. + reg.compute_queue_mut(18).unwrap().backing_owner = Some(B); assert_eq!(reg.sibling_source(B, &b, req), Some(SiblingSource::Warm(18))); assert_eq!(reg.bind_reusable_sibling(B, &b, 3, req), Ok(Some(true))); assert_eq!(reg.queue(18).channel_index, 1); diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 87c2396c1dcd5..6bd0fe837e49f 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -216,7 +216,7 @@ def context_source(text): } /// A firmware object: `id` is unique per allocation, the mapping is its address. -pub struct KernelObject { pub id: u64, pub mapping: Option, bytes: Vec } +pub struct KernelObject { pub charge: Option, pub id: u64, pub mapping: Option, bytes: Vec } impl KernelObject { pub fn size(&self) -> usize { self.bytes.len() } pub fn bytes_mut(&mut self) -> &mut [u8] { &mut self.bytes } @@ -237,12 +237,12 @@ def context_source(text): /// The control-ring witness when `id` was unmapped. pub fn unmapped_at(id: u64) -> Option { UNMAPPED_AT.with(|u| u.borrow().get(&id).copied()) } -pub struct Allocator<'a> { pub next: &'a Cell } +pub struct Allocator<'a> { pub client: Option, pub next: &'a Cell } impl Allocator<'_> { pub fn kernel(&self, size: usize, _align: u64, _prot: mmu::Prot, _cpu: impl Sized) -> Result { let id = self.next.get(); self.next.set(id + 1); - Ok(KernelObject { id, mapping: Some(mmu::KernelMapping { iova: id << 20 }), bytes: vec![0xa5; size] }) + Ok(KernelObject { charge: self.client, id, mapping: Some(mmu::KernelMapping { iova: id << 20 }), bytes: vec![0xa5; size] }) } } @@ -348,7 +348,7 @@ def context_source(text): pub fn differential(ops: &[crate::Op], after_release: bool) -> Vec { crate::channel::set(0, 0); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = $new(after_release); let mut live: Vec> = (0..5).map(|_| Vec::new()).collect(); let mut trace = Vec::new(); @@ -428,10 +428,28 @@ def context_source(text): /// Uncached pooled objects (`prefix == 0`) skip `set_fw_cached_prefix` while keeping /// their pool lease, fence, return mark, reuse zeroing and retention until stop. + pub fn client_pool_retirement() { + let next = Cell::new(1); + let a = Allocator { client: Some(1), next: &next }; + let b = Allocator { client: Some(2), next: &next }; + let pool = Pool::new(false).unwrap(); + crate::forget_unmapped(); + crate::channel::set(3, 3); + let original = work_state(&pool, &a); + let id = original.id; + drop(original); + assert!(!unmapped(id)); + crate::channel::set(4, 4); + let new = work_state(&pool, &b); + assert_eq!(new.charge, b.client); + assert_ne!(new.id, id); + assert!(unmapped(id)); + } + pub fn uncached_pooled() { for after_release in [true, false] { let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(5, 3); @@ -480,7 +498,7 @@ def context_source(text): crate::forget_unmapped(); crate::channel::set(0, 0); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); let mut cached = Vec::new(); let page = mmu::UAT_PGSZ; @@ -512,7 +530,7 @@ def context_source(text): /// Each return class decides the fence; reuse never waits on a met fence. pub fn return_classes() { let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(true).unwrap(); // Three records published, two of them consumed. crate::channel::set(3, 1); @@ -600,7 +618,7 @@ def context_source(text): let what = format!("{family:?}, after_release {after_release}"); let line = format!("cached_objects_{} ", family as usize); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); let get = || match family { Family::WorkState => work_state(&pool, &alloc), @@ -674,7 +692,7 @@ def context_source(text): // An uncached object kept until stop leaves the deferred list alone. let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(10, 7); @@ -707,7 +725,7 @@ def context_source(text): pub fn model(seed: u64, steps: usize) { crate::channel::set(0, 0); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(true).unwrap(); crate::forget_unmapped(); let mut rng = crate::Rng(seed); @@ -866,7 +884,7 @@ def context_source(text): pub fn accessors() { for after_release in [true, false] { let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(6, 4); @@ -933,7 +951,7 @@ def context_source(text): for after_release in [true, false] { let what = format!("after_release {after_release}"); let next = Cell::new(1); - let alloc = Allocator { next: &next }; + let alloc = Allocator { client: None, next: &next }; let pool = Pool::new(after_release).unwrap(); crate::forget_unmapped(); crate::channel::set(10, 7); @@ -985,6 +1003,7 @@ def context_source(text): } fn main() { + now::client_pool_retirement(); now::cached_queue_lifetimes(); now::uncached_pooled(); now::return_classes(); @@ -1075,7 +1094,7 @@ def need(text, pattern, what): need(compute, r'Family::Descriptor,\s*size,\s*if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ size \},', 'compute descriptors: M5 uncached, G17P cached') # The compute graph, whose queue record is rebound in place, is an ordinary uncached allocation. - need(compute, r'let mut graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', + need(compute, r'let graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', 'compute graph uncached') if 'Family::QueueState' in compute: failures.append('compute graph not pooled') diff --git a/tools/asahi/g17-queue-object-charge-tests.py b/tools/asahi/g17-queue-object-charge-tests.py new file mode 100644 index 0000000000000..275942570136e --- /dev/null +++ b/tools/asahi/g17-queue-object-charge-tests.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Kernel objects a client's ioctls build for its queues are charged to that client. + +The G17 code builds per-queue firmware objects through an `Allocator` that +names the client whose queue they are for. Two ioctls build them, where a +failure comes back from the ioctl, so their Allocators name the client and +their objects are charged to it: +- QUEUE_CREATE builds the context (scheduler storage, work state) in + `Backend::new`; +- a compute SUBMIT builds its queue's compute backing (pool pages, descriptor + ring) in `Backend::provision_backing`. + +Everything else is built at publication, after SUBMIT accepted the job, or is +device memory: render pairs, rings, generations, tiler heaps, timestamps, and +the compute kit and shared compute objects, which outlive the client. A +failure at publication would cost the client its device, so these stay +uncharged (`client: None`, plain `KernelObject::backing`) until they are +built at QUEUE_CREATE or SUBMIT. That work then charges them and empties +PUBLICATION below. This test fails when the split moves: + +- every `Allocator { .. }` literal sets `client`; exactly the two above name + the client, and all others say None; +- `KernelObject::backing`, `KernelObject::new` and `gem::new_kernel_object*` + appear only in object.rs, the global boot files and the PUBLICATION files. + +--mutation drop-client / uncharged-backing / none-client / uncharged-compute / +charged-kit inject each fault and must be caught. +""" +import argparse +import re +import sys +from pathlib import Path + +G17 = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' +GLOBAL = {'object.rs', 'initdata.rs', 'initdata/m5.rs', 'mod.rs'} +# Built at publication; uncharged until they are built at QUEUE_CREATE or SUBMIT. +PUBLICATION = {'buffer.rs', 'buffer/target.rs', 'completion.rs'} +UNCHARGED = re.compile(r'KernelObject::(backing|new)\(|gem::new_kernel_object(_wc)?\(') +LITERAL = re.compile(r'Allocator\s*\{(?P[^{}]*)\}', re.S) + + +def sources(mutation): + files = {str(p.relative_to(G17)): p.read_text() for p in sorted(G17.rglob('*.rs'))} + if mutation == 'drop-client': + k = 'runtime.rs' + files[k] = files[k].replace('client: vm.memory_client(),', '', 1) + elif mutation == 'uncharged-backing': + k = 'queue/render/memory.rs' + files[k] = files[k].replace('alloc.backing(size, CpuMap::WriteCombined)', + 'KernelObject::backing(alloc.dev, size, CpuMap::WriteCombined)', 1) + elif mutation == 'none-client': + k = 'runtime.rs' + files[k] = files[k].replace('client: vm.memory_client(),', 'client: None,', 1) + elif mutation == 'uncharged-compute': + k = 'runtime.rs' + files[k] = files[k].replace('let charged = super::object::Allocator { dev: &dev, uat: &uat, client };', + 'let charged = super::object::Allocator { dev: &dev, uat: &uat, client: None };', 1) + elif mutation == 'charged-kit': + k = 'runtime.rs' + files[k] = files[k].replace('let device = super::object::Allocator { dev: &dev, uat: &uat, client: None };', + 'let device = super::object::Allocator { dev: &dev, uat: &uat, client };', 1) + return files + + +def line(text, pos): + return text.count('\n', 0, pos) + 1 + + +def check(files): + failures = [] + named = [] + literals = 0 + for name, text in files.items(): + code = '\n'.join(l.split('//')[0] for l in text.split('\n')) + for m in LITERAL.finditer(code): + body = m.group('body') + if 'dev' not in body or 'uat' not in body: + continue # the struct definition or an unrelated type + if name == 'object.rs' and 'pub(crate) dev' in body: + continue + literals += 1 + if 'client' not in body: + failures.append(f'FAIL line {line(code, m.start())}: {name}: Allocator without a client') + elif not re.search(r'client:\s*None', body): + functions = re.findall(r'\bfn (\w+)\s*[<(]', code[:m.start()]) + named.append((name, functions[-1] if functions else '')) + if name not in GLOBAL | PUBLICATION: + for m in UNCHARGED.finditer(code): + failures.append(f'FAIL line {line(code, m.start())}: {name}: uncharged kernel object ' + f'{m.group(0)} outside the global boot and publication files') + # QUEUE_CREATE's context and a compute SUBMIT's backing are the allocators that name a client. + if sorted(named) != [('runtime.rs', 'new'), ('runtime.rs', 'provision_backing')]: + failures.append(f'FAIL line 0: allocators naming a client {named}, expected only ' + "QUEUE_CREATE's context (Backend::new) and SUBMIT's compute backing " + '(Backend::provision_backing)') + if literals < 10: + failures.append(f'FAIL line 0: only {literals} Allocator literals found; the scan is broken') + return failures + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--mutation', choices=['drop-client', 'uncharged-backing', 'none-client', + 'uncharged-compute', 'charged-kit']) + args = parser.parse_args() + failures = check(sources(args.mutation)) + for f in failures: + print(f) + if failures: + sys.exit(1) + print("ok: QUEUE_CREATE's context and SUBMIT's compute backing are charged to the client, " + "publication's objects and device memory are not") + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g17-resource-tests.py b/tools/asahi/g17-resource-tests.py index 31d24d19afee2..dabfe40fbe655 100644 --- a/tools/asahi/g17-resource-tests.py +++ b/tools/asahi/g17-resource-tests.py @@ -392,6 +392,7 @@ def shared_alias_tests(root, source): } struct Allocator<'a> {dev:&'a Device,uat:&'a Uat} impl Allocator<'_> { + fn backing(&self,size:usize,cpu:CpuMap)->Result {KernelObject::backing(self.dev,size,cpu)} '''+method+''' } fn case(obstacles:&[(usize,u64,u64)],fault:Option,size:usize,expected:std::result::Result,attempts:usize) { diff --git a/tools/asahi/g17-uninstalled-cleanup-tests.py b/tools/asahi/g17-uninstalled-cleanup-tests.py index d74f67aba6267..15edba3f67e3a 100644 --- a/tools/asahi/g17-uninstalled-cleanup-tests.py +++ b/tools/asahi/g17-uninstalled-cleanup-tests.py @@ -23,8 +23,8 @@ def fixture(): assert 'retired = entry.queue.take().map(|queue| (entry.reservation, queue));' in abort assert 'self.finish_uninstalled_compute(retired)?;' in abort assert 'cancel_unpublished' not in abort - start=abort.index(' drop(state);\n // Tentative replacement mappings') - end=abort.index('\n }',start) + start=abort.index(' // Tentative replacement mappings') + end=abort.index(' self.shared.queue_events();\n }',start)+len(' self.shared.queue_events();\n }') cleanup=abort[start:end] return r''' use std::sync::{Arc,Mutex,atomic::{AtomicBool,Ordering}}; @@ -45,15 +45,27 @@ def fixture(): assert!(!ALIAS.load(Ordering::SeqCst)&&!PAGES.load(Ordering::SeqCst),"tentative aliases still live at identity return"); MAPPED.store(false,Ordering::SeqCst); }} +impl Queue {fn take_backing(&mut self)->Vacated{Vacated}} struct Tentative(&'static AtomicBool); impl Drop for Tentative{fn drop(&mut self){assert!(!LOCKED.load(Ordering::SeqCst));self.0.store(false,Ordering::SeqCst);}} +/// A queue's backing on its way back to its owner. +struct Vacated; +impl Vacated {fn drop_aliases(&mut self){assert!(!LOCKED.load(Ordering::SeqCst));}} +impl Drop for Vacated {fn drop(&mut self){assert!(!LOCKED.load(Ordering::SeqCst),"backing freed under device mutex");}} mod compute {pub(crate) use crate::Queue;} struct Registry; -impl Registry {fn cancel_compute(&mut self,res:ComputeReservation)->Result{ - assert_eq!(res.0,7); - assert!(!MAPPED.load(Ordering::SeqCst),"identity returned before aliases disappeared"); - assert!(RESERVED.swap(false,Ordering::SeqCst));Ok(()) -}} +impl Registry { + fn cancel_compute(&mut self,res:ComputeReservation)->Result{ + assert_eq!(res.0,7); + assert!(!MAPPED.load(Ordering::SeqCst),"identity returned before aliases disappeared"); + assert!(RESERVED.swap(false,Ordering::SeqCst));Ok(()) + } + fn keep_returned(&mut self,_:&mut Vacated){assert!(LOCKED.load(Ordering::SeqCst));} + // The tentative pages go back to their owner, no longer the builder's. + fn put_back(&mut self,_:u64,pages:Option,_:Option<()>,_:Option<()>)->Vacated{ + if let Some(pages)=pages{std::mem::forget(pages);PAGES.store(false,Ordering::SeqCst);}Vacated + } +} struct Firmware{queues:Registry} struct Guard<'a>(std::sync::MutexGuard<'a,Option>>); impl Deref for Guard<'_>{type Target=Option>;fn deref(&self)->&Self::Target{&self.0}} @@ -64,20 +76,20 @@ def fixture(): struct Available; impl Available {fn notify(&self){}} struct Shared{state:State,channels:Available} impl Shared{fn queue_events(&self){}} -struct Backend{shared:Arc} +struct Backend{shared:Arc,owner:u64} impl Backend { ''' +helper+r''' fn growth_cleanup(&self)->Result{ let mut alias=Some(Tentative(&ALIAS));let mut pages=Some(Tentative(&PAGES)); ALIAS.store(true,Ordering::SeqCst);PAGES.store(true,Ordering::SeqCst); let retired=Some((ComputeReservation(7),Box::new(Queue))); - let state=self.shared.state.lock(); + let (growth,result)=(Some(()),Err::<(),i32>(-11)); ''' +cleanup+r''' Ok(()) } } fn main(){ - let b=Backend{shared:Arc::new(Shared{state:State(Mutex::new(Some(Box::new(Firmware{queues:Registry})))),channels:Available})}; + let b=Backend{owner:1,shared:Arc::new(Shared{state:State(Mutex::new(Some(Box::new(Firmware{queues:Registry})))),channels:Available})}; b.finish_uninstalled_compute(None).unwrap(); for _ in 0..512 { MAPPED.store(true,Ordering::SeqCst);RESERVED.store(true,Ordering::SeqCst); @@ -95,8 +107,8 @@ def fixture(): def main(): source=fixture() cases=[('fixed',source),('cancel-before-alias-drop',source.replace('drop(queue);','core::mem::forget(queue);')), - ('keep-tentative-growth-aliases',source.replace('drop(alias.take());','').replace('drop(pages.take());','')), - ('drop-under-device-mutex',source.replace(' drop(queue);\n','').replace(' let mut state = self.shared.state.lock();',' let mut state = self.shared.state.lock();\n drop(queue);'))] + ('keep-tentative-growth-aliases',source.replace('drop(alias.take());','')), + ('drop-under-device-mutex',source.replace(' drop(queue);\n backing.drop_aliases();\n let mut state = self.shared.state.lock();',' backing.drop_aliases();\n let mut state = self.shared.state.lock();\n drop(queue);'))] with tempfile.TemporaryDirectory(prefix='g17-uninstalled-') as tmp: for name,code in cases: path=Path(tmp)/(name+'.rs');path.write_text(code);binary=path.with_suffix('') diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index ec411fc648a87..bf0885209d9e6 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -431,6 +431,10 @@ def mutations(flag, names, base, expect=KILL): 'g17-chunk-work-guard-tests.py': [([], PASS)] + mutations('--mutation', ('no-guard', 'no-finish-enqueue'), []), 'g17-compute-constructor-tests.py': [([], PASS)], + 'g17-compute-reserve-tests.py': [([], PASS)] + mutations( + '--mutation', ['allocating-bind', 'allocating-graph', 'publication-allocates', + 'claim-after-provision', 'free-returned', 'bind-other-owner', 'kit-needs-qid', + 'keep-idle'], []), 'g17-compute-owed-stamp-tests.py': [([], PASS)] + mutations('--mutation', ('own-finished', 'no-retire-glue', 'retire-unchecked', 'no-expiry', 'no-step-past', 'pop-owed', 'head-includes-owed', 'held-stamped-pops', @@ -481,7 +485,6 @@ def mutations(flag, names, base, expect=KILL): 'skip-pending-error-fallback', 'single-slot-bailout', 'skip-epoch-check', - 'unconditional-changed-notify', 'skip-generation-bump'), []), 'g17-m5-cross-qid-direct-tests.py': [([], PASS)] + mutations('--mutation', ('no-chain-dedup', @@ -608,6 +611,9 @@ def mutations(flag, names, base, expect=KILL): 'wrong-j813-pipe'), []), 'g17-resource-tests.py': [([], PASS)], 'g17-shared-pool-tests.py': [([], PASS)], + 'g17-queue-object-charge-tests.py': [([], PASS)] + mutations( + '--mutation', ['drop-client', 'uncharged-backing', 'none-client', 'uncharged-compute', + 'charged-kit'], []), 'g17-t6041-initdata-tests.py': [([], PASS)], 'g17-uninstalled-cleanup-tests.py': [([], PASS)], 'g17-unpublished-tests.py': [([], PASS)],