diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index a5033558636ee..cac7f0bb76d3f 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -9,10 +9,14 @@ use super::Output; use crate::g17::{dependency::PRODUCER_FAILED, status::VmStatus}; -use core::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use core::{ + cell::UnsafeCell, + ptr::NonNull, + sync::atomic::{AtomicU8, AtomicU64, Ordering}, +}; use kernel::{new_mutex, prelude::*, sync::{Arc, Mutex}}; -type Links = Option>; +type Links = Option>; /// Lockless publication phase stored in a single `AtomicU8` so lockless readers /// (`is_pending()`, `link_deferred()`, `failed_after_release()`) never observe @@ -36,10 +40,10 @@ const PHASE_FAILED_AFTER_SETTLE: u8 = 5; /// One step of `Publication::pending_within()`, taken under the state lock and finished off it. enum Probe { - /// A failed predecessor's link, consumed. - Consumed((Arc, KBox)), + /// A failed predecessor's link, consumed: the predecessor it held. + Consumed(Option>), /// Settled clean: the dropped predecessor links and the successors to release. - Settled(KVec<(Arc, KBox)>, Links), + Settled(Links, Links), /// Ask this unsettled timestamp-free predecessor. Next(Arc), } @@ -49,22 +53,125 @@ enum Probe { /// stops early only leaves settlement to the deferred links. const PENDING_PROBE_DEPTH: usize = 4; +/// One wait of a successor on a predecessor. All of a successor's links live in one +/// [`LinkBlock`] that its publication owns; a predecessor's list only points into it. struct Link { // Populated only when attached to a predecessor's successor list so // `deferred_links` held on the target itself never forms a self-Arc cycle. + // Held from then until the link has been consumed, so that the block the + // link lives in stays allocated while a list or a traversal can reach it. target: Option>, + /// The predecessor, held while the link is deferred on its successor. + predecessor: Option>, result: Result, + /// The next link of the predecessor's list, or of the successor's deferred links. next: Links, // Reuse an already-consumed link as a traversal frame instead of recursing // or allocating when publication unlocks a long chain of ready successors. resume: Links, } +/// Releases a consumed link's hold on its successor. +/// +/// # Safety +/// +/// `link` must be reachable from no list and no traversal any more. It may be freed on return. +unsafe fn release(link: NonNull) { + // SAFETY: Per the contract the caller is its only user, and the held successor keeps its + // block allocated until this drop. + drop(unsafe { (*link.as_ptr()).target.take() }); +} + +/// How many links a list holds. +/// +/// # Safety +/// +/// The caller must own the list: no other thread may reach its links. +unsafe fn list_len(mut links: Links) -> usize { + let mut len = 0; + while let Some(link) = links { + len += 1; + // SAFETY: Per the contract. + links = unsafe { (*link.as_ptr()).next }; + } + len +} + +/// Drops the predecessors that a list of deferred links holds. +/// +/// # Safety +/// +/// The caller must own the list, taken out of `deferred_links`, and keep its block allocated. +unsafe fn drop_predecessors(mut links: Links) { + while let Some(link) = links { + // SAFETY: Per the contract. + unsafe { + links = (*link.as_ptr()).next.take(); + drop((*link.as_ptr()).predecessor.take()); + } + } +} + +/// The flags of a successor's link block: per-job state sized by the commands it covers, so +/// charged to the client like the job's fence vectors. +const LINK_FLAGS: kernel::alloc::Flags = GFP_KERNEL_ACCOUNT; + +#[cfg(CONFIG_KUNIT = "y")] +static BLOCKS: [core::sync::atomic::AtomicUsize; 2] = + [core::sync::atomic::AtomicUsize::new(0), core::sync::atomic::AtomicUsize::new(0)]; + +/// Counts link blocks allocated (`false`) and freed (`true`) for KUnit. +#[cfg(CONFIG_KUNIT = "y")] +fn note_block(freed: bool) { + BLOCKS[usize::from(freed)].fetch_add(1, Ordering::Relaxed); +} +#[cfg(not(CONFIG_KUNIT = "y"))] +fn note_block(_freed: bool) {} + +/// One successor's links, in a single allocation. +struct LinkBlock(KVVec>); + +// SAFETY: A link is reached through exactly one list, under the lock of the publication that +// holds that list, or through the one traversal that detached it, so no two threads use it at +// once. +unsafe impl Send for LinkBlock {} + +impl LinkBlock { + /// Threads every link onto one list through `next`, in order, and returns its head. + fn list_links(&mut self) -> Links { + let links = self.0.as_mut_ptr(); + let mut head = None; + for index in (0..self.0.len()).rev() { + // SAFETY: `index` is within the block, and nothing reaches its links yet. The + // block never grows after setup, so the links stay in place. + let link = unsafe { NonNull::new_unchecked(UnsafeCell::raw_get(links.add(index))) }; + // SAFETY: As above. + unsafe { (*link.as_ptr()).next = head }; + head = Some(link); + } + head + } +} + +impl Drop for LinkBlock { + fn drop(&mut self) { + if self.0.capacity() != 0 { + // A large block may come from vmalloc, and vfree() may sleep: every place that can + // drop the last reference to a publication must be able to. + kernel::task::might_sleep(); + note_block(true); + } + } +} + struct State { // Pre-allocated predecessor links kept on the successor until `finish()` // runs, a waiter subscribes it, or `is_pending()` observes all predecessors // settled cleanly. Always drained before attaching so no Arc cycle forms. - deferred_links: KVec<(Arc, KBox)>, + // They live in `block`, listed through `Link::next`. + deferred_links: Links, + /// This publication's own links, owned from activation on. + block: Option, remaining: usize, result: Option>, predecessor_error: Option, @@ -79,6 +186,24 @@ struct State { subscribe_next: Option>, } +// SAFETY: See `LinkBlock`: the links in `successors` and `deferred_links` are used only under +// this lock or by the one caller that took them out of it. +unsafe impl Send for State {} + +impl Drop for State { + /// A publication dropped before it published releases the links still waiting on it. + fn drop(&mut self) { + let mut next = self.successors.take(); + while let Some(link) = next { + // SAFETY: The list owned these links; each is released after its successor is read. + unsafe { + next = (*link.as_ptr()).next.take(); + release(link); + } + } + } +} + impl State { fn claim(&mut self) -> Option> { if self.remaining != 0 || self.claimed { @@ -91,6 +216,43 @@ impl State { (result, _) => result, }) } + + /// The first deferred link whose predecessor has not settled clean, after which link it + /// sits, and that predecessor's phase. + fn first_unclean(&self) -> Option<((Links, NonNull), u8)> { + let mut prev = None; + let mut next = self.deferred_links; + while let Some(link) = next { + // SAFETY: Deferred links are reached only through this list, under this lock. + let deferred = unsafe { link.as_ref() }; + let phase = deferred + .predecessor + .as_ref() + .map_or(PHASE_SETTLED_CLEAN, |pred| pred.phase.load(Ordering::Acquire)); + if phase != PHASE_SETTLED_CLEAN { + return Some(((prev, link), phase)); + } + prev = next; + next = deferred.next; + } + None + } + + /// Takes a deferred link, sitting after `prev`, out of the list, and returns its predecessor. + fn unlink_deferred( + &mut self, + (prev, link): (Links, NonNull), + ) -> Option> { + // SAFETY: Deferred links are reached only through this list, under this lock. + unsafe { + let after = (*link.as_ptr()).next.take(); + match prev { + Some(prev) => (*prev.as_ptr()).next = after, + None => self.deferred_links = after, + } + (*link.as_ptr()).predecessor.take() + } + } } #[pin_data] @@ -125,7 +287,8 @@ impl Publication { phase: AtomicU8::new(PHASE_PENDING), reach: [AtomicU64::new(0), AtomicU64::new(0)], state <- new_mutex!(State { - deferred_links: KVec::new(), + deferred_links: None, + block: None, // Acceptance installs deferred links before releasing this sentinel. remaining: 1, result: None, @@ -205,18 +368,11 @@ impl Publication { } if state.published.is_some() || state.claimed - || state.deferred_links.is_empty() + || state.deferred_links.is_none() { return true; } - let first_unclean = state - .deferred_links - .iter() - .enumerate() - .find_map(|(index, (pred, _))| { - let phase = pred.phase.load(Ordering::Acquire); - (phase != PHASE_SETTLED_CLEAN).then_some((index, phase)) - }); + let first_unclean = state.first_unclean(); match first_unclean { Some((index, PHASE_FAILED_PENDING | PHASE_FAILED_AFTER_SETTLE)) => { // Terminal and settles nothing: consume the link and keep the failure for @@ -224,14 +380,14 @@ impl Publication { if state.predecessor_error.is_none() { state.predecessor_error = Some(PRODUCER_FAILED); } - Probe::Consumed(state.deferred_links.swap_remove(index)) + Probe::Consumed(state.unlink_deferred(index)) } - Some((index, _)) => { - let pred = &state.deferred_links[index].0; - if !pred.has_outputs { - Probe::Next(pred.clone()) - } else { - return true; + Some(((_, link), _)) => { + // SAFETY: Deferred links are reached only through this list, under this + // lock. + match unsafe { link.as_ref() }.predecessor.as_ref() { + Some(pred) if !pred.has_outputs => Probe::Next(pred.clone()), + _ => return true, } } None if state.predecessor_error.is_none() => { @@ -245,9 +401,10 @@ impl Publication { } }; match step { - Probe::Consumed(link) => drop(link), + Probe::Consumed(pred) => drop(pred), Probe::Settled(old, successors) => { - drop(old); + // SAFETY: `old` was taken out of `deferred_links`, and `self` keeps its block. + unsafe { drop_predecessors(old) }; // Successors that attached before this settlement are released here, as // `predecessors_done_ok()` releases them. Self::drain(Self::released_ok(successors)); @@ -263,11 +420,14 @@ impl Publication { } /// Mark successor links released by a clean upstream settlement. - fn released_ok(mut links: Links) -> Links { - let mut next = links.as_mut(); + fn released_ok(links: Links) -> Links { + let mut next = links; while let Some(link) = next { - link.result = Ok(()); - next = link.next.as_mut(); + // SAFETY: These links were taken out of the list and belong to this caller. + unsafe { + (*link.as_ptr()).result = Ok(()); + next = (*link.as_ptr()).next; + } } links } @@ -309,12 +469,13 @@ impl Publication { } state.result = Some(result); let deferred = core::mem::take(&mut state.deferred_links); - if deferred.is_empty() { + if deferred.is_none() { (self.claim_locked(&mut state), deferred) } else { // Hold a sentinel (+1) while checking/attaching predecessors // off-lock so `remaining` cannot reach 0 prematurely. - state.remaining += 1 + deferred.len(); + // SAFETY: Deferred links are reached only through this list, under this lock. + state.remaining += 1 + unsafe { list_len(deferred) }; (None, deferred) } }; @@ -322,14 +483,14 @@ impl Publication { Self::drain(self.publish(result)); return; } - if !to_attach.is_empty() { + if to_attach.is_some() { self.attach_deferred(to_attach); } } /// Link this publication to its deferred predecessors; the caller holds one sentinel in /// `remaining` for this. - fn attach_deferred(self: &Arc, deferred: KVec<(Arc, KBox)>) { + fn attach_deferred(self: &Arc, deferred: Links) { let mut stack = None; self.link_deferred(deferred, &mut stack); Self::subscribe(stack); @@ -339,20 +500,30 @@ impl Publication { /// onto `stack` for [`Self::subscribe`]. fn link_deferred( self: &Arc, - deferred: KVec<(Arc, KBox)>, + deferred: Links, stack: &mut Option>, ) { let mut fast_ok = 0usize; - for (predecessor, mut link) in deferred { - if predecessor.is_settled_clean() { - fast_ok += 1; - drop(link); - } else { - link.target = Some(self.clone()); - if predecessor.add_successor(link) { - predecessor.state.lock().subscribe_next = stack.take(); - *stack = Some(predecessor); + let mut next = deferred; + while let Some(link) = next { + // SAFETY: The caller took these links out of `deferred_links`, so each is this + // caller's until it is handed to its predecessor, and `self`, held, keeps their + // block allocated. + let predecessor = unsafe { + next = (*link.as_ptr()).next.take(); + (*link.as_ptr()).predecessor.take() + }; + match predecessor { + Some(predecessor) if !predecessor.is_settled_clean() => { + // SAFETY: As above. + unsafe { (*link.as_ptr()).target = Some(self.clone()) }; + // SAFETY: As above; the link now holds its successor. + if unsafe { predecessor.add_successor(link) } { + predecessor.state.lock().subscribe_next = stack.take(); + *stack = Some(predecessor); + } } + _ => fast_ok += 1, } } Self::drain(self.predecessors_done_ok(1 + fast_ok)); @@ -371,14 +542,15 @@ impl Publication { || state.claimed || state.published.is_some() || state.upstream_released - || state.deferred_links.is_empty() + || state.deferred_links.is_none() { // `finish()` or a probe linked or settled it meanwhile. continue; } let deferred = core::mem::take(&mut state.deferred_links); // Hold a sentinel (+1) while linking off-lock, as `finish()` does. - state.remaining += 1 + deferred.len(); + // SAFETY: Deferred links are reached only through this list, under this lock. + state.remaining += 1 + unsafe { list_len(deferred) }; deferred }; node.link_deferred(deferred, &mut stack); @@ -395,7 +567,7 @@ impl Publication { } self.output.publish(result, &self.status); let result = result.map(|_| ()); - let mut links = { + let links = { let mut state = self.state.lock(); // A late link is acknowledged only after timestamp writes, the public // fence and aggregate membership have all been published off this lock. @@ -410,10 +582,13 @@ impl Publication { self.phase.store(next_phase, Ordering::Release); state.successors.take() }; - let mut next = links.as_mut(); + let mut next = links; while let Some(link) = next { - link.result = result; - next = link.next.as_mut(); + // SAFETY: These links were taken out of the list and belong to this caller. + unsafe { + (*link.as_ptr()).result = result; + next = (*link.as_ptr()).next; + } } links } @@ -471,7 +646,11 @@ impl Publication { /// Returns whether this publication must now be subscribed to its predecessors /// ([`Self::subscribe`]): an unfinished timestamp-free publication keeps them deferred /// until its own `finish()`, and the queued waiter must not wait for that. - fn add_successor(&self, mut link: KBox) -> bool { + /// + /// # Safety + /// + /// `link` must hold its successor, and no list or traversal may reach it yet. + unsafe fn add_successor(&self, link: NonNull) -> bool { let mut state = self.state.lock(); let immediate = if let Some(result) = state.published { Some(result) @@ -482,18 +661,24 @@ impl Publication { }; if let Some(result) = immediate { drop(state); - if let Some(target) = link.target.take() { - Self::drain(target.predecessor_done(result)); - } + // SAFETY: The caller still owns the link, whose successor is held. + let children = unsafe { link.as_ref() } + .target + .as_ref() + .and_then(|target| target.predecessor_done(result)); + // SAFETY: Nothing else reaches the link. + unsafe { release(link) }; + Self::drain(children); return false; } - link.next = state.successors.take(); + // SAFETY: The caller still owns the link; the list owns it from here. + unsafe { (*link.as_ptr()).next = state.successors.take() }; state.successors = Some(link); let subscribe = !self.has_outputs && !state.subscribe_queued && !state.claimed && state.result.is_none() - && !state.deferred_links.is_empty(); + && state.deferred_links.is_some(); state.subscribe_queued |= subscribe; subscribe } @@ -502,21 +687,28 @@ impl Publication { fn drain(mut pending: Links) { let mut frames: Links = None; loop { - if let Some(mut link) = pending.take() { - pending = link.next.take(); - let children = link - .target - .take() - .map_or(None, |target| target.predecessor_done(link.result)); + if let Some(link) = pending.take() { + // SAFETY: This traversal owns every link in `pending` and `frames`; a link's + // held successor keeps its block allocated until `release()`. + let node = unsafe { &mut *link.as_ptr() }; + pending = node.next.take(); + let children = node.target.as_ref().and_then(|t| t.predecessor_done(node.result)); if children.is_some() { - link.resume = pending.take(); - link.next = frames.take(); + node.resume = pending.take(); + node.next = frames.take(); frames = Some(link); pending = children; + } else { + // SAFETY: Done with: no list or frame holds it. + unsafe { release(link) }; } - } else if let Some(mut frame) = frames.take() { - frames = frame.next.take(); - pending = frame.resume.take(); + } else if let Some(frame) = frames.take() { + // SAFETY: As above. + let node = unsafe { &mut *frame.as_ptr() }; + frames = node.next.take(); + pending = node.resume.take(); + // SAFETY: Popped: no list or frame holds it. + unsafe { release(frame) }; } else { break; } @@ -524,13 +716,15 @@ impl Publication { } } -/// Pre-allocated predecessor links held until acceptance. While deferred on the -/// successor, each link keeps `target: None` so no Arc cycle can form; once -/// attached to a predecessor on out-of-order completion, the predecessor owns -/// the link and the successor has already dropped its predecessor references. +/// Pre-allocated predecessor links held until acceptance, all in one block that the +/// successor owns from activation on. While deferred on the successor, each link +/// holds its predecessor and keeps `target: None` so no Arc cycle can form; once +/// attached to a predecessor on out-of-order completion, the link holds the +/// successor instead, and so its block, until the predecessor has consumed it, +/// or released it when dropped unpublished (`State::drop`). pub(crate) struct Prepared { target: Arc, - links: KVec<(Arc, KBox)>, + block: LinkBlock, } impl Prepared { @@ -538,27 +732,43 @@ impl Prepared { target: Arc, predecessors: impl Iterator> + Clone, ) -> Result { - let mut links = KVec::with_capacity(predecessors.clone().count(), GFP_KERNEL)?; + // One link per covered unfinished predecessor, all in one allocation that the target + // owns once active: it publishes only after every predecessor has consumed its link, + // so the block outlives each of them, and one charge per job keeps memcg's per-object + // hooks off the submit and event paths. + let count = predecessors.clone().count(); + let mut block = LinkBlock(KVVec::with_capacity(count, LINK_FLAGS)?); + if count != 0 { + note_block(false); + } for predecessor in predecessors { - let link = KBox::new(Link { - target: None, - result: Ok(()), - next: None, - resume: None, - }, GFP_KERNEL)?; - links.push((predecessor.clone(), link), GFP_KERNEL)?; + block + .0 + .push_within_capacity(UnsafeCell::new(Link { + target: None, + predecessor: Some(predecessor.clone()), + result: Ok(()), + next: None, + resume: None, + })) + .map_err(|_| ENOMEM)?; } - Ok(Self { target, links }) + Ok(Self { target, block }) } /// Called after all fallible scheduler setup and before any GPU publication. pub(crate) fn activate(self) { + let mut block = self.block; + let links = block.list_links(); + let count = block.0.len(); let attach_now = { let mut state = self.target.state.lock(); - debug_assert!(state.remaining == 1 && !state.claimed); + debug_assert!(state.remaining == 1 && !state.claimed && state.block.is_none()); state.remaining -= 1; + // Moving the vector leaves its buffer, and so every link, in place. + state.block = Some(block); if state.result.is_some() { - if self.links.is_empty() { + if links.is_none() { let ready = self.target.claim_locked(&mut state); drop(state); if let Some(result) = ready { @@ -566,20 +776,20 @@ impl Prepared { } return; } - state.remaining += 1 + self.links.len(); - Some(self.links) + state.remaining += 1 + count; + links } else { - if self.links.is_empty() && !self.target.has_outputs { + if links.is_none() && !self.target.has_outputs { state.upstream_released = true; self.target.phase.store(PHASE_SETTLED_CLEAN, Ordering::Release); } else { - state.deferred_links = self.links; + state.deferred_links = links; } None } }; - if let Some(links) = attach_now { - self.target.attach_deferred(links); + if attach_now.is_some() { + self.target.attach_deferred(attach_now); } } } @@ -871,4 +1081,94 @@ mod tests { assert!(!consumer.is_pending()); assert!(consumer.failed_after_release()); } + + fn blocks() -> (usize, usize) { + (BLOCKS[0].load(Ordering::Relaxed), BLOCKS[1].load(Ordering::Relaxed)) + } + + #[test] + fn consumer_links_are_one_charged_allocation() { + assert!(LINK_FLAGS.contains(GFP_KERNEL_ACCOUNT)); + let contexts = FenceContexts::new(1, c_str!("asahi_pub_block"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let (a, _) = make_pub(&contexts, &status, true); + let (b, _) = make_pub(&contexts, &status, true); + let (c, _) = make_pub(&contexts, &status, true); + for producer in [&a, &b, &c] { + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + } + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let start = blocks(); + Prepared::new(consumer.clone(), [&a, &b, &c].into_iter()).unwrap().activate(); + assert_eq!(blocks().0 - start.0, 1); + + // Error in the middle of the prefix: the consumer still waits for the last + // producer, then inherits the failure. + a.finish(Ok([1, 2, 0, 0])); + b.finish(Err(EIO)); + consumer.finish(Ok([7, 8, 0, 0])); + assert_eq!(fence_status(&cons_fence), 0); + c.finish(Ok([3, 4, 0, 0])); + assert_eq!(fence_status(&cons_fence), PRODUCER_FAILED.to_errno()); + + assert_eq!(blocks().1 - start.1, 0); + drop(consumer); + assert_eq!(blocks(), (start.0 + 1, start.1 + 1)); + } + + #[test] + fn link_block_is_freed_once_on_release_and_drop_paths() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_block_free"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + + // Release: timestamp-free consumer settles when both producers publish cleanly. + let (a, _) = make_pub(&contexts, &status, true); + let (b, _) = make_pub(&contexts, &status, true); + Prepared::new(a.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(b.clone(), core::iter::empty()).unwrap().activate(); + let (consumer, cons_fence) = make_pub(&contexts, &status, false); + let start = blocks(); + Prepared::new(consumer.clone(), [&a, &b].into_iter()).unwrap().activate(); + a.finish(Ok([1, 2, 0, 0])); + assert!(consumer.is_pending()); + b.finish(Ok([3, 4, 0, 0])); + assert!(!consumer.is_pending()); + consumer.finish(Ok([5, 6, 0, 0])); + assert!(fence_status(&cons_fence) > 0); + drop(consumer); + assert_eq!(blocks(), (start.0 + 1, start.1 + 1)); + + // Setup that fails before activation drops its block unused. + let (late, _) = make_pub(&contexts, &status, false); + let start = blocks(); + drop(Prepared::new(late.clone(), [&a, &b].into_iter()).unwrap()); + assert_eq!(blocks(), (start.0 + 1, start.1 + 1)); + + // A successor dropped with its links still deferred frees its block once. + let (stuck, _) = make_pub(&contexts, &status, true); + Prepared::new(stuck.clone(), core::iter::empty()).unwrap().activate(); + let (waiter, _) = make_pub(&contexts, &status, false); + let start = blocks(); + Prepared::new(waiter.clone(), core::iter::once(&stuck)).unwrap().activate(); + drop(waiter); + assert_eq!(blocks(), (start.0 + 1, start.1 + 1)); + + // A predecessor dropped before it publishes releases the links installed in it: + // the waiter's `finish()` attaches its deferred link first. + let (waiter, _) = make_pub(&contexts, &status, false); + let start = blocks(); + Prepared::new(waiter.clone(), core::iter::once(&stuck)).unwrap().activate(); + waiter.finish(Ok([1, 2, 0, 0])); + assert!(stuck.state.lock().successors.is_some()); + drop(stuck); + assert_eq!(blocks().1 - start.1, 0); + drop(waiter); + assert_eq!(blocks(), (start.0 + 1, start.1 + 1)); + + // No predecessors: no block at all. + let (alone, _) = make_pub(&contexts, &status, false); + let start = blocks(); + Prepared::new(alone.clone(), core::iter::empty()).unwrap().activate(); + assert_eq!(blocks(), start); + } } diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index ea8e02319177f..ae3c45050488e 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -131,7 +131,7 @@ pub(crate) struct Packet { pub(crate) footprint: Option>, /// Number of render passes in the submit ioctl that created this packet. pub(crate) batch_renders: u16, - inputs: KVec, + inputs: KVVec, /// The submission's own input fences ([`super::sync_input::Inputs`]), unless compute sources /// take them over in firmware. shared_inputs: Option, @@ -169,7 +169,7 @@ impl Packet { order: Order, completion: Arc, batch_renders: u16, - inputs: KVec, + inputs: KVVec, shared_inputs: Option, producers: Option, ) -> Result> { @@ -663,7 +663,7 @@ pub(crate) struct Fences { /// timestamp-free publication chaining. `None` for commands that write their /// own timestamps (covered by `completed`) or have no pending timestamp /// ancestors. - pub(crate) timestamp_waits: Option>>, + pub(crate) timestamp_waits: Option>>, /// `(since, prefix)` of [`Producers`] when the command waits for the other engine's /// producers in firmware: what that engine's failure log must keep for it. pub(crate) producers: Option<(u64, Option)>, @@ -743,7 +743,7 @@ impl Scheduler { pub(crate) fn enqueue( &mut self, packet: Arc, - dependencies: KVec, + dependencies: KVVec, early: bool, publication: Option, ) -> Result { diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 5b544db04c781..1676a6aca7b9e 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -406,26 +406,29 @@ impl Queue { )?; let input_dependencies = command_inputs.as_ref().map_or(&[][..], |inputs| inputs.dependencies()); - let mut dependencies = KVec::with_capacity( + // These grow with the producers this command waits for, which userspace decides: the + // other engine's unfinished commands alone can number thousands. So they need no + // contiguous pages and are charged to the caller. + let mut dependencies = KVVec::with_capacity( // The firmware-ordered producers add one scheduled fence between them. input_dependencies.len() + ordering_host_waits.len() + usize::from(!ordering_firmware_waits.is_empty()) + failure_count, - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; // Host-waited producers are checked on the host instead of in firmware. - let mut checked_inputs = KVec::with_capacity( + let mut checked_inputs = KVVec::with_capacity( ordering_host_waits.len() + failure_count, - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; for fence in failures.into_iter().flatten() { - checked_inputs.push(fence.clone(), GFP_KERNEL)?; - dependencies.push(fence.clone(), GFP_KERNEL)?; + checked_inputs.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; + dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; } for fence in ordering_host_waits { - dependencies.push(fence.clone(), GFP_KERNEL)?; - checked_inputs.push(fence, GFP_KERNEL)?; + dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; + checked_inputs.push(fence, GFP_KERNEL_ACCOUNT)?; } // Firmware orders execution after each producer; the scheduler needs only the latest // scheduled fence of producers that have not already been published into firmware. @@ -436,7 +439,7 @@ impl Queue { { if !*published && job::fence_status(scheduled) <= 0 { producer_waits.producer(scheduled, |fence| { - Ok(dependencies.push(fence.clone(), GFP_KERNEL)?) + Ok(dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?) })?; } } @@ -449,16 +452,16 @@ impl Queue { since, prefix, }); - producer_waits.finish(|fence| Ok(dependencies.push(fence.clone(), GFP_KERNEL)?))?; + producer_waits.finish(|fence| Ok(dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?))?; // Independent engines may publish in either order and must each consume an input's error // status before running, so every command keeps the inputs. for fence in input_dependencies { - dependencies.push(fence.clone(), GFP_KERNEL)?; + dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; } if let Some(sources) = &sources { for ready in sources.publication_waits() { - dependencies.push(ready.clone(), GFP_KERNEL)?; - checked_inputs.push(ready.clone(), GFP_KERNEL)?; + dependencies.push(ready.clone(), GFP_KERNEL_ACCOUNT)?; + checked_inputs.push(ready.clone(), GFP_KERNEL_ACCOUNT)?; } } // Publish from the ioctl whenever nothing has to wait, at any depth. @@ -878,9 +881,9 @@ impl FrontierEntry for Fences { } } -fn push_unique_fence(out: &mut KVec, fence: &Fence) -> Result { +fn push_unique_fence(out: &mut KVVec, fence: &Fence) -> Result { if !out.iter().any(|existing| existing.raw() == fence.raw()) { - out.push(fence.clone(), GFP_KERNEL)?; + out.push(fence.clone(), GFP_KERNEL_ACCOUNT)?; } Ok(()) } @@ -888,7 +891,7 @@ fn push_unique_fence(out: &mut KVec, fence: &Fence) -> Result { /// Collect the actual pending host-timestamp writer fences represented by `entry`: /// its own `completed` fence when it writes host timestamps, otherwise its still-pending /// inherited timestamp-writer fences. -fn collect_timestamp_waits(entry: &E, out: &mut KVec) -> Result { +fn collect_timestamp_waits(entry: &E, out: &mut KVVec) -> Result { let Some(pub_ref) = entry.pending_publication() else { return Ok(()); }; @@ -904,15 +907,18 @@ fn collect_timestamp_waits(entry: &E, out: &mut KVec) - Ok(()) } +/// Each of these grows with the covered prefixes, which userspace sizes: the other engine's +/// unfinished commands alone can number thousands. So they need no contiguous pages and are +/// charged to the caller. struct EnqueueOrdering<'a> { - predecessors: KVec<&'a Arc>, + predecessors: KVVec<&'a Arc>, /// How far the command's ancestors reach on each engine, for its publication /// ([`Publication::set_reach`]). reach: [u64; 2], - host_waits: KVec, - firmware_waits: KVec<(Fence, Fence)>, - firmware_published: KVec, - inherited_timestamp_waits: KVec, + host_waits: KVVec, + firmware_waits: KVVec<(Fence, Fence)>, + firmware_published: KVVec, + inherited_timestamp_waits: KVVec, } impl<'a> EnqueueOrdering<'a> { @@ -940,11 +946,11 @@ impl<'a> EnqueueOrdering<'a> { // deferred error published between pruning and link selection, // `add_successor()` still delivers that failure immediately instead of // letting the successor signal success. - let mut predecessors = KVec::new(); - let mut host = KVec::new(); - let mut firmware = KVec::new(); - let mut firmware_published = KVec::new(); - let mut inherited_timestamp_waits = KVec::new(); + let mut predecessors = KVVec::new(); + let mut host = KVVec::new(); + let mut firmware = KVVec::new(); + let mut firmware_published = KVVec::new(); + let mut inherited_timestamp_waits = KVVec::new(); // A covered publication some kept predecessor already has as an ancestor needs no link of // its own: it fires before that predecessor, which fires before this command, and its // error reaches this command through it. Newest first, so the kept ones reach furthest. @@ -953,7 +959,7 @@ impl<'a> EnqueueOrdering<'a> { -> Result { if sequence > covered[engine_index] { - predecessors.push(publication, GFP_KERNEL)?; + predecessors.push(publication, GFP_KERNEL_ACCOUNT)?; for (reach, slot) in covered.iter_mut().enumerate() { *slot = (*slot).max(publication.reach(reach)); } @@ -1040,16 +1046,16 @@ impl<'a> EnqueueOrdering<'a> { collect_timestamp_waits(entry, &mut host)?; firmware.push( (entry.scheduled().clone(), entry.completed().clone()), - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; - firmware_published.push(entry.inline_published(), GFP_KERNEL)?; + firmware_published.push(entry.inline_published(), GFP_KERNEL_ACCOUNT)?; } } else { firmware.push( (entry.scheduled().clone(), entry.completed().clone()), - GFP_KERNEL, + GFP_KERNEL_ACCOUNT, )?; - firmware_published.push(entry.inline_published(), GFP_KERNEL)?; + firmware_published.push(entry.inline_published(), GFP_KERNEL_ACCOUNT)?; } } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.c b/drivers/gpu/drm/asahi/g17/sync_input.c index 4adbe490a5e00..8243a9804f265 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.c +++ b/drivers/gpu/drm/asahi/g17/sync_input.c @@ -164,11 +164,12 @@ struct dma_fence *asahi_g17_merge_fences(struct dma_fence *const *fences, size_t struct dma_fence_unwrap *cursors; struct dma_fence *merged; - cursors = kmalloc_array(count, sizeof(*cursors), GFP_KERNEL); + /* One cursor per fence the command waits for: no contiguous pages needed. */ + cursors = kvmalloc_array(count, sizeof(*cursors), GFP_KERNEL_ACCOUNT); if (!cursors) return NULL; merged = __dma_fence_unwrap_merge(count, (struct dma_fence **)fences, cursors); - kfree(cursors); + kvfree(cursors); return merged; } diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index a63d4267dad60..c4bc93c461e49 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -40,9 +40,10 @@ impl super::dependency::FenceOrder for Fence { /// One fence that signals once all of `fences` have (see `job::MERGED_DEPENDENCIES`). pub(super) fn merge(fences: &[Fence]) -> Result { - let mut raw = KVec::with_capacity(fences.len(), GFP_KERNEL)?; + // As many as the command waits for: no contiguous pages, charged to the caller. + let mut raw = KVVec::with_capacity(fences.len(), GFP_KERNEL_ACCOUNT)?; for fence in fences { - raw.push(fence.raw(), GFP_KERNEL)?; + raw.push(fence.raw(), GFP_KERNEL_ACCOUNT)?; } // SAFETY: Every pointer is a live fence borrowed from `fences` for this call; // the helper only reads them and returns a new reference of its own. diff --git a/tools/asahi/g17-inline-cross-engine-tests.py b/tools/asahi/g17-inline-cross-engine-tests.py index 585ed819d67a7..140d3d7176e0c 100755 --- a/tools/asahi/g17-inline-cross-engine-tests.py +++ b/tools/asahi/g17-inline-cross-engine-tests.py @@ -110,7 +110,7 @@ def build_harness(mutation=None): # Verify structural pieces that feed into inline_published. fences_has_inline = ( 'pub(crate) inline_published: bool,' in job_src - and 'firmware_published.push(entry.inline_published(), GFP_KERNEL)?;' in queue_src + and 'firmware_published.push(entry.inline_published(), GFP_KERNEL_ACCOUNT)?;' in queue_src ) # Extract the guard prefix of try_compute_early and try_render_early up to begin_publication. @@ -122,9 +122,9 @@ def build_harness(mutation=None): rend_guard_end = rend_early_fn.index('let admission =', rend_guard_start) rend_guard = rend_early_fn[rend_guard_start:rend_guard_end] - # Normalize loop_block for std Vec instead of KVec(..., GFP_KERNEL)?. + # Normalize loop_block for std Vec instead of KVVec(..., GFP_KERNEL_ACCOUNT)?. loop_std = loop_block.replace( - 'Ok(dependencies.push(fence.clone(), GFP_KERNEL)?)', + 'Ok(dependencies.push(fence.clone(), GFP_KERNEL_ACCOUNT)?)', '{ dependencies.push(fence.clone()); Ok::<(), i32>(()) }', ) diff --git a/tools/asahi/g17-publication-lazy-tests.py b/tools/asahi/g17-publication-lazy-tests.py index 13b5daa634462..09efd52b3a97e 100755 --- a/tools/asahi/g17-publication-lazy-tests.py +++ b/tools/asahi/g17-publication-lazy-tests.py @@ -50,14 +50,14 @@ def build_harness(mutation=None): claim_fn = item(pub_src, 'fn claim_locked(&self, state: &mut State)') publish_fn = item(pub_src, 'fn publish(&self, result: Result<[u64; 4]>) -> Links') is_pending_fn = item(pub_src, 'fn pending_within(&self, depth: usize) -> bool') - add_succ_fn = item(pub_src, 'fn add_successor(&self, mut link: KBox) -> bool') + add_succ_fn = item(pub_src, 'fn add_successor(&self, link: NonNull) -> bool') subscribe_fn = item(pub_src, 'fn subscribe(mut stack: Option>)') link_fn = item(pub_src, 'fn link_deferred(') if mutation == 'eager-activate': activate_fn = activate_fn.replace( - 'state.deferred_links = self.links;', - 'for (p, l) in self.links { p.add_successor(l); }', + 'state.deferred_links = links;', + 'predecessor.add_successor(links);', 1, ) elif mutation == 'cycle-target-some': @@ -88,11 +88,11 @@ def build_harness(mutation=None): 1, ) elif mutation == 'no-subscribe': - add_succ_fn = add_succ_fn.replace('&& !state.deferred_links.is_empty();', '&& false;', 1) + add_succ_fn = add_succ_fn.replace('&& state.deferred_links.is_some();', '&& false;', 1) elif mutation == 'skip-fast-check': link_fn = link_fn.replace( - 'if predecessor.is_settled_clean() {', - 'if false {', + 'Some(predecessor) if !predecessor.is_settled_clean() =>', + 'Some(predecessor) if true =>', 1, ) @@ -100,10 +100,10 @@ def build_harness(mutation=None): 'single_atomic_phase': 'phase: AtomicU8,' in pub_src and 'pending: AtomicBool' not in pub_src and 'settled_clean: AtomicBool' not in pub_src, - 'lazy_activate': 'state.deferred_links = self.links;' in activate_fn + 'lazy_activate': 'state.deferred_links = links;' in activate_fn and 'predecessor.add_successor' not in activate_fn, 'no_cycle_prep': 'target: None,' in new_prep_fn, - 'fast_settled_check': 'if predecessor.is_settled_clean() {' in link_fn, + 'fast_settled_check': 'Some(predecessor) if !predecessor.is_settled_clean() =>' in link_fn, 'error_phase_on_publish': 'PHASE_FAILED_AFTER_SETTLE' in publish_fn and 'PHASE_FAILED_PENDING' in publish_fn, 'revoke_clean_on_claim_err': 'state.upstream_released = false;' in claim_fn @@ -114,9 +114,9 @@ def build_harness(mutation=None): and 'self.phase.store(PHASE_SETTLED_CLEAN, Ordering::Release);' in is_pending_fn, 'bounded_probe': 'pred.pending_within(depth - 1)' in is_pending_fn, 'consume_failed': 'Some((index, PHASE_FAILED_PENDING | PHASE_FAILED_AFTER_SETTLE)) => {' in is_pending_fn - and 'Probe::Consumed(state.deferred_links.swap_remove(index))' in is_pending_fn + and 'Probe::Consumed(state.unlink_deferred(index))' in is_pending_fn and 'let first_unclean =' in is_pending_fn, - 'subscribe_deferred': '&& !state.deferred_links.is_empty();' in add_succ_fn + 'subscribe_deferred': '&& state.deferred_links.is_some();' in add_succ_fn and 'state.subscribe_queued |= subscribe;' in add_succ_fn and '*stack = Some(predecessor);' in link_fn and 'node.link_deferred(deferred, &mut stack);' in subscribe_fn diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py index 15d20e5ea7206..99af9f3eabb65 100644 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-fence-signalling.py @@ -557,6 +557,7 @@ def extract_function(text, name): static inline void smp_rmb(void) { } +#define GFP_KERNEL_ACCOUNT 0 struct dma_fence { uint64_t context; @@ -641,13 +642,13 @@ def extract_function(text, name): for ((fence) = dma_fence_unwrap_first((head), (cursor)); (fence); \ (fence) = dma_fence_unwrap_next((cursor))) -static inline void *kmalloc_array(size_t n, size_t size, int flags) +static inline void *kvmalloc_array(size_t n, size_t size, int flags) { (void)flags; return calloc(n, size); } -static inline void kfree(void *p) +static inline void kvfree(void *p) { free(p); }