diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 0ab365a54a989..5ffeea685de63 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -295,6 +295,24 @@ impl Kill { } } +/// 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, @@ -320,6 +338,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, @@ -474,6 +495,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), @@ -519,6 +541,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/fence.rs b/drivers/gpu/drm/asahi/g17/fence.rs index f64e82b3076bf..80647f7c5e560 100644 --- a/drivers/gpu/drm/asahi/g17/fence.rs +++ b/drivers/gpu/drm/asahi/g17/fence.rs @@ -703,13 +703,29 @@ mod tests { assert!(!untouched_refusal(false, &Ok(()))); } + #[test] + fn nothing_queued_and_restarted_leaves_outputs_untouched() { + for error in [ERESTARTSYS, EAGAIN, ENOMEM, ENOSPC] { + assert!(untouched(false, &Err(error))); + assert!(!untouched(true, &Err(error))); + } + assert!(!untouched(false, &Err(EIO))); + assert!(!untouched(false, &Err(EBUSY))); + assert!(!untouched(false, &Ok(()))); + } + #[test] fn enomem_and_enospc_after_publication_become_eio() { assert_eq!(submit_result(true, Err(ENOMEM)), Err(EIO)); assert_eq!(submit_result(true, Err(ENOSPC)), Err(EIO)); + // A restart after publication would queue the published commands again. + assert_eq!(submit_result(true, Err(ERESTARTSYS)), Err(EIO)); + assert_eq!(submit_result(true, Err(EAGAIN)), Err(EIO)); // Before publication they keep their meaning: nothing changed. assert_eq!(submit_result(false, Err(ENOMEM)), Err(ENOMEM)); assert_eq!(submit_result(false, Err(ENOSPC)), Err(ENOSPC)); + assert_eq!(submit_result(false, Err(ERESTARTSYS)), Err(ERESTARTSYS)); + assert_eq!(submit_result(false, Err(EAGAIN)), Err(EAGAIN)); // Other results are never rewritten. assert_eq!(submit_result(true, Err(EINVAL)), Err(EINVAL)); assert_eq!(submit_result(true, Ok(())), Ok(())); @@ -922,6 +938,68 @@ mod tests { } } + #[test] + fn a_restart_before_the_first_command_leaves_outputs_untouched() -> Result { + let contexts = contexts(); + let allocation_failure = allocation_failure(&contexts)?; + // A binary syncobj with a completed fence, and timelines at point 1. + let binary = kernel::drm::syncobj::SyncObj::new_kunit()?; + let previous = independent(&contexts)?; + binary.replace_fence(Some(&Fence::from_fence(&previous))); + previous.signal(); + let timeline = kernel::drm::syncobj::SyncObj::new_kunit()?; + let anchor = kernel::drm::syncobj::SyncObj::new_kunit()?; + for syncobj in [&timeline, &anchor] { + let point1 = independent(&contexts)?; + syncobj.add_point(kernel::dma_fence::FenceChain::new()?, &Fence::from_fence(&point1), 1); + point1.signal(); + } + let cumulative = || -> Result> { + let mut syncs = KVVec::with_capacity(3, GFP_KERNEL)?; + syncs.push(cumulative_item(anchor.clone(), 2), GFP_KERNEL)?; + syncs.push(timeline_item(timeline.clone(), 2)?, GFP_KERNEL)?; + let bundle = super::super::sync_output::SignalBundle::new(&syncs, 0)?; + syncs[0].cumulative = Some(bundle); + Ok(syncs) + }; + let mut syncs = KVVec::with_capacity(2, GFP_KERNEL)?; + syncs.push(SyncItem { syncobj: binary.clone(), fence: None, chain_fence: None, timeline_value: 0, + cumulative: None, timeline: false }, GFP_KERNEL)?; + syncs.push(timeline_item(timeline.clone(), 2)?, GFP_KERNEL)?; + // The submission's fence is prepared before the first command, whose compute provisioning + // is interrupted: SUBMIT's install gate (queue/mod.rs) keeps the outputs as they were. + for (syncs, error) in [(syncs, ERESTARTSYS), (cumulative()?, ERESTARTSYS), (cumulative()?, EAGAIN)] { + let mut outputs = Outputs::new(&contexts, syncs, 0, &allocation_failure)?; + let aggregate = outputs.publish_with(None, false, false)?; + if !untouched(false, &Err(error)) { + outputs.install(); + } + let result = submit_result(outputs.published(), Err(error)); + assert_eq!(result, Err(error)); + outputs.set_result(result); + drop(outputs); + drop(aggregate); + } + let kept = binary.fence_get().unwrap(); + assert_eq!(kept.raw(), Fence::from_fence(&previous).raw()); + assert_eq!(timeline.fence_get().unwrap().chain_find_seqno(2).err(), Some(EINVAL)); + assert_eq!(anchor.fence_get().unwrap().chain_find_seqno(2).err(), Some(EINVAL)); + // The restarted SUBMIT publishes point 2 once, chained on point 1, without error. + let mut retry = Outputs::new(&contexts, cumulative()?, 0, &allocation_failure)?; + let aggregate = retry.publish_with(None, false, false)?; + let member = aggregate.member(); + retry.install(); + retry.set_result(Ok(())); + drop(retry); + member.complete(Ok(())); + drop(member); + for syncobj in [&anchor, &timeline] { + let point2 = syncobj.fence_get().unwrap().chain_find_seqno(2)?.unwrap(); + assert!(super::super::job::fence_status(&point2) > 0); + } + Ok(()) + } + #[test] fn full_window_signal_leaves_timeline_untouched_for_restart() -> Result { unsafe extern "C" { @@ -1408,11 +1486,29 @@ pub(crate) fn untouched_refusal(published: bool, result: &Result) -> bool { !published && matches!(result, Err(error) if *error == ENOMEM || *error == ENOSPC) } -/// The result a submission returns. ENOMEM and ENOSPC promise that nothing changed, so the same -/// failures after its outputs were published are returned as EIO: the outputs carry the failure. +/// Whether the ioctl returns `result` to be called again as it is: interrupted (ERESTARTSYS), or +/// to retry (EAGAIN). libdrm's drmIoctl() restarts both. +pub(crate) fn retried(result: &Result) -> bool { + matches!(result, Err(error) if *error == ERESTARTSYS || *error == EAGAIN) +} + +/// Whether a submission's outputs stay untouched: none of its commands was queued (`queued` +/// false), and it was refused ([`untouched_refusal`]) or is to be called again as it is +/// ([`retried`]). A compute command's SUBMIT-time provisioning can wait interruptibly before the +/// first command is queued; its fence in the outputs would carry an error for a submission the +/// restart then queues, and be the previous point a cumulative timeline chains on. +pub(crate) fn untouched(queued: bool, result: &Result) -> bool { + !queued && (untouched_refusal(false, result) || retried(result)) +} + +/// The result a submission returns. ENOMEM and ENOSPC promise that nothing changed, and +/// ERESTARTSYS and EAGAIN have the ioctl called again as it is, so the same results after its +/// outputs were published are returned as EIO: the outputs carry the failure, and a restart would +/// queue the commands already queued a second time. A compute command's SUBMIT-time provisioning +/// can wait for a recovery or for reclaim after earlier commands of the submission were queued. pub(crate) fn submit_result(published: bool, result: Result) -> Result { match result { - Err(error) if published && (error == ENOMEM || error == ENOSPC) => Err(EIO), + Err(error) if published && [ENOMEM, ENOSPC, ERESTARTSYS, EAGAIN].contains(&error) => Err(EIO), result => result, } } @@ -1490,7 +1586,7 @@ impl Outputs { } /// The fence installed, or about to be installed on error, in every output sync. pub(crate) fn output_fence(&self) -> Option { - if self.submission.is_none() && self.result == Err(ERESTARTSYS) { + if self.submission.is_none() && retried(&self.result) { return None; } self.submission @@ -1548,7 +1644,7 @@ impl Drop for Outputs { chunk.finish_enqueue(self.result); } if self.submission.is_some() { - if !self.installed && !untouched_refusal(false, &self.result) { + if !self.installed && !untouched(false, &self.result) { self.install(); } let Some(submission) = self.submission.take() else { @@ -1567,7 +1663,7 @@ impl Drop for Outputs { if let Some(fallback) = self.fallback.take() { // No work was accepted and no fence was published; leave output // syncobjs untouched so a restarted ioctl can publish them once. - if self.result == Err(ERESTARTSYS) { + if retried(&self.result) { return; } if let Err(error) = self.result { diff --git a/drivers/gpu/drm/asahi/g17/freelist.rs b/drivers/gpu/drm/asahi/g17/freelist.rs index e68551713e831..3d8660b27b07f 100644 --- a/drivers/gpu/drm/asahi/g17/freelist.rs +++ b/drivers/gpu/drm/asahi/g17/freelist.rs @@ -376,6 +376,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; @@ -436,8 +450,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)) @@ -497,6 +512,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 { @@ -1092,6 +1120,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 @@ -1108,33 +1153,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 { @@ -1203,12 +1237,13 @@ impl ComputePool { /// rewrites the page-pool descriptor row before the queue is kicked again. /// As render repopulation does, the firmware-completed counter is carried /// over so it stays consistent with the host submitted counter in `state`. - pub(crate) fn rearm(&mut self, pages: Pages) -> Result { + /// Takes `pages` only once they are written in: on failure they stay with the caller. + pub(crate) fn rearm(&mut self, pages: &mut Option) -> Result { if self.pages.is_some() { return Err(EBUSY); } - self.write_pages(&pages)?; - self.pages = Some(pages); + self.write_pages(pages.as_ref().ok_or(EINVAL)?)?; + self.pages = pages.take(); Ok(()) } /// Preserve both sets of pages on failure. The caller owns the consumed diff --git a/drivers/gpu/drm/asahi/g17/initdata.rs b/drivers/gpu/drm/asahi/g17/initdata.rs index 499359d3d4559..97b815b963029 100644 --- a/drivers/gpu/drm/asahi/g17/initdata.rs +++ b/drivers/gpu/drm/asahi/g17/initdata.rs @@ -519,12 +519,23 @@ impl InitData { self.compute_shared.is_some() } - /// Install a prepared pool once while holding the device mutex. A competing preparer may - /// have installed its own first; the redundant one then drops. - pub(super) fn install_compute_shared(&mut self, shared: ComputeShared) -> Result { + /// Whether this firmware's InitData has the objects the device-wide compute aperture and + /// scheduler serve: the boot free list's control and state. An M5 build has none, whatever + /// its compute program. + pub(super) fn hosts_compute_aperture(&self) -> bool { + self.boot_control.is_some() && self.boot_state.is_some() + } + + /// Install the pool in `prepared` once while holding the device mutex, taking it only once + /// the install succeeded: a failed install leaves it prepared. A competing preparer may + /// have installed its own first; the redundant one then stays in `prepared`. + pub(super) fn install_compute_shared(&mut self, prepared: &mut Option) -> Result { if self.compute_shared.is_some() { return Ok(()); } + if prepared.is_none() { + return Err(EIO); + } let boot_control = self.boot_control.ok_or(ENODEV)?; let boot_state = self.boot_state.ok_or(ENODEV)?; let state_va = self.object(boot_state)?.gpu_va(); @@ -541,7 +552,7 @@ impl InitData { self.object_mut(boot_control)?.write(0, control)?; self.object_mut(boot_state)?.bytes_mut().fill(0); fence(Ordering::SeqCst); - self.compute_shared = Some(shared); + self.compute_shared = prepared.take(); Ok(()) } diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index 2f0f46b2f09e3..0ec025183f489 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: KVVec, @@ -173,6 +175,7 @@ impl Packet { inputs: KVVec, shared_inputs: Option, producers: Option, + claim: Option, ) -> Result> { if command.is_none() { return Err(EINVAL); @@ -188,6 +191,7 @@ impl Packet { order, completion, footprint, + _claim: claim, batch_renders, inputs, shared_inputs, 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 a22bcbb462549..dc4adde3c4625 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::{ @@ -1348,39 +1347,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 { @@ -1425,6 +1391,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, @@ -1514,8 +1482,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, } @@ -1838,7 +1804,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(); } @@ -2370,11 +2335,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/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 4a8cdb87cddd9..599a8a1db61c0 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::{ @@ -73,13 +74,55 @@ static_assert!(core::mem::offset_of!(GraphLayout, items) == ITEMS); /// Aliases are destroyed before the logical root they name. Superseded bindings remain owned /// until the first exact successful publication under their replacement has retired. -/// Backing of a vacated pool and descriptor ring, freed outside the device -/// mutex. Field order drops each client alias before the storage it names. +/// Backing of a vacated pool and descriptor ring, freed or returned to its owner outside the +/// device 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, + /// The owner's spares, which the pages and ring return to when this is dropped. + returns: Option>, +} + +impl Drop for Vacated { + fn drop(&mut self) { + let Some(reserve) = self.returns.take() else { return }; + // The pages and ring map at the same client addresses again: their views go first. + self.drop_aliases(); + reserve.give_back(self.pages.take(), self.ring.take()); + } +} + +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, returns: None } + } + /// The owner the pages and ring go back to. + pub(crate) fn returns_to(&self) -> Option { + self.owner + } + /// Returns the pages and ring to `reserve`, their owner's, when this is dropped. + pub(crate) fn return_to(&mut self, reserve: Arc) { + self.returns = Some(reserve); + } + /// Whether dropping this frees pool pages or a ring, rather than returning them to their + /// owner or freeing only client views. + pub(crate) fn frees_backing(&self) -> bool { + self.returns.is_none() && (self.pages.is_some() || self.ring.is_some()) + } + /// 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 +178,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 +218,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 +248,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 +268,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 +321,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 +358,7 @@ impl Graph { board, program, mcache, - }) + } } /// All fallible mapping work finishes before replacing a physical queue's logical owner. @@ -281,23 +367,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 +690,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 +807,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 +849,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 +866,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 +923,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 +948,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 @@ -2068,6 +2146,42 @@ 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(), + returns: None, + } + } /// Binds a reusable physical queue with its own dedicated compute pool as an additional /// compute channel of `owner`. pub(crate) fn bind_sibling( @@ -2087,7 +2201,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)?; @@ -2261,9 +2375,12 @@ 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(), + returns: None, }) } /// An idle retained queue whose USC backing may be given back. @@ -2456,45 +2573,50 @@ 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(), + returns: None, })) } /// Installs fresh backing into a vacant pool; returns the descriptor row data /// the caller writes before binding an owner, plus any previous sibling descriptor /// ring to drop off-lock. + /// Takes `pages` and `ring` only on success: on failure the queue is unchanged and both stay + /// with the caller, to go back to their owner. pub(crate) fn rearm( &mut self, - pages: crate::g17::freelist::Pages, - ring: DescriptorRing, + owner: u64, + pages: &mut Option, + ring: &mut Option, ) -> Result<(PoolDescriptor, Option)> { if !self.can_rearm() { return Err(EAGAIN); } + if ring.is_none() { + return Err(EINVAL); + } + self.pool.rearm(pages)?; let descriptors = self .binding .as_mut() .and_then(|binding| binding.descriptors.take()); - let old_ring = self.graph.rearm_ring(ring); - if let Err(error) = self.pool.rearm(pages) { - if let Some(old) = old_ring { - let _ = self.graph.rearm_ring(old); - } - if let (Some(binding), Some(descriptors)) = (self.binding.as_mut(), descriptors) { - binding.descriptors = Some(descriptors); - } - return Err(error); - } + let old_ring = self.graph.rearm_ring(ring.take().ok_or(EINVAL)?); self.pool_phase = PoolPhase::Populated; self.release_sent_ns = None; 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, + returns: None, }); + self.backing_owner = Some(owner); Ok((self.pool.descriptor()?, vacated)) } pub(crate) fn pool_fits(&self, required: ComputeCapacity) -> bool { @@ -2569,11 +2691,16 @@ 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, + returns: None, }) } 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..bbcc0dace9962 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/queue/compute/reserve.rs @@ -0,0 +1,315 @@ +// 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. +//! +//! The spares are behind their own lock ([`Reserve`]), so backing a queue gives back returns to +//! them off the device mutex, once its client views are gone: the same pages and ring map at the +//! same client addresses again. +//! +//! [`Kit`]: super::Kit + +use crate::g17::freelist::ComputeCapacity; +use kernel::{ + new_mutex, + prelude::*, + sync::{Arc, Mutex, MutexGuard}, +}; + +/// 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()) + } +} + +/// The spares of one owner. +pub(crate) type OwnerSpares = Spares; + +impl Reserve { + /// The spares. Taken under the device mutex too; nothing takes the device mutex under it. + pub(crate) fn lock(&self) -> MutexGuard<'_, OwnerSpares> { + self.spares.lock() + } + + /// Keeps pages and a ring a queue gave back, off the device mutex and after their client + /// views are gone ([`super::Vacated`]), and wakes a publication that waits for them. Pages + /// whose tables cannot be written again are freed; the owner's next SUBMIT provisions. + pub(crate) fn give_back( + &self, + pages: Option, + ring: Option, + ) { + // Unreset tables would hand the firmware the old free list. + let pages = pages.and_then(|mut pages| pages.reset().is_ok().then_some(pages)); + let ring = ring.map(|mut ring| { + ring.clear(); + ring + }); + let unused = { + let mut spares = self.lock(); + ( + pages.and_then(|pages| spares.put_pages(pages)), + ring.and_then(|ring| spares.put_ring(ring)), + ) + }; + drop(unused); + self.returned.notify(); + } +} + +/// An owner's spares behind their own lock, shared with the backing its queues give back. +#[pin_data] +pub(crate) struct Reserve { + #[pin] + spares: Mutex, + /// Woken when backing comes back: the device's compute channel waiters. + returned: Arc, +} + +impl Reserve { + pub(crate) fn new(returned: Arc) -> Result> { + Arc::pin_init( + pin_init!(Self { + spares <- new_mutex!(Spares::new(), "g17::compute::Reserve"), + returned, + }), + GFP_KERNEL, + ) + } +} + +#[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 9681fe4aee416..b2907a5615426 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -289,6 +289,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 { let command = entry.command.as_ref().ok_or(EIO)?; self.ensure_compute(command)?; @@ -493,6 +497,7 @@ impl Queue { checked_inputs, command_inputs, producers, + claim, )?; let scheduler = match engine { Engine::Render => &mut self.render, @@ -808,9 +813,10 @@ impl crate::queue::Queue for Queue { } Ok(()) })(); - // Queued commands need their outputs to carry the submission's fence. A refusal before - // the first one was queued leaves them untouched. - if !super::fence::untouched_refusal(enqueued != 0, &result) { + // Queued commands need their outputs to carry the submission's fence. A refusal, or a + // restart (a compute command's provisioning waits interruptibly), before the first one was + // queued leaves them untouched. + if !super::fence::untouched(enqueued != 0, &result) { outputs.install(); if outputs.published() { let output_fence = outputs.output_fence(); @@ -839,7 +845,7 @@ impl crate::queue::Queue for Queue { } let result = super::fence::submit_result(outputs.published(), result); outputs.set_result(result); - let output_fence = if super::fence::untouched_refusal(outputs.published(), &result) { + let output_fence = if super::fence::untouched(outputs.published(), &result) { None } else { outputs.output_fence() diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index 7e8b90239216f..204ca92f5a38a 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -33,6 +33,10 @@ use kernel::{prelude::*, sync::Arc}; const QIDS: usize = 128; const FIRST_COMPUTE_QID: u8 = 4; const WORK_RING_WAIT_NS: u64 = super::job::TIMEOUT_MS as u64 * 1_000_000; +/// Bound for a compute SUBMIT whose backing found the lower range short: idle pools are given +/// back, and the firmware consumes their releases, well within it; then the SUBMIT fails with +/// ENOSPC. +const PROVISION_RECLAIM_NS: u64 = 1_000_000_000; /// Pending admission keeps exactly retired compute backing available for reuse. /// The guard spans retries and disappears on publication, cancellation or error. @@ -255,6 +259,51 @@ 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: Arc, + /// 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, spares: Arc) -> Self { + Self { owner, context, spares, 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`]): they return to its spares when `vacated` is dropped, off the +/// device mutex and after their client views ([`compute::Vacated`]). An owner without commands +/// is idle: its backing is freed, as before it had a reserve. +fn keep_backing(reserves: &KVec>, vacated: &mut compute::Vacated) { + let Some(owner) = vacated.returns_to() else { return }; + let Some(reserve) = reserves.iter().find(|reserve| reserve.owner == owner) else { return }; + if !reserve.context.compute_claimed() { + return; + } + vacated.return_to(reserve.spares.clone()); +} + pub(super) struct Registry { pub(super) qids: kick::QueueIds, pub(super) buffers: BufferIds, @@ -264,10 +313,16 @@ pub(super) struct Registry { render: render::RenderState, identities: queue::Identities, compute: KVec>, + /// 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>, /// Bit `slot` is set while `compute[slot]` is `Some(_)`. compute_occupied_mask: u128, - pub(super) compute_building: bool, - compute_scheduler_building: bool, replay_outer_wait: Option, /// A compute replay waits for its owner's renders to park or idle (compute_replay). replay_consumer_wait: Option, @@ -324,9 +379,10 @@ impl Registry { } compute }, + prepared_shared: None, + prepared_scheduler: None, + reserves: KVec::with_capacity(kick::queue_limit(variant.qid_floor) as usize, GFP_KERNEL)?, compute_occupied_mask: 0, - compute_building: false, - compute_scheduler_building: false, replay_outer_wait: None, replay_consumer_wait: None, observations: compute::retirement::Batch::new()?, @@ -450,7 +506,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; } @@ -579,6 +635,168 @@ 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) + } + + /// `owner`'s spares, under their own lock (inside the device mutex). + fn spares(&self, owner: u64) -> Option> { + self.reserves.iter().find(|reserve| reserve.owner == owner).map(|reserve| reserve.spares.lock()) + } + + /// 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 (spare_pages, spare_ring, spare_kit) = self.spares(owner).map_or((false, false, false), + |spares| (spares.fits(required), spares.has_ring(), spares.has_kit())); + 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 = !spare_pages && !held().any(|queue| queue.backing_fits(required)); + let ring = !spare_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 = !spare_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 mut spares = target.spares.lock(); + let pages = pages.and_then(|pages| spares.put_pages(pages)); + let ring = ring.and_then(|ring| spares.put_ring(ring)); + let kit = kit.and_then(|kit| spares.put_kit(kit)); + drop(spares); + (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 mut spares = self.spares(owner)?; + 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 mut spares = self.spares(owner)?; + Some((spares.take_kit()?, spares.take_pages(required)?, spares.take_ring()?)) + } + + fn take_pages(&mut self, owner: u64, required: super::freelist::ComputeCapacity) + -> Option { + self.spares(owner)?.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.spares(owner) { + Some(mut spares) => compute::Vacated::spares( + pages.and_then(|pages| spares.put_pages(pages)), + ring.and_then(|ring| spares.put_ring(ring)), + kit.and_then(|kit| 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(&self.reserves, vacated); + } + + /// Asks the idle queues holding `owner`'s backing that serves `required` to give it back, + /// and with `ring`, while the owner has no spare ring, any that holds one of its rings, + /// smaller pages too: 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, ring: bool) -> bool { + let ring = ring && !self.spares(owner).is_some_and(|spares| spares.has_ring()); + 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) || (ring && queue.has_ring()))) + { + 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().filter(|reserve| !reserve.context.compute_claimed()) { + let mut spares = reserve.spares.lock(); + while deferred.vacated_room() { + let Some((pages, ring, kit)) = 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 @@ -741,7 +959,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()) @@ -758,7 +977,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) @@ -807,7 +1027,8 @@ impl Registry { queue.owner(), // Prefer a channel serving the requester's VM, then best fit, // then the longest idle. - (!queue.pool_serves(vm), !queue.pool_fits(required), queue.last_published()), + (!queue.pool_serves(vm) || !queue.backing_free_for(owner), !queue.pool_fits(required), + queue.last_published()), queue.qid(), ) }; @@ -834,9 +1055,10 @@ impl Registry { if !queue.share_idle()? { return Err(ENOSPC); } - if !queue.pool_serves(vm) || !queue.pool_fits(required) { - // Its backing holds another VM's scratch or is too small for this - // submission: vacate it, then re-arm fresh. + if !queue.pool_serves(vm) || !queue.backing_free_for(owner) || !queue.pool_fits(required) { + // Its backing holds another VM's scratch or another open owner's backing, which + // goes back to it, or is too small for this submission: vacate it, then re-arm + // fresh. queue.require_fresh_backing(); return Err(ENOSPC); } @@ -936,7 +1158,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)); } @@ -952,12 +1178,14 @@ impl Registry { } /// Installs fresh USC backing into the vacant queue `qid`; the caller writes - /// the returned descriptor row before binding. EAGAIN if the queue was taken. + /// the returned descriptor row before binding. EAGAIN if the queue was taken. Takes `pages` + /// and `ring` only on success. pub(super) fn rearm_compute( &mut self, qid: u8, - pages: crate::g17::freelist::Pages, - ring: compute::DescriptorRing, + owner: u64, + pages: &mut Option, + ring: &mut Option, ) -> Result<(super::freelist::PoolDescriptor, Option)> { let mut queue = self .compute @@ -966,7 +1194,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 @@ -1106,7 +1334,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(&self.reserves, &mut vacated); deferred.defer_vacated(vacated); freed += 1; } @@ -1207,22 +1436,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)?; @@ -1714,146 +1927,48 @@ impl Backend { PublicationBatch::lazy(&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() { - return Ok(()); - } - loop { - admission.check()?; - let lease = self.shared.preparations.enter_until(admission)?; - { - 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; - } - let _ = self.shared.changed.wait_timeout( - &mut state, kernel::time::msecs_to_jiffies(admission.slice_ms()?) - ); - } - } - let mut built = Some(super::initdata::ComputeShared::new()); - 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; + // The shared aperture is G17P compute state. M5 compute queues need only their own + // pools, and M5's InitData has nothing it would install into. + if !firmware.init.hosts_compute_aperture() { + return Ok(()); } - self.shared.note_changed(); - result + // This command's SUBMIT left it prepared; only an install takes it. + firmware.init.install_compute_shared(&mut firmware.queues.prepared_shared)?; + 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(()) @@ -1868,6 +1983,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 firmware.init.hosts_compute_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()?; { @@ -1891,12 +2053,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, client: None }; - 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 @@ -1906,7 +2066,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 = (|| { @@ -1919,11 +2080,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, false); + 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 @@ -1934,7 +2115,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(); @@ -1949,9 +2134,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() { @@ -1966,42 +2151,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)?; @@ -2009,8 +2191,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)) @@ -2018,17 +2198,41 @@ 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) { - Err(error) if error == EAGAIN => return Ok(Some(false)), - result => result?, + let Some((pages, ring)) = firmware.queues.take_set(self.owner, required) else { + if channel_index != 0 { + firmware.queues.want_sibling(self.owner); + } else { + // Its set may sit on an idle queue, its ring on one with smaller pages: there it + // would wait out the admission. + firmware.queues.recall_backing(self.owner, required, true); + } + return Ok(None); }; + let (mut pages, mut ring) = (Some(pages), Some(ring)); + let (descriptor, mut vacated) = match firmware.queues.rearm_compute(qid, self.owner, &mut pages, &mut ring) { + Ok(rearmed) => rearmed, + Err(error) => { + // The set goes back to its owner for the retry; what it does not keep is + // freed after the device guard. + let unused = firmware.queues.put_back(self.owner, pages, ring, None); + drop(state); + drop(unused); + return if error == EAGAIN { Ok(Some(false)) } else { Err(error) }; + } + }; + // 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)?; - firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)?; + // was dropped; the row is rewritten before the queue is kicked. Should either fail, + // the queue keeps the owner's set, tagged for it to recall. + let bound = firmware.init.install_compute_pool(descriptor) + .and_then(|()| firmware.queues.bind_rearmed(qid, self.owner, &self.context, channel_index)); drop(state); drop(vacated); - Ok(Some(true)) + bound.map(|()| Some(true)) } fn build_compute(&self, required: super::freelist::ComputeCapacity, admission: &Admission<'_>) -> Result { @@ -2049,9 +2253,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)?; @@ -2077,8 +2280,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, false, min_span)?; + continue; + } let reservation = match firmware .queues .reserve_compute_reclaiming(self.owner, &mut reclaimed) @@ -2110,23 +2320,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, - client: None, - }; - 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); @@ -2137,80 +2341,20 @@ impl Backend { Some(false) => continue, None => { drop(lease); - self.wait_channels(observed, admission, true, min_span)?; + self.wait_channels(observed, admission, false, min_span)?; continue; } } } }; - 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, min_span)?; + self.wait_channels(observed, admission, false, min_span)?; continue; } if result != Err(EAGAIN) { return result; } @@ -2219,11 +2363,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, @@ -2234,8 +2379,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)?; @@ -2280,36 +2424,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, - ) - }; - let alloc = super::object::Allocator { - dev: &dev, - uat: &uat, - client: None, + (source, channel_index) }; - 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, ); @@ -2325,65 +2465,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()) } @@ -3512,6 +3596,166 @@ 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. Firmware whose + /// InitData has nothing to install them into (M5) needs neither. + fn provision_shared(&self) -> Result { + let needed = |firmware: &super::Firmware| { + let hosts = firmware.init.hosts_compute_aperture(); + (hosts && !firmware.init.has_compute_shared() && firmware.queues.prepared_shared.is_none(), + hosts && !firmware.init.has_compute_scheduler() && firmware.queues.prepared_scheduler.is_none()) + }; + loop { + { + 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).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)?; + // A recovery replaced the firmware meanwhile: prepare for the new one, once the + // gate reopens, instead of failing the SUBMIT. + let current = lease.is_current(); + if current { + 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)); + if current { + return 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. + /// + /// Short of lower range (ENOSPC), it gives idle pools back as a publication's capacity + /// wait does and tries again, for at most [`PROVISION_RECLAIM_NS`]; a recovery that + /// replaced the firmware meanwhile provisions again for the new one. + fn provision_backing(&self, required: super::freelist::ComputeCapacity) -> Result { + let check = || if kernel::current!().signal_pending() { Err(ERESTARTSYS) } else { Ok(()) }; + let admission = Admission::new(now_ns().saturating_add(PROVISION_RECLAIM_NS), &check); + let min_span = self.compute_lower_span(required); + loop { + // Sampled before this attempt's allocation. + let observed = self.shared.channels.observe(); + let error = match self.try_provision_backing(required) { + Err(error) if error == ENOSPC || error == EAGAIN => error, + result => return result, + }; + if error == ENOSPC { + match self.wait_channels(observed, &admission, true, min_span) { + Err(error) if error == EBUSY => return Err(ENOSPC), + Err(error) if error != EAGAIN => return Err(error), + _ => {} + } + } + } + } + + fn try_provision_backing(&self, required: super::freelist::ComputeCapacity) -> Result { + // Recovery joins this lease before replacing the firmware or tearing down its roots. + let lease = self.shared.preparations.enter(true)?; + 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 = if reserved { + None + } else { + let spares = compute::reserve::Reserve::new(self.shared.channels.clone())?; + Some(KBox::new(OwnerReserve::new(self.owner, self.context.clone(), spares), GFP_KERNEL)?) + }; + 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(); + // A queue that closed meanwhile keeps nothing, nor does firmware a recovery replaced. + let closed = self.closed.load(Ordering::Acquire); + let current = lease.is_current(); + let (unused, reserve, stocked) = match state.as_deref_mut() { + Some(firmware) if !closed && current => { + let (unused, reserve) = firmware.queues.stock(self.owner, reserve, pages, ring, kit); + (unused, reserve, firmware.queues.reserves.iter().any(|reserve| reserve.owner == self.owner)) + } + _ => (compute::Vacated::spares(pages, ring, kit), reserve, closed), + }; + let lost = state.is_none(); + drop(state); + drop((unused, reserve)); + if lost { + return Err(ENODEV); + } + if !current && !closed { + return Err(EAGAIN); + } + // 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()?; @@ -4807,7 +5051,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(&self.queues.reserves, &mut vacated); deferred.defer_vacated(vacated); freed = true; } @@ -4820,6 +5065,7 @@ impl super::Firmware { } 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 @@ -5055,8 +5301,9 @@ impl Backend { } Ok(()) })(); + // Backing that goes back to its owner, or client views alone, free no lower range. let freed = !deferred.render.is_empty() - || !deferred.vacated.is_empty() + || deferred.vacated.iter().any(|vacated| vacated.frees_backing()) || !deferred.bindings.is_empty(); deferred.finish(); if freed { diff --git a/drivers/gpu/drm/asahi/g17/runtime/backend.rs b/drivers/gpu/drm/asahi/g17/runtime/backend.rs index fc4e76e71c0e6..c56591a6484c3 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/backend.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/backend.rs @@ -160,7 +160,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); // Both schedulers are gone, so the firmware cannot see a context it has not seen yet. // Its identities return with the queue's admission, not after the jobs that the // closing entities cancelled: those wait for their inputs before they are freed. @@ -342,7 +345,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/submit.rs b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs index 2ef51ab4aa183..832435f0268bd 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/submit.rs @@ -416,11 +416,12 @@ impl Backend { } Ok(published != 0 || !deferred.render.is_empty() - || !deferred.vacated.is_empty() + || deferred.vacated.iter().any(|vacated| vacated.frees_backing()) || !deferred.bindings.is_empty()) })(); + // Backing that goes back to its owner, or client views alone, free nothing for others. let freed = !deferred.render.is_empty() - || !deferred.vacated.is_empty() + || deferred.vacated.iter().any(|vacated| vacated.frees_backing()) || !deferred.bindings.is_empty(); deferred.finish(); if freed { diff --git a/drivers/gpu/drm/asahi/memacct.rs b/drivers/gpu/drm/asahi/memacct.rs index 9a81de6718180..d58ddfdf5613e 100644 --- a/drivers/gpu/drm/asahi/memacct.rs +++ b/drivers/gpu/drm/asahi/memacct.rs @@ -44,12 +44,14 @@ //! memory is pinned without `RLIMIT_MEMLOCK`. //! //! Imported dma-bufs are charged to their exporter and are not counted here. -//! Kernel objects a client's queue creation builds (on G17, its context) 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 global kernel objects (firmware heaps and boot structures) 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. +//! 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, @@ -71,6 +73,7 @@ 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); @@ -565,6 +568,19 @@ impl Drop for Client { } } +/// 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 { pub(crate) fn new() -> Result> { Ok(Arc::new( @@ -1047,12 +1063,20 @@ mod tests { } #[test] - fn charging_restores_the_memory_cgroup() -> Result { + fn device_memory_is_charged_to_the_root_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. + // 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) }; @@ -1199,6 +1223,20 @@ mod tests { 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(()) + } + #[test] fn only_the_unheld_part_of_user_objects_adds_held_memory() -> Result { let a = Client::new()?; diff --git a/drivers/gpu/drm/asahi/memcg_scope.c b/drivers/gpu/drm/asahi/memcg_scope.c index c7af8e96f083e..9e0318506e409 100644 --- a/drivers/gpu/drm/asahi/memcg_scope.c +++ b/drivers/gpu/drm/asahi/memcg_scope.c @@ -18,6 +18,19 @@ 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); diff --git a/drivers/gpu/drm/asahi/memcg_scope.h b/drivers/gpu/drm/asahi/memcg_scope.h index 87434556bfe2e..871624381e7a8 100644 --- a/drivers/gpu/drm/asahi/memcg_scope.h +++ b/drivers/gpu/drm/asahi/memcg_scope.h @@ -6,6 +6,7 @@ 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); diff --git a/tools/asahi/g17-admission-order-tests.py b/tools/asahi/g17-admission-order-tests.py index 7bc14b610a848..c1c8cbc48d2f1 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) @@ -643,6 +650,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-channel-wait-vacate-tests.py b/tools/asahi/g17-channel-wait-vacate-tests.py index e78a0aa6b1e83..e8fe51fc17488 100755 --- a/tools/asahi/g17-channel-wait-vacate-tests.py +++ b/tools/asahi/g17-channel-wait-vacate-tests.py @@ -82,8 +82,8 @@ def item(source, signature): ' let _ = undersized;', ), 'strand-stolen-undersized-same-vm': ( - ' if !queue.pool_serves(vm) || !queue.pool_fits(required) {', - ' if !queue.pool_serves(vm) {', + ' if !queue.pool_serves(vm) || !queue.backing_free_for(owner) || !queue.pool_fits(required) {', + ' if !queue.pool_serves(vm) || !queue.backing_free_for(owner) {', ), 'undersized-before-foreign': ( ' if let Some(qid) = foreign {\n' @@ -156,7 +156,11 @@ def render(mutation): build_fn = item(runtime, ' fn build_compute(') rebind_branch = build_fn[build_fn.index('rebind_compute('):build_fn.index('match rebound')] rebind_passes_false = 'self.wait_channels(observed, admission, false, min_span)?;' in rebind_branch - backing_sites_pass_true = build_fn.count('self.wait_channels(observed, admission, true, min_span)?;') == 2 + # #3704 allocates a queue's backing in SUBMIT: its ENOSPC reclaims there, and a publication + # (build_compute()) waits only for channels and givebacks. + backing_sites_pass_true = ('admission, true, min_span)' not in build_fn + and 'self.wait_channels(observed, &admission, true, min_span)' + in item(runtime, ' fn provision_backing(')) return (TEMPLATE .replace('@@REGISTRY_FNS@@', reg_fns) @@ -260,6 +264,8 @@ def render(mutation): fn pool_fits(&self, req: ComputeCapacity) -> bool { self.capacity >= req.0 } fn pool_vacant(&self) -> bool { self.vacant } fn pool_serves(&self, vm: Vm) -> bool { self.vm == vm } + // Every queue's backing is the requesting owner's (#3704's backing_free_for()). + fn backing_free_for(&self, _owner: u64) -> bool { true } fn needs_fresh_backing(&self) -> bool { self.needs_fresh } fn require_fresh_backing(&mut self) { self.needs_fresh = true; } fn reusable(&self) -> bool { @@ -327,6 +333,9 @@ def render(mutation): fn releasing(&self, _ctx: &Arc) -> bool { false } } +// A vacated pool here frees its backing (#3704's Vacated::frees_backing()). +trait FreesBacking { fn frees_backing(&self) -> bool; } +impl FreesBacking for u32 { fn frees_backing(&self) -> bool { true } } struct DeferredBatch { render: Vec, vacated: Vec, @@ -347,6 +356,8 @@ def render(mutation): impl Registry { const POOL_RETRY_NS: u64 = 100_000_000; fn compute_qid_fits(&self) -> bool { self.fresh_fits } + // Every owner's SUBMIT provisioned a kit (#3704's has_kit()). + fn has_kit(&self, _owner: u64) -> bool { true } fn observe_pool_releases(&mut self, _init: &InitData, _deferred: &mut DeferredBatch) -> Result { Ok(0) } @@ -437,7 +448,7 @@ def render(mutation): assert!(@@REBIND_PASSES_FALSE@@, "build_compute() rebind_compute()==ENOSPC must call wait_channels(..., false, min_span)"); assert!(@@BACKING_SITES_PASS_TRUE@@, - "build_compute() backing-allocation ENOSPC paths must call wait_channels(..., true, min_span)"); + "a backing-allocation ENOSPC (SUBMIT's provision_backing()) must call wait_channels(..., true, min_span), and build_compute() never"); let adm = Admission(&()); diff --git a/tools/asahi/g17-compute-constructor-tests.py b/tools/asahi/g17-compute-constructor-tests.py index e0f1504c7a333..47a23f2851272 100644 --- a/tools/asahi/g17-compute-constructor-tests.py +++ b/tools/asahi/g17-compute-constructor-tests.py @@ -1,9 +1,17 @@ #!/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 where the firmware's + InitData has no aperture objects (M5, whose variants share G17P's compute program); an + allocation failure is the SUBMIT's error and leaves nothing prepared, and a recovery + during the allocation prepares again instead of failing the SUBMIT; +- 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 +33,137 @@ 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);static STALE:AtomicUsize=AtomicUsize::new(0); +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{if STALE.load(Ordering::SeqCst)>0{STALE.fetch_sub(1,Ordering::SeqCst);return false;}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 ComputeCapacity; struct Allocator<'a>{dev:&'a (),uat:&'a (),client:Option<&'a ()>} -struct ComputeShared;struct ComputeScheduler; -fn allocate(){if ALLOCATE.load(Ordering::SeqCst){NOW.fetch_add(25_000_000,Ordering::SeqCst);}} -impl ComputeShared{fn new()->Result{allocate();Ok(Self)}} -impl ComputeScheduler{fn new(_:&Allocator<'_>)->Result{allocate();Ok(Self)}} -struct Init{shared:bool,scheduler:bool} +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()->Result{allocate()?;Ok(Self)}} +impl ComputeScheduler{fn new(a:&Allocator<'_>)->Result{assert!(a.client.is_none());allocate()?;Ok(Self)}} +struct Init{aperture:bool,shared:bool,scheduler:bool,cached:usize} impl Init{ + fn hosts_compute_aperture(&self)->bool{self.aperture} fn has_compute_shared(&self)->bool{self.shared} fn has_compute_scheduler(&self)->bool{self.scheduler} - fn cache_compute_vm(&self,_:&())->Result{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(())} + fn cache_compute_vm(&mut self,_:&())->Result{self.cached+=1;Ok(())} + fn install_compute_shared(&mut self,prepared:&mut Option)->Result{ + if self.shared{return Ok(());}if prepared.is_none(){return Err(EIO);}if !self.aperture{return Err(ENODEV);} + *prepared=None;self.shared=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''' } +// `g17p`: the variant's compute program is G17P's, which M5 variants share; only the InitData +// objects decide. +fn backend(m5:bool,shared:bool,scheduler:bool)->Backend{backend_of(m5,!m5,shared,scheduler)} +fn backend_of(m5:bool,g17p:bool,shared:bool,scheduler:bool)->Backend{ + Backend{context:Context{m5},shared:Shared{variant:Variant{compute:Layout(g17p)},compute_provision:Builder(Mutex::new(())),preparations:Gate,crashed:AtomicBool::new(false),state:State(Mutex::new(Some(Box::new(Firmware{uat:(), + init:Init{aperture:!m5,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:&(),client:None}; - 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, also with G17P's compute program: nothing is allocated or installed. + for g17p in [false,true]{ + let before=ALLOCATED.load(Ordering::SeqCst); + let b=backend_of(true,g17p,false,false); + assert_eq!(b.provision_shared(),Ok(()),"M5 has neither"); + assert_eq!(b.shared_compute(&ADMISSION),Ok(()),"M5 has neither"); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before,"M5 has neither"); + assert!(!fw(&b).as_ref().unwrap().init.shared,"M5 has neither"); + } + // A G17 variant whose compute program is not G17P's (V25F84) still has both. + let before=ALLOCATED.load(Ordering::SeqCst); + let b=backend_of(false,false,false,false); + assert_eq!(b.provision_shared(),Ok(())); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before+2,"V25F84 firmware has the aperture objects"); + assert_eq!(b.shared_compute(&ADMISSION),Ok(())); + assert!(fw(&b).as_ref().unwrap().init.shared,"V25F84 firmware has the aperture objects"); + // A recovery while SUBMIT allocated: it prepares again for the new firmware, not EAGAIN. + let before=ALLOCATED.load(Ordering::SeqCst); + let b=backend(false,false,false); + STALE.store(1,Ordering::SeqCst); + assert_eq!(b.provision_shared(),Ok(()),"a stale lease must prepare again"); + assert_eq!(ALLOCATED.load(Ordering::SeqCst),before+4); + assert!(fw(&b).as_ref().unwrap().queues.prepared_shared.is_some()); + println!("PASS G17P compute aperture and scheduler: SUBMIT prepares them once as device memory, fails on a refusal and prepares again after a recovery; publication installs the prepared aperture, never allocates, and keeps it on cancel, stale lease or crash; M5 has neither, whatever its compute program"); } ''' @@ -106,8 +172,26 @@ 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( + 'firmware.init.install_compute_shared(&mut firmware.queues.prepared_shared)?;', + 'if firmware.queues.prepared_shared.is_none() { firmware.queues.prepared_shared = ' + 'Some(device_memory(ComputeShared::new)?); }\n' + ' firmware.init.install_compute_shared(&mut firmware.queues.prepared_shared)?;'), + 'publication must not allocate'), + ('charged-to-client', source.replace('= device_memory(|| -> Result<_>', '= no_scope(|| -> Result<_>'), + 'must be device memory'), + ('swallow-refusal', source.replace( + 'shared.then(ComputeShared::new).transpose()?', 'shared.then(ComputeShared::new).transpose().unwrap_or(None)').replace( + '(&alloc)).transpose()?', '(&alloc)).transpose().unwrap_or(None)'), + 'must fail the SUBMIT'), + ('program-gate', source.replace( + 'let hosts = firmware.init.hosts_compute_aperture();', + 'let hosts = self.shared.variant.compute.needs_shared_aperture();'), + 'M5 has neither'), + ('stale-lease-fails', source.replace( + ' let current = lease.is_current();\n', + ' let current = lease.is_current();\n if !current { return Err(EAGAIN); }\n'), + 'a stale lease must prepare again'), ] with tempfile.TemporaryDirectory(prefix='g17-compute-constructors-') as tmp: for name, code, expected in mutants: @@ -122,7 +206,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 52d45bed21262..11b239461ccbf 100644 --- a/tools/asahi/g17-compute-growth-deadline-tests.py +++ b/tools/asahi/g17-compute-growth-deadline-tests.py @@ -50,7 +50,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)}} @@ -79,7 +79,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} @@ -88,7 +90,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");}}} @@ -118,6 +121,12 @@ def fixture(): fn compute_primary(&self,owner:u64)->Option>{self.compute(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)->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} @@ -133,7 +142,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:QueueSlot::new(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); @@ -141,8 +150,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"); } ''' @@ -151,7 +161,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..5e4be5450ee1d --- /dev/null +++ b/tools/asahi/g17-compute-reserve-tests.py @@ -0,0 +1,485 @@ +#!/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`, `Reserve::give_back`, `Vacated`'s drop, + `stock` and `trim_reserves` with the production spare bookkeeping keep a claimed + owner's backing, return it only once its client views are gone, free an idle or + unknown owner's and pages whose tables cannot be reset, 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 / return-before-unmap / submit-no-reclaim / reclaim-unbounded 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 let command = entry.command.as_ref().ok_or(EIO)?;\n' + ' self.ensure_compute(command)?;\n }', + ' .then(|| ());\n if engine == Engine::Compute {\n' + ' let command = entry.command.as_ref().ok_or(EIO)?;\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(&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 == 'return-before-unmap': + files['queue/compute.rs'] = files['queue/compute.rs'].replace( + ' self.drop_aliases();\n reserve.give_back(', ' reserve.give_back(', 1) + elif mutation == 'submit-no-reclaim': + files['runtime.rs'] = files['runtime.rs'].replace( + 'self.wait_channels(observed, &admission, true, min_span)', 'Err::<(), _>(EBUSY)', 1) + elif mutation == 'reclaim-unbounded': + files['runtime.rs'] = files['runtime.rs'].replace( + 'Err(error) if error == EBUSY => return Err(ENOSPC),', 'Err(error) if error == EBUSY => {}', 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 try_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(&self.reserves, &mut vacated);' in item(runtime, 'pub(super) fn observe_pool_releases('), + 'recycled rings go to their owner': 'keep_backing(&self.queues.reserves, &mut vacated);' in item(runtime, 'pub(in crate::g17) fn service_compute_pools('), + # Resetting may allocate, and the pages may still be mapped where they map again. + 'returned backing goes back off the device mutex': 'return_to(' in item(runtime, 'fn keep_backing(') + and not re.search(r'reset\(|put_pages\(|put_ring\(', item(runtime, 'fn keep_backing(')), + '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('), + # #4512: idle pools hold the lower range a SUBMIT allocates from. + 'a SUBMIT short of lower range gives idle pools back before refusing': ordered( + item(runtime, ' fn provision_backing('), 'let observed = self.shared.channels.observe();', + 'self.try_provision_backing(required)', 'self.wait_channels(observed, &admission, true, min_span)', + 'return Err(ENOSPC)'), + 'SUBMIT provisions under a preparation lease and stocks only for current firmware': ordered( + provision, 'self.shared.preparations.enter(true)?', 'lease.is_current()', 'firmware.queues.stock('), + 'only backing that is freed counts as reclaim progress': + 'vacated.frees_backing()' in item(runtime, ' fn reclaim_capacity('), + 'a re-arm without its set recalls it, its ring from smaller pages too': + 'recall_backing(self.owner, required, true)' in item(runtime, ' fn rearm_vacant('), + } + 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('/// An owner\'s spares behind their own lock')] + vacated_drop = item(files['queue/compute.rs'], 'impl Drop for Vacated {') + 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('compute::reserve::Reserve', 'Reserve').replace('crate::g17::freelist::Pages', 'Pages') + .replace('super::DescriptorRing', 'Ring').replace('super::Kit', 'Kit') + .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, MutexGuard, atomic::{AtomicBool, 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); +static ALIASES: AtomicUsize = AtomicUsize::new(0); +static RESET_FAILS: AtomicBool = AtomicBool::new(false); +static NOTIFIED: 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 { + assert_eq!(ALIASES.load(Ordering::SeqCst), 0, "returned backing must lose its client views before reuse"); + if RESET_FAILS.load(Ordering::SeqCst) { return Err(-12); } + self.1 = true; Ok(()) + } +} +/// A client view of returned backing. +struct Alias; +impl Alias { fn new() -> Self { ALIASES.fetch_add(1, Ordering::SeqCst); Self } } +impl Drop for Alias { fn drop(&mut self) { ALIASES.fetch_sub(1, Ordering::SeqCst); } } +struct Mutex(std::sync::Mutex); +impl Mutex { fn lock(&self) -> MutexGuard<'_, T> { self.0.lock().unwrap() } } +struct Availability; +impl Availability { fn notify(&self) { NOTIFIED.fetch_add(1, Ordering::SeqCst); } } +struct Reserve { spares: Mutex, returned: Arc } +fn reserve() -> Arc { Arc::new(Reserve { spares: Mutex(std::sync::Mutex::new(Spares::new())), returned: Arc::new(Availability) }) } +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 { _alias: Option, pages: Option, ring: Option, kit: Option, + owner: Option, returns: Option> } +impl Vacated { + fn spares(pages: Option, ring: Option, kit: Option) -> Self { + Self { _alias: None, pages, ring, kit, owner: None, returns: None } + } + fn returns_to(&self) -> Option { self.owner } + fn return_to(&mut self, reserve: Arc) { self.returns = Some(reserve); } + fn drop_aliases(&mut self) { drop(self._alias.take()); } +} +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) + '\n' + vacated_drop + '\nimpl Registry {\n' + replace(methods) + r''' +} +fn back(owner: u64, blocks: usize) -> Vacated { + Vacated { _alias: Some(Alias::new()), pages: Some(Pages::new(blocks)), ring: Some(Ring::new()), kit: None, + owner: Some(owner), returns: None } +} +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(), reserve()))), + 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(), reserve()))), 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, and + // only once it is dropped, off the device mutex, after its client view. + let mut returned = back(1, 30); + keep_backing(®istry.reserves, &mut returned); + assert!(returned.returns.is_some(), "a claimed owner's backing must be kept"); + assert!(!registry.owner_reserve(1).unwrap().spares.lock().fits(ComputeCapacity::Blocks(30)), + "backing must not return while its client view is mapped"); + let notified = NOTIFIED.load(Ordering::SeqCst); + drop(returned); + assert_eq!(FREED.load(Ordering::SeqCst), 0); + assert_eq!(NOTIFIED.load(Ordering::SeqCst), notified + 1, "a returned set wakes its waiters"); + { + let mut spares = registry.owner_reserve(1).unwrap().spares.lock(); + 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(®istry.reserves, &mut idle); + assert!(idle.returns.is_none(), "an idle owner's backing must be freed"); + drop(idle); + let mut unknown = back(9, 21); + keep_backing(®istry.reserves, &mut unknown); + assert!(unknown.returns.is_none()); + drop(unknown); + // Pages whose tables cannot be written again are freed, never kept stale. + let before = FREED.load(Ordering::SeqCst); + RESET_FAILS.store(true, Ordering::SeqCst); + let mut stale = back(1, 40); + keep_backing(®istry.reserves, &mut stale); + drop(stale); + RESET_FAILS.store(false, Ordering::SeqCst); + assert_eq!(FREED.load(Ordering::SeqCst), before + 1, "unreset pages must be freed"); + assert!(!registry.owner_reserve(1).unwrap().spares.lock().fits(ComputeCapacity::Blocks(40))); + // 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.lock().is_empty(), "the pool pass must free idle spares"); + assert!(!registry.owner_reserve(1).unwrap().spares.lock().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, after its client views, with a wake), an idle or unknown owner's backing, unresettable pages 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 provision_loop(files): + """Runs the production SUBMIT provisioning loop against scripted allocation results.""" + loop = item(files['runtime.rs'], ' fn provision_backing(') + loop = loop.replace('kernel::current!().signal_pending()', 'SIGNAL.load(Ordering::SeqCst)') + source = r''' +#![allow(dead_code)] +use std::{cell::{Cell, RefCell}, collections::VecDeque, sync::atomic::{AtomicBool, AtomicU64, Ordering}}; +type Result = std::result::Result; +const ENOMEM: i32 = -12; const EAGAIN: i32 = -11; const EBUSY: i32 = -16; const ENOSPC: i32 = -28; +const ERESTARTSYS: i32 = -512; +const PROVISION_RECLAIM_NS: u64 = 1_000_000_000; +static NOW: AtomicU64 = AtomicU64::new(0); +static SIGNAL: AtomicBool = AtomicBool::new(false); +fn now_ns() -> u64 { NOW.load(Ordering::SeqCst) } +mod super_ { pub mod freelist { #[derive(Clone, Copy)] pub enum ComputeCapacity { Blocks(usize) } } } +use super_ as sup; +struct Admission<'a> { deadline: u64, check: &'a dyn Fn() -> Result } +impl<'a> Admission<'a> { + fn new(deadline: u64, check: &'a dyn Fn() -> Result) -> Self { Self { deadline, check } } + fn check(&self) -> Result { (self.check)()?; if now_ns() >= self.deadline { Err(EBUSY) } else { Ok(()) } } +} +struct Channels; +impl Channels { fn observe(&self) -> u64 { 0 } } +struct Shared { channels: Channels } +struct Backend { shared: Shared, tries: RefCell>, waits: Cell } +impl Backend { + fn compute_lower_span(&self, _: sup::freelist::ComputeCapacity) -> u64 { 0 } + fn try_provision_backing(&self, _: sup::freelist::ComputeCapacity) -> Result { + self.tries.borrow_mut().pop_front().unwrap_or(Err(ENOSPC)) + } + /// The production wait checks its admission (deadline, signal) before reclaiming. + fn wait_channels(&self, _: u64, admission: &Admission<'_>, reclaim_backing: bool, _: u64) -> Result { + assert!(reclaim_backing, "a SUBMIT short of lower range must reclaim idle pools"); + self.waits.set(self.waits.get() + 1); + assert!(self.waits.get() < 100, "the reclaim must end at its deadline"); + NOW.fetch_add(300_000_000, Ordering::SeqCst); + admission.check() + } +''' + loop.replace('super::freelist::', 'sup::freelist::') + r''' +} +fn run(tries: &[Result]) -> (Result, usize) { + let backend = Backend { shared: Shared { channels: Channels }, tries: RefCell::new(tries.iter().copied().collect()), + waits: Cell::new(0) }; + let result = backend.provision_backing(sup::freelist::ComputeCapacity::Blocks(21)); + (result, backend.waits.get()) +} +fn main() { + assert_eq!(run(&[Err(ENOSPC), Ok(())]), (Ok(()), 1), "a SUBMIT short of lower range must retry after reclaim"); + let (result, waits) = run(&[]); + assert_eq!(result, Err(ENOSPC), "a range that stays short must refuse with ENOSPC"); + assert!(waits <= 4, "the reclaim must end at its deadline"); + assert_eq!(run(&[Err(EAGAIN), Ok(())]), (Ok(()), 0), "a stale lease must provision again at once"); + assert_eq!(run(&[Err(ENOMEM)]), (Err(ENOMEM), 0), "other failures are the SUBMIT's own"); + SIGNAL.store(true, Ordering::SeqCst); + assert_eq!(run(&[]).0, Err(ERESTARTSYS), "a signal ends the reclaim wait"); + println!("PASS SUBMIT provisioning: reclaims and retries when short of lower range, refuses with ENOSPC at its deadline, provisions again after a recovery, and stops on a signal"); +} +''' + with tempfile.TemporaryDirectory(prefix='g17-provision-loop-') as tmp: + path = Path(tmp) / 'loop.rs' + path.write_text(source) + build = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-Awarnings', str(path), + '-o', str(path.with_suffix(''))], capture_output=True, text=True) + if build.returncode != 0: + return [f'FAIL line 0: compiled provisioning loop 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 provisioning loop: {run.stderr.strip()}'] + print(run.stdout.strip()) + return [] + + +def check(files): + failures = structure(files) + compiled(files) + provision_loop(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', 'return-before-unmap', + 'submit-no-reclaim', 'reclaim-unbounded']) + 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 a94abd1c851db..fc454c99c385a 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 } @@ -271,6 +284,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 f37dc6added6c..79089400967f9 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 kill_unfinished(&self)->bool{false} 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;}} @@ -93,7 +93,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,returns:Option<()>} +// The owners' spare backing: what a queue gives back stays its owner's while it has commands. +fn keep_backing(_:&(),_:&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 { @@ -101,7 +103,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 ecc40cca1f85b..d828144fbbd01 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,20 @@ 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.bind_rearmed(qid, self.owner, &self.context, channel_index)?;'), + 'firmware.queues.take_set(self.owner, required)', + 'firmware.queues.rearm_compute(qid, self.owner, &mut pages, &mut ring)', + 'firmware.queues.put_back(self.owner, pages, ring, None)', '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()) @@ -246,6 +248,7 @@ def build(mutation=None): const EIO: i32 = -5; const EAGAIN: i32 = -11; const EBUSY: i32 = -16; +const EINVAL: i32 = -22; const EPERM: i32 = -1; const ENOSPC: i32 = -28; type Result = std::result::Result; @@ -288,7 +291,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, returns: Option<()> } pub struct FreeListRelease; enum ControlRecord { FreeListRelease(FreeListRelease) } struct Rings; @@ -317,7 +320,7 @@ def build(mutation=None): impl Pool { @@POOL@@ fn fits_capacity(&self, required: ComputeCapacity) -> bool { self.pages.is_some() && self.cap >= required.0 } - fn rearm(&mut self, pages: Pages) -> Result { if self.pages.is_some() { return Err(EBUSY); } self.pages = Some(pages); Ok(()) } + fn rearm(&mut self, pages: &mut Option) -> Result { if self.pages.is_some() { return Err(EBUSY); } self.pages = Some(pages.take().ok_or(EINVAL)?); Ok(()) } fn descriptor(&self) -> Result { Ok(PoolDescriptor(u32::from(self.id))) } fn release_record(&self, _generation: u64) -> FreeListRelease { FreeListRelease } } @@ -330,7 +333,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, retained_owner: Option, + channel_index: u8, sustained: bool, retained_owner: Option, backing_owner: Option, } impl Queue { @@QUEUE@@ @@ -411,13 +414,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, retained_owner: None, + channel_index: 0, sustained: true, retained_owner: None, 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; @@ -448,8 +453,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) @@ -458,7 +462,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, &mut Some(Pages(2)), &mut Some(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) @@ -616,9 +620,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 b7fd10bb96268..e765672a733e7 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -1096,7 +1096,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-primary-sibling-livelock-tests.py b/tools/asahi/g17-primary-sibling-livelock-tests.py index 04932b285231a..f8346d83f233e 100755 --- a/tools/asahi/g17-primary-sibling-livelock-tests.py +++ b/tools/asahi/g17-primary-sibling-livelock-tests.py @@ -226,6 +226,8 @@ def render(mutation): } fn pool_fits(&self, req: ComputeCapacity) -> bool { self.pool_cap >= req.0 } fn pool_serves(&self, vm: Vm) -> bool { self.pool_vm == vm } + // Every queue's backing is the requesting owner's (#3704's backing_free_for()). + fn backing_free_for(&self, _owner: u64) -> bool { true } fn pool_vacant(&self) -> bool { self.pool_vacant } fn vacancy_pending(&self) -> bool { self.vacancy_pending } fn reusable(&self) -> bool { self.reusable } @@ -304,6 +306,8 @@ def render(mutation): } } fn compute_qid_fits(&self) -> bool { self.qid_fits } + // Every owner's SUBMIT provisioned a kit (#3704's has_kit()). + fn has_kit(&self, _owner: u64) -> bool { true } fn give_back_foreign(&mut self, qid: u8) -> Result { self.compute.iter_mut().flatten().filter_map(|e| e.queue.as_deref_mut()) .find(|q| q.qid() == qid).ok_or(EIO)?.require_fresh_backing(); diff --git a/tools/asahi/g17-queue-object-charge-tests.py b/tools/asahi/g17-queue-object-charge-tests.py index e9f6b053787a1..f919088ce9eb5 100644 --- a/tools/asahi/g17-queue-object-charge-tests.py +++ b/tools/asahi/g17-queue-object-charge-tests.py @@ -1,22 +1,26 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: GPL-2.0-only OR MIT -"""Kernel objects a client's QUEUE_CREATE builds are charged to that client. +"""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. QUEUE_CREATE builds the context -(scheduler storage, work state) in the client's ioctl, where a failure comes -back from the ioctl, so that Allocator names the client and its objects are -charged to it. - -Everything else is built at publication, after SUBMIT accepted the job: render -pairs, rings, generations, tiler heaps, compute state, timestamps. A failure -there 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 one (QUEUE_CREATE's, - in `Backend::new`) names the client, and all others say None; +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::try_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; - an object charged to a client has its pages charged to that client's memory @@ -25,8 +29,8 @@ inside `client.charging(..)`. A worker has no memory cgroup of its own, so pages populated there otherwise land in the root cgroup. ---mutation drop-client / uncharged-backing / none-client / uncharged-pages / -root-populate inject each fault and must be caught. +--mutation drop-client / uncharged-backing / none-client / uncharged-compute / +charged-kit / uncharged-pages / root-populate inject each fault and must be caught. """ import argparse import re @@ -53,6 +57,14 @@ def sources(mutation): 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) elif mutation == 'uncharged-pages': # client_backing populates in the calling task again, as before the fix. k = 'object.rs' @@ -94,7 +106,8 @@ def check(files): 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): - named.append((name, code[m.end():m.end() + 200])) + 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 ' @@ -111,10 +124,11 @@ def check(files): if not re.search(r'client\.charging\(\s*\|\|\s*Self::with_object\(', charged) \ or charged.count('with_object(') != 1: failures.append('FAIL line 0: object.rs: charged() populates outside client.charging()') - # QUEUE_CREATE's context is the only allocator that names a client. - if len(named) != 1 or named[0][0] != 'runtime.rs' or 'owner_pid' not in named[0][1]: - failures.append(f'FAIL line 0: allocators naming a client {[n for n, _ in named]}, ' - "expected only QUEUE_CREATE's context (Backend::new)") + # 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', 'try_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::try_provision_backing)') if literals < 10: failures.append(f'FAIL line 0: only {literals} Allocator literals found; the scan is broken') return failures @@ -123,14 +137,16 @@ def check(files): def main(): parser = argparse.ArgumentParser() parser.add_argument('--mutation', choices=['drop-client', 'uncharged-backing', 'none-client', - 'uncharged-pages', 'root-populate']) + 'uncharged-compute', 'charged-kit', + 'uncharged-pages', 'root-populate']) 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 objects are charged to the client, publication's are not yet; " + print("ok: QUEUE_CREATE's context and SUBMIT's compute backing are charged to the client, " + "publication's objects and device memory are not; " "client-charged pages go to the client's memory cgroup") diff --git a/tools/asahi/g17-shared-pool-tests.py b/tools/asahi/g17-shared-pool-tests.py index c6158c5a3f6a9..f622fe797b443 100644 --- a/tools/asahi/g17-shared-pool-tests.py +++ b/tools/asahi/g17-shared-pool-tests.py @@ -209,7 +209,9 @@ def reclaim_flow_fixture(): } } struct ComputeEntry { queue: Option> } -struct Registry { compute: Vec> } +struct Registry { compute: Vec>, reserves: () } +// What a vacated pool gives back goes to its owner's reserve; nothing is kept here. +fn keep_backing(_: R, _: V) {} struct DeferredBatch { vacated: Vec, vacated_cap: usize } impl DeferredBatch { fn new(vacated_cap: usize) -> Self { Self { vacated: Vec::with_capacity(vacated_cap), vacated_cap } } @@ -299,7 +301,7 @@ def reclaim_flow_fixture(): // 3. DeferredBatch::reclaim() must provide vacated room for observe_pool_releases(). let init = super_mod::initdata::InitData { consumer: 1.into(), producer: 1.into() }; - let mut reg = Registry { compute: vec![Some(ComputeEntry { queue: Some(Box::new(ComputeQueue { vacated: true })) })] }; + let mut reg = Registry { compute: vec![Some(ComputeEntry { queue: Some(Box::new(ComputeQueue { vacated: true })) })], reserves: () }; let mut batch = DeferredBatch::new(QIDS); let freed = reg.observe_pool_releases(&init, &mut batch).unwrap(); assert_eq!(freed, 1, "reclaim batch must observe and collect vacated compute pools"); diff --git a/tools/asahi/g17-submit-refusal-untouched-tests.py b/tools/asahi/g17-submit-refusal-untouched-tests.py index d6b8f8deca47c..d74381302e069 100644 --- a/tools/asahi/g17-submit-refusal-untouched-tests.py +++ b/tools/asahi/g17-submit-refusal-untouched-tests.py @@ -60,7 +60,7 @@ def sources(mutation): 'bundle.prepare(&submission.fence(), compute_only)?;\n }\n self.install();\n Ok(submission)', 1) elif mutation == 'ignore-queued': files['g17/queue/mod.rs'] = files['g17/queue/mod.rs'].replace( - 'untouched_refusal(enqueued != 0, &result)', 'untouched_refusal(false, &result)', 1) + 'untouched(enqueued != 0, &result)', 'untouched(false, &result)', 1) elif mutation == 'queued-enomem': files['g17/queue/mod.rs'] = files['g17/queue/mod.rs'].replace( '.push_within_capacity(order.sequence, fences).map_err(|_| EIO)?;', @@ -91,9 +91,9 @@ def check(files): state = item(fence, 'pub(crate) fn published(') if ('self.installed' not in state or 'bundle.prepare(' not in publish or 'self.installed = true;' in publish - or 'if !self.installed && !untouched_refusal(false, &self.result)' not in drop): + or 'if !self.installed && !untouched(false, &self.result)' not in drop): failures.append('FAIL: cumulative allocation failure publishes the private aggregate') - if 'if super::fence::untouched_refusal(outputs.published(), &result)' not in submit: + if 'if super::fence::untouched(outputs.published(), &result)' not in submit: failures.append('FAIL: refusal trace exposes a private fence') scope = files['g17/sync_scope.c'] create = item(scope, 'struct dma_fence *asahi_g17_scope_create(') @@ -113,7 +113,7 @@ def check(files): if 'install(' in publish or 'commit(' in publish: failures.append('FAIL line 7: creating the submission stores it in the outputs') loop_end = submit.find('enqueued += 1;') - gate = submit.find('if !super::fence::untouched_refusal(enqueued != 0, &result) {\n outputs.install();') + gate = submit.find('if !super::fence::untouched(enqueued != 0, &result) {\n outputs.install();') if loop_end < 0 or gate < loop_end: failures.append('FAIL line 8: the outputs are not installed after the loop, gated on queued commands') install_trace = re.compile(r'super::trace::submit\(\s*1,') 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 1a4e29266d35d..08d32ddce1943 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -504,6 +504,11 @@ 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', 'return-before-unmap', 'submit-no-reclaim', + 'reclaim-unbounded'], []), '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', @@ -573,7 +578,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-host-only-render-kick-tests.py': [([], PASS)] + mutations('--mutation', ('skip-pre-stamp-check', @@ -740,7 +744,7 @@ def mutations(flag, names, base, expect=KILL): 'g17-shared-pool-tests.py': [([], PASS)], 'g17-queue-object-charge-tests.py': [([], PASS)] + mutations( '--mutation', ['drop-client', 'uncharged-backing', 'none-client', 'uncharged-pages', - 'root-populate'], []), + 'root-populate', 'uncharged-compute', 'charged-kit'], []), 'asahi-idle-vm-reclaim-feature-tests.py': [([], PASS)] + mutations( '--mutation', ['drop-g17', 'drop-m5', 'report-g16'], []), 'asahi-held-ceiling-tests.py': [([], PASS)] + mutations(