diff --git a/drivers/gpu/drm/asahi/file.rs b/drivers/gpu/drm/asahi/file.rs index ba674b41fa410..45fd6f47c1362 100644 --- a/drivers/gpu/drm/asahi/file.rs +++ b/drivers/gpu/drm/asahi/file.rs @@ -375,6 +375,14 @@ fn admit_bind( ledger.admit(client, BOUND_OBJECT_BYTES) } +/// Closing the handle can wake a submitter independently of the queue's ioctl mutex. +#[pin_data] +struct QueueHandle { + admission: Option>, + #[pin] + state: Mutex, +} + /// A queue in a file's table. Its count in the creating process's share of the device's /// queues is given back once the queue itself is gone. pub(crate) struct TableQueue { @@ -390,7 +398,7 @@ impl TableQueue { const REUSE_CMDBUF_CAP: usize = 4096; /// Takes the cached command-buffer staging allocation so userspace copies run outside the - /// queue mutex (preventing `queue.lock()` -> `mmap_lock` lock-order inversion). + /// queue mutex (preventing `queue.state.lock()` -> `mmap_lock` lock-order inversion). fn take_cmdbuf(&mut self) -> KVVec { core::mem::take(&mut self.cmdbuf) } @@ -438,7 +446,7 @@ pub(crate) struct File { // Fields drop in order: the queues go first, so that a closing client's submitted work // can finish before its VMs unmap the user ranges. // #[pin] - queues: xarray::XArray>>, + queues: xarray::XArray>, // #[pin] vms: xarray::XArray>, // #[pin] @@ -550,7 +558,7 @@ impl File { let raw_queues = addr_of_mut!((*slot).queues); pin_init::raw_try_init( raw_queues, - xarray::XArray::>>::new( + xarray::XArray::>::new( xarray::AllocKind::Alloc1, ), )?; @@ -580,7 +588,7 @@ impl File { } #[allow(clippy::type_complexity)] - fn queues(self: Pin<&Self>) -> Pin<&xarray::XArray>>> { + fn queues(self: Pin<&Self>) -> Pin<&xarray::XArray>> { // SAFETY: Structural pinned projection for queues. // We never move out of this field. unsafe { self.map_unchecked(|s| &s.queues) } @@ -1537,13 +1545,13 @@ impl File { .queues() .find(index, usize::MAX) .map(|(idx, guard)| { - let queue: Arc> = guard.borrow().into(); + let queue: Arc = guard.borrow().into(); (idx, queue) }) else { break; }; - queue.lock().drain(); + queue.state.lock().drain(); if idx == usize::MAX { break; } @@ -1557,10 +1565,10 @@ impl File { let mut index = 0; while let Some((idx, entry)) = this.vms().find(index, usize::MAX) { let vm: &Vm = entry.borrow(); - if which(vm) { - if let Some(status) = vm.vm.status() { - status.mark_client_closed(); - } + let status = if which(vm) { vm.vm.status().cloned() } else { None }; + drop(entry); + if let Some(status) = status { + status.mark_client_closed(); } if idx == usize::MAX { break; @@ -1847,10 +1855,13 @@ impl File { data.queue_id = resv.index().try_into()?; resv.fill(Arc::pin_init( - new_mutex!(TableQueue { - queue, - cmdbuf: KVVec::new(), - _share: share, + pin_init!(QueueHandle { + admission: queue.admission(), + state <- new_mutex!(TableQueue { + queue, + cmdbuf: KVVec::new(), + _share: share, + }), }), GFP_KERNEL, )?)?; @@ -1867,11 +1878,9 @@ impl File { ) -> Result { // grab the queue so the xarray spinlock is dropped first let queue = file.inner().queues().remove(data.queue_id as usize); - if queue.is_none() { - Err(ENOENT) - } else { - Ok(0) - } + let queue = queue.ok_or(ENOENT)?; + if let Some(room) = &queue.admission { room.close(); } + Ok(0) } /// IOCTL: submit: Submit GPU work to a command submission queue. @@ -1897,7 +1906,7 @@ impl File { } // Upgrade to Arc to drop the XArray lock early - let queue: Arc> = file + let queue: Arc = file .inner() .queues() .lock() @@ -1927,11 +1936,11 @@ impl File { // on every failure but a refusal (ENOMEM, ENOSPC), which leaves them // untouched (DRM_ASAHI_FEATURE_SUBMIT_REFUSAL_UNTOUCHED). Take the fallible userspace snapshot before that point, // staging into a buffer taken from the queue's reusable cache so user - // copies never execute under `queue.lock()`. + // copies never execute under `queue.state.lock()`. let mut cmdbuf = if guarded { - let mut buf = queue.lock().take_cmdbuf(); + let mut buf = queue.state.lock().take_cmdbuf(); if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { - queue.lock().return_cmdbuf(buf); + queue.state.lock().return_cmdbuf(buf); return Err(e); } Some(buf) @@ -1958,7 +1967,7 @@ impl File { Ok(syncs) => syncs, Err(e) => { if let Some(buf) = cmdbuf { - queue.lock().return_cmdbuf(buf); + queue.state.lock().return_cmdbuf(buf); } return Err(e); } @@ -1972,15 +1981,15 @@ impl File { id ); - // Copy the command buffer into the kernel outside `queue.lock()`. Because we + // Copy the command buffer into the kernel outside `queue.state.lock()`. Because we // need to iterate the command buffer twice, we do this in one big copy_from_user // to avoid TOCTOU issues. let cmdbuf = match cmdbuf.take() { Some(buf) => buf, None => { - let mut buf = queue.lock().take_cmdbuf(); + let mut buf = queue.state.lock().take_cmdbuf(); if let Err(e) = copy_cmdbuf_from_user(&mut buf, data.cmdbuf, cmdbuf_size) { - queue.lock().return_cmdbuf(buf); + queue.state.lock().return_cmdbuf(buf); return Err(e); } buf @@ -1988,7 +1997,20 @@ impl File { }; let objects = file.inner().objects(); - let mut guard = queue.lock(); + // A full queue takes the submission once it has room. Sleep without its lock, which + // nothing that frees the room takes, and check again under it. Nothing is published yet, + // so a signal restarts the ioctl. + let mut guard = loop { + let guard = queue.state.lock(); + let Some(room) = queue.admission.as_ref().filter(|room| room.must_wait()) else { + break guard; + }; + drop(guard); + if let Err(error) = room.wait() { + queue.state.lock().return_cmdbuf(cmdbuf); + return Err(error); + } + }; let ret = guard.queue.submit( reg_data, id, diff --git a/drivers/gpu/drm/asahi/g17/completion/publication.rs b/drivers/gpu/drm/asahi/g17/completion/publication.rs index a5033558636ee..4c503b67412c7 100644 --- a/drivers/gpu/drm/asahi/g17/completion/publication.rs +++ b/drivers/gpu/drm/asahi/g17/completion/publication.rs @@ -58,6 +58,9 @@ struct Link { // 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, + /// One unit of the queue budget ([`Prepared::with_charges`]), given back with the link's + /// memory: delivered, dropped unused, or freed with a queue. + charge: Option, } struct State { @@ -545,12 +548,23 @@ impl Prepared { result: Ok(()), next: None, resume: None, + charge: None, }, GFP_KERNEL)?; links.push((predecessor.clone(), link), GFP_KERNEL)?; } Ok(Self { target, links }) } + /// Charges each link one unit of `budget`, given back when the link is freed (delivered or + /// dropped unused), not when the publication goes: its queue's frontier keeps that until the + /// next submission, which may be waiting for these units. + pub(crate) fn with_charges(mut self, budget: &Arc) -> Self { + for (_, link) in self.links.iter_mut() { + link.charge = Some(budget.charge(1)); + } + self + } + /// Called after all fallible scheduler setup and before any GPU publication. pub(crate) fn activate(self) { let attach_now = { @@ -633,6 +647,39 @@ mod tests { (Publication::new(output, status.clone(), has_outputs).unwrap(), handle) } + #[test] + fn link_units_come_back_once_the_links_are_freed() { + let contexts = FenceContexts::new(1, c_str!("asahi_pub_charge"), KEY).unwrap(); + let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL).unwrap(); + let budget = crate::g17::queue::budget::Budget::with_limit(1).unwrap(); + let pair = || { + let (producer, _) = make_pub(&contexts, &status, true); + let (consumer, _) = make_pub(&contexts, &status, false); + Prepared::new(producer.clone(), core::iter::empty()).unwrap().activate(); + Prepared::new(consumer.clone(), core::iter::once(&producer)) + .unwrap() + .with_charges(&budget) + .activate(); + (producer, consumer) + }; + // Delivered: the consumer finishes first, so its link waits in the producer's successor + // list until the producer publishes. The units come back while `consumer` still holds the + // publication, as its queue's frontier does until the next submission. + let (producer, consumer) = pair(); + assert!(budget.full()); + consumer.finish(Ok([1, 2, 3, 4])); + assert!(budget.full()); + producer.finish(Ok([5, 6, 0, 0])); + assert_eq!(budget.used(), 0); + // Dropped unused: the producer has published when the consumer finishes. + let (producer, consumer2) = pair(); + assert!(budget.full()); + producer.finish(Ok([5, 6, 0, 0])); + consumer2.finish(Ok([1, 2, 3, 4])); + assert_eq!(budget.used(), 0); + drop((consumer, consumer2)); + } + #[test] fn consumer_retiring_before_delayed_producer_failure_inherits_error() { let contexts = FenceContexts::new(1, c_str!("asahi_pub_test"), KEY).unwrap(); diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index f13a4a3b24179..253738d560dc6 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -414,7 +414,7 @@ impl Context { let render_id = Arc::pin_init(new_mutex!(render_id, "G17 context render pool identity"), GFP_KERNEL)?; let order = - Arc::pin_init(new_mutex!(Order::new(), "G17 context admission order"), GFP_KERNEL)?; + Arc::pin_init(new_mutex!(Order::new()?, "G17 context admission order"), GFP_KERNEL)?; let kill = Arc::new(Kill::new(), GFP_KERNEL)?; let order_wait = Arc::pin_init(new_condvar!("G17 context admission order wait"), GFP_KERNEL)?; @@ -867,7 +867,7 @@ pub(super) struct TestOrderWindow { #[cfg(CONFIG_KUNIT = "y")] impl TestOrderWindow { pub(super) fn new_full() -> Result { - let order = KBox::pin_init(new_mutex!(Order::new(), "G17 test order"), GFP_KERNEL)?; + let order = KBox::pin_init(new_mutex!(Order::new()?, "G17 test order"), GFP_KERNEL)?; let wait = KBox::pin_init(new_condvar!("G17 test order wait"), GFP_KERNEL)?; let status = Arc::pin_init(VmStatus::new(), GFP_KERNEL)?; let first = { diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index 16bc0a7d8d5de..c215b8d36d053 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -96,14 +96,24 @@ impl WorkStates { } } -/// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the -/// turn remembered for ioctls that left early. +/// Maximum number of live ordinals waiting for a work-state node. pub(super) const ORDER_WINDOW: u64 = 2048; /// Cap for extra work-state splits inside multi-command ioctls, keeping the upper half of /// [`ORDER_WINDOW`] permanently reserved for new ioctls. pub(super) const ORDER_SPLIT_LIMIT: u64 = ORDER_WINDOW / 2; +// A full queue makes its submitter sleep on the budget before the window could make it wait, +// and after a second refuse it (EBUSY, a lost device to Vulkan). Every live ticket is the lease +// of at least one pending command: a split is taken only for a following command. A submission +// is admitted only while its queue holds less than its budget, and each pending command holds at +// least COMMAND_UNITS of it (`queue::budget`). So an admitted submission finds fewer than +// UNITS / COMMAND_UNITS live tickets. An early departure returns its ticket immediately. +const _: () = assert!( + ORDER_WINDOW + >= (super::super::queue::budget::UNITS / super::super::queue::budget::COMMAND_UNITS) as u64 +); + /// The order in which a context's ioctls take work-state nodes. /// /// Each engine admits a context's ioctls in submission order, but the engines advance @@ -122,7 +132,7 @@ pub(super) const ORDER_SPLIT_LIMIT: u64 = ORDER_WINDOW / 2; /// it. Taking nodes strictly in turn keeps the words in submission order. Each engine admits /// from its own scheduler, so the turn costs a scheduler round trip whenever the other engine's /// ioctl is ready first. -/// Which waiters to wake after [`Order::admit`] or [`Order::leave`] advances the turn. +/// Which waiters to wake after [`Order::admit`] or [`Order::leave`] frees a ticket. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub(super) struct OrderWake { pub(super) publishers: bool, @@ -132,88 +142,92 @@ pub(super) struct OrderWake { pub(super) struct Order { /// The next ordinal to hand out. next: u64, - /// The oldest ordinal that has neither taken a node nor left. - turn: u64, - /// Ordinals past the turn that left, as bits at ordinal % ORDER_WINDOW. - done: [u64; (ORDER_WINDOW / 64) as usize], - /// A scheduler publisher was refused since the turn last moved. + /// A FIFO of live tickets. Normal admission advances its head in constant time. + tickets: KVVec, + head: usize, + len: usize, + /// A scheduler publisher was refused since the head last moved. refused: bool, - /// A submitter hit the full window since the turn last moved. + /// A submitter hit the full window since a ticket last left. submitter_waiting: bool, } impl Order { - pub(super) const fn new() -> Self { - Self { + pub(super) fn new() -> Result { + Ok(Self { next: 0, - turn: 0, - done: [0; (ORDER_WINDOW / 64) as usize], + tickets: KVVec::from_elem(0, ORDER_WINDOW as usize, GFP_KERNEL)?, + head: 0, + len: 0, refused: false, submitter_waiting: false, - } + }) + } + fn slot(&self, offset: usize) -> usize { + (self.head + offset) % self.tickets.len() } /// The ordinal of a new ioctl, in submission order. None while [`ORDER_WINDOW`] ioctls of - /// the context are past the oldest one still waiting for its node; remembers the refusal - /// so the next turn advance wakes blocked submitters. + /// the context wait for their nodes; remembers the refusal so the next ticket to leave wakes + /// blocked submitters. pub(super) fn assign(&mut self) -> Option { - if self.next - self.turn >= ORDER_WINDOW { + if self.len == self.tickets.len() { self.submitter_waiting = true; return None; } let ordinal = self.next; self.next += 1; + let tail = self.slot(self.len); + self.tickets[tail] = ordinal; + self.len += 1; Some(ordinal) } /// The ordinal of an extra work-state split within a multi-command ioctl. None once - /// [`ORDER_SPLIT_LIMIT`] ordinals are ahead of the turn so new ioctls keep full headroom. + /// [`ORDER_SPLIT_LIMIT`] tickets are live so new ioctls keep full headroom. pub(super) fn assign_split(&mut self) -> Option { - if self.next - self.turn >= ORDER_SPLIT_LIMIT { - return None; - } + if self.len >= ORDER_SPLIT_LIMIT as usize { return None } self.assign() } /// Whether the ioctl `ordinal` may take its node now: only at its turn. A refusal is /// remembered until the turn next moves, so that move wakes the refused publisher. pub(super) fn admits(&mut self, ordinal: u64) -> bool { - let admits = ordinal == self.turn; + let admits = self.len != 0 && self.tickets[self.head] == ordinal; self.refused |= !admits; admits } /// The ioctl `ordinal` took its node at its turn. Returns which waiters may now retry. pub(super) fn admit(&mut self, ordinal: u64) -> OrderWake { - self.finish(ordinal) - } - /// The ioctl `ordinal` left without taking a node (it failed or was cancelled first). - /// Returns which waiters may now retry. - pub(super) fn leave(&mut self, ordinal: u64) -> OrderWake { - self.finish(ordinal) - } - fn finish(&mut self, ordinal: u64) -> OrderWake { - if ordinal < self.turn { + if self.len == 0 || self.tickets[self.head] != ordinal { return OrderWake::default(); } - if ordinal == self.turn { - self.pass(); - return OrderWake { - publishers: core::mem::take(&mut self.refused), - submitters: core::mem::take(&mut self.submitter_waiting), - }; + self.head = self.slot(1); + self.len -= 1; + OrderWake { + publishers: core::mem::take(&mut self.refused), + submitters: core::mem::take(&mut self.submitter_waiting), } - // assign() keeps every ordinal within the window past the turn. - let bit = ordinal % ORDER_WINDOW; - self.done[(bit / 64) as usize] |= 1 << (bit % 64); - OrderWake::default() } - /// Moves the turn past the current ordinal and every following one already done. - fn pass(&mut self) { - loop { - self.turn += 1; - let bit = self.turn % ORDER_WINDOW; - let (word, mask) = ((bit / 64) as usize, 1u64 << (bit % 64)); - if self.done[word] & mask == 0 { - break; + /// The ioctl `ordinal` left without taking a node (it failed or was cancelled first). + /// Returns which waiters may now retry: its ticket frees a slot at once, but only the head + /// leaving moves the turn. + pub(super) fn leave(&mut self, ordinal: u64) -> OrderWake { + if self.len == 0 || ordinal < self.tickets[self.head] { return OrderWake::default() } + if self.tickets[self.head] == ordinal { return self.admit(ordinal) } + // Cancellation can remove a ticket anywhere. Compact only its younger + // neighbors, preserving their admission order across ring wraparound. + for offset in (1..self.len).rev() { + let index = self.slot(offset); + if self.tickets[index] == ordinal { + for pos in offset..self.len - 1 { + let dest = self.slot(pos); + self.tickets[dest] = self.tickets[self.slot(pos + 1)]; + } + self.len -= 1; + return OrderWake { + publishers: false, + submitters: core::mem::take(&mut self.submitter_waiting), + }; } - self.done[word] &= !mask; } + OrderWake::default() } } @@ -370,7 +384,7 @@ mod tests { #[test] fn ioctls_take_nodes_only_at_their_turn() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); let ordinals: [u64; 4] = core::array::from_fn(|_| order.assign().unwrap()); // Only the oldest waiting ioctl may take its node; the others are refused. for &ordinal in &ordinals[1..] { @@ -390,7 +404,7 @@ mod tests { #[test] fn ioctls_leaving_without_a_node_pass_the_turn() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); let (a, b, c, d) = ( order.assign().unwrap(), order.assign().unwrap(), @@ -410,24 +424,63 @@ mod tests { #[test] fn no_ioctl_is_ordered_past_the_window() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); let first = order.assign().unwrap(); let mut last = first; for _ in 1..ORDER_WINDOW { last = order.assign().unwrap(); } assert!(order.assign().is_none()); - // An ioctl leaving far ahead is remembered within the window. - assert_eq!(order.leave(last), OrderWake::default()); + // A younger ioctl leaving frees its ticket at once and wakes the submitter that found the + // window full. + assert_eq!(order.leave(last), OrderWake { publishers: false, submitters: true }); + // Keep the oldest blocked while more than a whole window of younger ioctls leave. + for _ in 0..ORDER_WINDOW + 1 { + let replacement = order.assign().unwrap(); + assert_eq!(order.leave(replacement), OrderWake::default()); + } + // Full again: the oldest taking its node wakes the refused submitter, not a publisher. + order.assign().unwrap(); + assert!(order.assign().is_none()); assert!(order.admits(first)); - // Only the refused submitter waiting on the full window is woken once the turn advances. assert_eq!(order.admit(first), OrderWake { publishers: false, submitters: true }); assert!(order.assign().is_some()); } + #[test] + fn an_admitted_submission_always_finds_room_in_the_window() { + use crate::g17::queue::budget::{Budget, COMMAND_UNITS}; + // Behind an oldest ordinal that never takes its node, submissions arrive while the queue + // has budget left: first 64-command ones that split as often as they may (each split + // carries a command), then single-command ones, which take the most ordinals for their + // units. Each is admitted whole and charges its commands. The window must take every + // admitted one; the next sleeps on the budget. + let budget = Budget::new().unwrap(); + let mut order = Order::new().unwrap(); + let mut charges = KVec::new(); + let mut submissions = 0u32; + let mut refused = 0u32; + while !budget.full() { + if order.assign().is_none() { + refused += 1; + break; + } + let commands = if submissions < 8 { 64 } else { 1 }; + for command in 0..commands { + if command > 0 { + let _ = order.assign_split(); + } + charges.push(budget.charge(COMMAND_UNITS), GFP_KERNEL).unwrap(); + } + submissions += 1; + } + assert_eq!(refused, 0); + assert!(budget.full()); + } + #[test] fn split_ordinals_reserve_half_the_window_for_new_ioctls() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); for _ in 0..ORDER_SPLIT_LIMIT { assert!(order.assign_split().is_some()); } @@ -440,7 +493,7 @@ mod tests { #[test] fn single_engine_admission_wakes_nobody() { - let mut order = Order::new(); + let mut order = Order::new().unwrap(); for _ in 0..24 { let ordinal = order.assign().unwrap(); assert!(order.admits(ordinal)); diff --git a/drivers/gpu/drm/asahi/g17/job.rs b/drivers/gpu/drm/asahi/g17/job.rs index fe14dc661201e..e645b28588896 100644 --- a/drivers/gpu/drm/asahi/g17/job.rs +++ b/drivers/gpu/drm/asahi/g17/job.rs @@ -145,6 +145,8 @@ pub(crate) struct Packet { /// When the job's watchdog allowance ends (host ns, [`super::timeout::Allowance::end`]): /// zero under the default allowance, `u64::MAX` for a longer one not yet placed. allowance_end: AtomicU64, + /// Its queue's budget units for this state ([`super::queue::budget`]). + _charge: super::queue::budget::Charge, /// Another VM's watchdog took the rest of the allowance away /// ([`super::timeout::Verdict::forfeits`]). forfeited: AtomicBool, @@ -173,6 +175,7 @@ impl Packet { inputs: KVec, shared_inputs: Option, producers: Option, + charge: super::queue::budget::Charge, ) -> Result> { if command.is_none() { return Err(EINVAL); @@ -197,6 +200,7 @@ impl Packet { early: AtomicI32::new(0), backlog: AtomicBool::new(false), allowance_end: AtomicU64::new(0), + _charge: charge, forfeited: AtomicBool::new(false), first_excuse: AtomicU64::new(0), ordinal: AtomicU64::new(0), diff --git a/drivers/gpu/drm/asahi/g17/queue/budget.rs b/drivers/gpu/drm/asahi/g17/queue/budget.rs new file mode 100644 index 0000000000000..22ab9348f6124 --- /dev/null +++ b/drivers/gpu/drm/asahi/g17/queue/budget.rs @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: GPL-2.0-only OR MIT + +//! How much a userspace queue's pending commands may keep allocated. +//! +//! drm_sched credits bound only the commands on the firmware rings. Behind them a queue could keep +//! any number of commands waiting on a stalled job or a foreign fence, and each keeps its packet, +//! its fence vectors and its publication links, several of which grow with the number of other +//! pending commands it covers. So each queue has a budget of units: [`COMMAND_UNITS`] for a +//! command's own state and one for each fence reference or publication link it holds. A +//! submission waits, interruptibly, while the queue has used the whole budget, and the units come +//! back as that memory is freed ([`Charge`]). + +use kernel::{prelude::*, sync::Arc}; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use crate::g17::status::VmStatus; + +/// The commands a queue may keep pending when they hold no references, a policy constant: about +/// 2.3 times the deepest queue measured (Cyberpunk 2077, 874 commands pending on one queue on an +/// M4 Pro; a Hearthstone session, 339). That is 32 times the queue's hardware credits there (32 +/// render and 32 compute); amdgpu's default software queue is 16 times its hardware depth. +pub(crate) const COMMANDS: usize = 2048; + +/// One command's own state: its packet with the validated command, its completion and frontier +/// entries, about 2.5 KB, or 80 publication links (32 bytes, the largest reference), rounded up. +pub(crate) const COMMAND_UNITS: usize = 128; + +/// The whole budget of one queue: about 8 MB of what its pending commands hold however it is made +/// up (as links), and one submission (sized by its own arguments) past it. +pub(crate) const UNITS: usize = COMMANDS * COMMAND_UNITS; + +#[pin_data] +pub(crate) struct Budget { + used: AtomicUsize, + limit: usize, + status: Arc, + closed: AtomicBool, +} + +impl Budget { + pub(crate) fn for_vm(status: &Arc, limit: usize) -> Result> { + Arc::new(Self { + used: AtomicUsize::new(0), + limit, + status: status.clone(), + closed: AtomicBool::new(false), + }, GFP_KERNEL).map_err(Into::into) + } + + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn new() -> Result> { + Self::with_limit(UNITS) + } + + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn with_limit(limit: usize) -> Result> { + Self::for_vm(&Arc::pin_init(VmStatus::new(), GFP_KERNEL)?, limit) + } + + pub(crate) fn close(&self) { + self.closed.store(true, Ordering::Release); + self.status.wake_budget_waiters(); + } + + + /// The queue has used its whole budget: a submission waits ([`Self::wait_for_room`]) before + /// it is taken. + pub(crate) fn full(&self) -> bool { + self.used.load(Ordering::Acquire) >= self.limit + } + + #[cfg(CONFIG_KUNIT = "y")] + pub(crate) fn used(&self) -> usize { + self.used.load(Ordering::Acquire) + } + + /// Takes `units` until the returned charge drops. Never refused: a submission is admitted + /// whole once the queue is below its budget, so it may end up to one submission past it. + pub(crate) fn charge(self: &Arc, units: usize) -> Charge { + self.used.fetch_add(units, Ordering::AcqRel); + Charge { budget: self.clone(), units } + } + + /// Sleeps, interruptibly, until the queue is below its budget. Called without the queue's + /// lock: what frees the budget never takes it. + pub(crate) fn wait_for_room(&self) -> Result { + self.status.wait_for_budget(|| self.full(), || self.closed.load(Ordering::Acquire)) + } +} + +impl crate::queue::Room for Budget { + fn must_wait(&self) -> bool { + self.full() || self.closed.load(Ordering::Acquire) || self.status.client_closed() + } + + fn close(&self) { + Budget::close(self); + } + + fn wait(&self) -> Result { + self.wait_for_room() + } +} + +/// Units of a [`Budget`] held by whatever owns the charged memory. +pub(crate) struct Charge { + budget: Arc, + units: usize, +} + +impl Drop for Charge { + fn drop(&mut self) { + let budget = &self.budget; + let before = budget.used.fetch_sub(self.units, Ordering::AcqRel); + // Only dropping below the budget can let a waiter in. Taking the lock orders this wake-up + // after a waiter's check, so it cannot miss it. + if before >= budget.limit && before - self.units < budget.limit { + budget.status.wake_budget_waiters(); + } + } +} + +#[kernel::macros::kunit_tests(asahi_g17_queue_budget)] +mod tests { + use super::*; + + #[test] + fn charges_fill_the_budget_until_they_drop() { + let budget = Budget::with_limit(10).unwrap(); + let first = budget.charge(4); + let second = budget.charge(6); + assert!(budget.full()); + drop(first); + assert!(!budget.full()); + assert_eq!(budget.used(), 6); + drop(second); + assert_eq!(budget.used(), 0); + // A submission is admitted whole below the budget, so a charge may pass it. + let large = budget.charge(25); + assert!(budget.full()); + drop(large); + assert!(!budget.full()); + } + + #[test] + fn teardown_refuses_a_wait_without_a_charge_return() { + for vm in [false, true] { + let budget = Budget::with_limit(1).unwrap(); + let _external = budget.charge(1); + if vm { budget.status.mark_client_closed(); } else { budget.close(); } + assert_eq!(budget.wait_for_room(), Err(ENOENT)); + } + } + + #[test] + fn a_waiter_wakes_once_a_charge_drops_elsewhere() { + let budget = Budget::with_limit(1).unwrap(); + let charge = budget.charge(1); + assert!(budget.full()); + // Dropped by another task, as the scheduler's free_job work or event work drops a + // packet while the submitter sleeps. + kernel::workqueue::system() + .try_spawn(GFP_KERNEL, move || { + kernel::time::delay::fsleep(kernel::time::Delta::from_millis(20)); + drop(charge); + }) + .unwrap(); + assert_eq!(budget.wait_for_room(), Ok(())); + assert!(!budget.full()); + } +} diff --git a/drivers/gpu/drm/asahi/g17/queue/mod.rs b/drivers/gpu/drm/asahi/g17/queue/mod.rs index 0fa26c3812137..9e745eeb01082 100644 --- a/drivers/gpu/drm/asahi/g17/queue/mod.rs +++ b/drivers/gpu/drm/asahi/g17/queue/mod.rs @@ -45,6 +45,7 @@ fn work_state_split_before( static FENCE_KEY: Pin<&LockClassKey> = kernel::static_lock_class!(); pub(crate) mod admission; +pub(crate) mod budget; mod outstanding; use outstanding::Outstanding; @@ -142,6 +143,8 @@ pub(crate) struct Queue { /// The commands and VM pins of the ioctl being submitted, kept empty between /// ioctls so their room is allocated once ([`Self::prepare_submission`]). scratch: Scratch, + /// What this queue's pending commands may keep allocated. + budget: Arc, /// Persistent parser attachment lists, cleared by count on every submit ioctl /// rather than zeroed on the stack. attachments: [Attachments; ATTACHMENT_KINDS], @@ -192,6 +195,7 @@ impl Queue { )?); let failures = context.status().failures().finished; let usage = Arc::new(crate::usage::Lane::new(usage), GFP_KERNEL)?; + let budget = budget::Budget::for_vm(context.status(), budget::UNITS)?; KBox::try_init( kernel::try_init!(Self { dev: dev.into(), @@ -214,6 +218,7 @@ impl Queue { failures: [FailureRecord::new(), FailureRecord::new()], failure_logs: [FailureLog::new()?, FailureLog::new()?], scratch: Scratch::default(), + budget, attachments <- Attachments::init_array(), _slot: slot, }), @@ -416,6 +421,7 @@ impl Queue { shared_inputs, inputs.iter().filter_map(|sync| sync.fence.as_ref()), |fence| sources.as_ref().is_some_and(|sources| sources.contains_input(fence)), + Some(&self.budget), )?; let input_dependencies = command_inputs.as_ref().map_or(&[][..], |inputs| inputs.dependencies()); @@ -474,6 +480,16 @@ impl Queue { checked_inputs.push(ready.clone(), GFP_KERNEL)?; } } + // Charged until the memory goes: the packet's own state and vectors, its scheduler job's + // dependencies (held until the job runs, so no later than the packet), and the + // timestamp waits its frontier entries keep. Each link carries a unit of its own. + let charge = self.budget.charge( + budget::COMMAND_UNITS + + checked_inputs.len() + + dependencies.len() + + inherited_timestamp_waits.as_ref().map_or(0, |waits| waits.len()), + ); + let publication = publication.map(|publication| publication.with_charges(&self.budget)); // Publish from the ioctl whenever nothing has to wait, at any depth. // The backend falls back to the scheduler behind any backlog or on any // capacity miss, so submission order is preserved. @@ -489,6 +505,7 @@ impl Queue { checked_inputs, command_inputs, producers, + charge, )?; let scheduler = match engine { Engine::Render => &mut self.render, @@ -608,6 +625,10 @@ impl Queue { } impl crate::queue::Queue for Queue { + fn admission(&self) -> Option> { + Some(self.budget.clone()) + } + fn set_compute_timeout(&mut self, requested_ms: u32) -> Result { // The compute scheduler takes the allowance when the first compute command creates it. if self.compute.is_some() { @@ -790,7 +811,7 @@ impl crate::queue::Queue for Queue { Some(&output_fence), ); let shared_inputs = - Inputs::new(outputs.inputs().iter().filter_map(|sync| sync.fence.as_ref()))?; + Inputs::new(outputs.inputs().iter().filter_map(|sync| sync.fence.as_ref()), Some(&self.budget))?; let mut work_states = work_states.into_iter(); for entry in pending.iter_mut() { let guard = guards.next().ok_or(EIO)?; @@ -1368,6 +1389,20 @@ mod tests { drop(r1); } + #[test] + fn a_queue_has_room_until_its_pending_commands_hold_the_budget() { + let budget = budget::Budget::with_limit(4).unwrap(); + assert!(!crate::queue::Room::must_wait(&*budget)); + let pending = budget.charge(3); + assert!(!crate::queue::Room::must_wait(&*budget)); + let more = budget.charge(1); + // Full: the next submission sleeps on the budget without the queue's lock. + assert!(crate::queue::Room::must_wait(&*budget)); + drop(pending); + assert!(!crate::queue::Room::must_wait(&*budget)); + drop(more); + } + #[test] fn transitive_render_chains_publication_without_host_wait() { let none = frontier([]); diff --git a/drivers/gpu/drm/asahi/g17/status.rs b/drivers/gpu/drm/asahi/g17/status.rs index 5c062f8a2c8e8..33b9c15c838a7 100644 --- a/drivers/gpu/drm/asahi/g17/status.rs +++ b/drivers/gpu/drm/asahi/g17/status.rs @@ -23,6 +23,10 @@ pub(crate) struct VmStatus { reported_error: AtomicI32, /// The client's VM handle is gone: no client can see a lost device any more. client_closed: AtomicBool, + #[pin] + budget_wait_lock: Mutex<()>, + #[pin] + budget_wait: kernel::sync::CondVar, /// A queue of this VM went away while its work was still in the GPU, and the wait for that /// work ended. Never cleared. teardown_expired: AtomicBool, @@ -77,6 +81,8 @@ impl VmStatus { error: AtomicI32::new(0), reported_error: AtomicI32::new(0), client_closed: AtomicBool::new(false), + budget_wait_lock <- new_mutex!((), "G17 VM queue budget"), + budget_wait <- kernel::new_condvar!("G17 VM queue budget"), teardown_expired: AtomicBool::new(false), warned: AtomicBool::new(false), recovery_guilty: AtomicBool::new(false), @@ -152,16 +158,33 @@ impl VmStatus { self.client_closed.load(Ordering::Acquire) } + pub(crate) fn wait_for_budget(&self, full: impl Fn() -> bool, closed: impl Fn() -> bool) -> Result { + let mut guard = self.budget_wait_lock.lock(); + loop { + if closed() || self.client_closed() { return Err(ENOENT) } + if self.get() != 0 { return Err(EIO) } + if !full() { return Ok(()) } + if self.budget_wait.wait_interruptible(&mut guard) { return Err(ERESTARTSYS) } + } + } + + pub(crate) fn wake_budget_waiters(&self) { + let _guard = self.budget_wait_lock.lock(); + self.budget_wait.notify_all(); + } + /// Record permanent admission failure and report it to the client. #[track_caller] pub(crate) fn record(&self, error: Error) { self.report_failure(error); - let _ = self.error.compare_exchange( + if self.error.compare_exchange( 0, error.to_errno(), Ordering::SeqCst, Ordering::SeqCst, - ); + ).is_ok() { + self.wake_budget_waiters(); + } } pub(crate) fn reported_error(&self) -> i32 { @@ -275,6 +298,7 @@ impl VmStatus { /// more, even before its VM handle goes (the file drops its queues first). pub(crate) fn mark_client_closed(&self) { self.client_closed.store(true, Ordering::Release); + self.wake_budget_waiters(); } /// The client's VM handle is gone and nobody reads the mirror any more. The diff --git a/drivers/gpu/drm/asahi/g17/sync_input.rs b/drivers/gpu/drm/asahi/g17/sync_input.rs index a63d4267dad60..6a2f7e99e6937 100644 --- a/drivers/gpu/drm/asahi/g17/sync_input.rs +++ b/drivers/gpu/drm/asahi/g17/sync_input.rs @@ -4,6 +4,7 @@ //! because polling a container's status can signal it and run callbacks. use core::mem::MaybeUninit; +use super::queue::budget::Budget; use kernel::{bindings, dma_fence::{Fence, RawDmaFence}, prelude::*}; #[repr(C)] @@ -153,14 +154,17 @@ pub(crate) struct Inputs { /// One fence for all of them, past [`super::job::MERGED_DEPENDENCIES`]: what each command's /// scheduler job waits on instead of every input. merged: Option, + /// One unit of the queue's budget per fence the list holds, given back when the list goes. + _charge: Option, } impl Inputs { /// `None` when there is nothing to wait for. Userspace sets the count, so the list is charged /// to the caller and needs no contiguous pages. - pub(crate) fn new<'a>(inputs: impl IntoIterator) - -> Result>> - { + pub(crate) fn new<'a>( + inputs: impl IntoIterator, + budget: Option<&kernel::sync::Arc>, + ) -> Result>> { let mut fences = KVVec::new(); for fence in inputs { // An input that already signalled without error orders nothing and has no status left @@ -194,7 +198,8 @@ impl Inputs { } else { None }; - Ok(Some(kernel::sync::Arc::new(Self { fences, merged }, GFP_KERNEL_ACCOUNT)?)) + let _charge = budget.map(|budget| budget.charge(fences.len() + usize::from(merged.is_some()))); + Ok(Some(kernel::sync::Arc::new(Self { fences, merged, _charge }, GFP_KERNEL_ACCOUNT)?)) } #[cfg(CONFIG_KUNIT = "y")] @@ -250,6 +255,7 @@ pub(crate) fn command_inputs<'a>( shared: Option<&kernel::sync::Arc>, inputs: impl Iterator + Clone, covered: impl Fn(&Fence) -> bool, + budget: Option<&kernel::sync::Arc>, ) -> Result> { let Some(shared) = shared else { return Ok(None); @@ -258,7 +264,9 @@ pub(crate) fn command_inputs<'a>( return Ok(Some(shared.for_command()?)); } // Rare: the sources take over some inputs. Wait on the others only, in a list of its own. - Inputs::new(inputs.filter(|fence| !covered(fence)))?.map(|own| own.for_command()).transpose() + Inputs::new(inputs.filter(|fence| !covered(fence)), budget)? + .map(|own| own.for_command()) + .transpose() } /// One command's share of its submission's [`Inputs`]. @@ -569,7 +577,7 @@ mod inputs_tests { fn commands_of_one_submission_share_its_inputs() { let contexts = contexts(); let fences = unsignalled(&contexts, 64); - let inputs = Inputs::new(fences.iter()).unwrap().unwrap(); + let inputs = Inputs::new(fences.iter(), None).unwrap().unwrap(); let first = inputs.for_command().unwrap(); let second = inputs.for_command().unwrap(); // Every command still checks every input before publication. @@ -580,11 +588,28 @@ mod inputs_tests { assert!(first.dependencies().len() <= MERGED_DEPENDENCIES); } + #[test] + fn a_submissions_inputs_are_charged_once_until_its_last_command_goes() { + let contexts = contexts(); + let fences = unsignalled(&contexts, 64); + let budget = crate::g17::queue::budget::Budget::new().unwrap(); + let inputs = Inputs::new(fences.iter(), Some(&budget)).unwrap().unwrap(); + // 64 fences and the merged one, however many commands share them. + assert_eq!(budget.used(), 65); + let first = inputs.for_command().unwrap(); + let second = inputs.for_command().unwrap(); + assert_eq!(budget.used(), 65); + drop((inputs, first)); + assert_eq!(budget.used(), 65); + drop(second); + assert_eq!(budget.used(), 0); + } + #[test] fn a_few_inputs_stay_separate_dependencies() { let contexts = contexts(); let fences = unsignalled(&contexts, MERGED_DEPENDENCIES); - let inputs = Inputs::new(fences.iter()).unwrap().unwrap(); + let inputs = Inputs::new(fences.iter(), None).unwrap().unwrap(); let command = inputs.for_command().unwrap(); assert_eq!(command.dependencies().len(), MERGED_DEPENDENCIES); for (dependency, fence) in command.dependencies().iter().zip(fences.iter()) { @@ -596,7 +621,7 @@ mod inputs_tests { fn a_repeated_input_is_kept_once() { let contexts = contexts(); let fence = Fence::from_fence(&independent(&contexts).unwrap()); - let inputs = Inputs::new(core::iter::repeat(&fence).take(100)).unwrap().unwrap(); + let inputs = Inputs::new(core::iter::repeat(&fence).take(100), None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 1); assert_eq!(inputs.fences()[0].raw(), fence.raw()); } @@ -607,7 +632,7 @@ mod inputs_tests { let earlier = Fence::from_fence(&contexts.new_fence(0, CompletionFence).unwrap()); let later = Fence::from_fence(&contexts.new_fence(0, CompletionFence).unwrap()); let other = Fence::from_fence(&independent(&contexts).unwrap()); - let inputs = Inputs::new([&later, &other, &earlier]).unwrap().unwrap(); + let inputs = Inputs::new([&later, &other, &earlier], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 2); assert!(inputs.fences().iter().any(|fence| fence.raw() == later.raw())); assert!(inputs.fences().iter().any(|fence| fence.raw() == other.raw())); @@ -618,7 +643,7 @@ mod inputs_tests { let contexts = contexts(); let fences = unsignalled(&contexts, 2); let array = merge(&fences).unwrap(); - let inputs = Inputs::new([&array, &fences[0], &fences[1]]).unwrap().unwrap(); + let inputs = Inputs::new([&array, &fences[0], &fences[1]], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 2); for fence in fences.iter() { assert!(inputs.fences().iter().any(|kept| kept.raw() == fence.raw())); @@ -634,15 +659,15 @@ mod inputs_tests { heads.push(container.clone(), GFP_KERNEL).unwrap(); let sources = Sources::new(heads, KVec::new(), KVec::new(), KVec::new()).unwrap(); // The submission keeps the container's base fences, which the sources do not list. - let inputs = Inputs::new(core::iter::once(&container)).unwrap().unwrap(); + let inputs = Inputs::new(core::iter::once(&container), None).unwrap().unwrap(); assert!(inputs.fences().iter().all(|fence| !sources.contains_input(fence))); // Coverage is decided on the inputs as passed, so the command still waits on none. let covered = |fence: &Fence| sources.contains_input(fence); - assert!(command_inputs(Some(&inputs), core::iter::once(&container), covered).unwrap().is_none()); + assert!(command_inputs(Some(&inputs), core::iter::once(&container), covered, None).unwrap().is_none()); // With an input the sources leave, the command waits on that one only, in its own list. let other = Fence::from_fence(&independent(&contexts).unwrap()); - let both = Inputs::new([&container, &other]).unwrap().unwrap(); - let own = command_inputs(Some(&both), [&container, &other].into_iter(), covered) + let both = Inputs::new([&container, &other], None).unwrap().unwrap(); + let own = command_inputs(Some(&both), [&container, &other].into_iter(), covered, None) .unwrap() .unwrap(); assert!(!own.shares_with(&both.for_command().unwrap())); @@ -659,7 +684,7 @@ mod inputs_tests { failed.set_error(EIO); failed.signal(); let failed = Fence::from_fence(&failed); - let inputs = Inputs::new([&later, &failed]).unwrap().unwrap(); + let inputs = Inputs::new([&later, &failed], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 2); } @@ -669,13 +694,13 @@ mod inputs_tests { let done = independent(&contexts).unwrap(); done.signal(); let done = Fence::from_fence(&done); - assert!(Inputs::new(core::iter::once(&done)).unwrap().is_none()); + assert!(Inputs::new(core::iter::once(&done), None).unwrap().is_none()); let failed = independent(&contexts).unwrap(); failed.set_error(EIO); failed.signal(); let failed = Fence::from_fence(&failed); // A failed input keeps its status for the command to consume. - let inputs = Inputs::new([&done, &failed]).unwrap().unwrap(); + let inputs = Inputs::new([&done, &failed], None).unwrap().unwrap(); assert_eq!(inputs.fences().len(), 1); assert_eq!(inputs.fences()[0].raw(), failed.raw()); } diff --git a/drivers/gpu/drm/asahi/queue/mod.rs b/drivers/gpu/drm/asahi/queue/mod.rs index 3aff30fe273e4..91080d986c6d1 100644 --- a/drivers/gpu/drm/asahi/queue/mod.rs +++ b/drivers/gpu/drm/asahi/queue/mod.rs @@ -170,6 +170,14 @@ struct TvbUser { seen: TvbUse, } +/// What a submission to a full queue sleeps on until the queue has room ([`Queue::admission`]). +pub(crate) trait Room: Send + Sync { + fn must_wait(&self) -> bool; + fn close(&self); + /// Sleeps, interruptibly, until the queue has room: ERESTARTSYS on a signal. + fn wait(&self) -> Result; +} + /// Trait implemented by all versioned queues. pub(crate) trait Queue: Send + Sync { /// Sets the watchdog allowance of the queue's compute commands to `requested_ms` @@ -203,6 +211,11 @@ pub(crate) trait Queue: Send + Sync { objects: Pin<&xarray::XArray>>, ) -> Result; + /// A handle shared by submitters and queue destruction. Unbounded queues do not need one. + fn admission(&self) -> Option> { + None + } + /// Waits for the work submitted so far to finish, before the mappings of a closing /// client go. Queues whose VMs keep user mappings for accepted jobs need not wait. fn drain(&mut self) {} diff --git a/include/uapi/drm/asahi_drm.h b/include/uapi/drm/asahi_drm.h index ec76f521bfd21..b9e09b78240e4 100644 --- a/include/uapi/drm/asahi_drm.h +++ b/include/uapi/drm/asahi_drm.h @@ -714,6 +714,9 @@ struct drm_asahi_vm_status { * and execution context, returning an allocation error if resources run out. * @max_in_flight_per_queue: Hardware scheduler credits per queue. Software * may enqueue additional jobs, which wait behind preceding work/dependencies. + * SUBMIT sleeps, interruptibly, while the queue's pending jobs already hold + * the state the kernel allows one queue (about 2048 jobs), and takes the + * submission once earlier jobs have finished. * @flags: Reserved, zero. * @pad: Reserved, zero. * diff --git a/tools/asahi/g15-input-error-tests.py b/tools/asahi/g15-input-error-tests.py index 0aa557e8dae80..008d4c688c151 100644 --- a/tools/asahi/g15-input-error-tests.py +++ b/tools/asahi/g15-input-error-tests.py @@ -46,6 +46,8 @@ def extract(text, marker): struct VmStatus{error:AtomicI32,reported_error:AtomicI32,client_closed:AtomicBool,teardown_expired:AtomicBool,warned:AtomicBool,recovery_guilty:AtomicBool,tgid:i32,comm:[u8;16],mirror:Mutex>} impl VmStatus { fn new(word:*mut i32)->Self{Self{error:AtomicI32::new(0),reported_error:AtomicI32::new(0),client_closed:AtomicBool::new(false),teardown_expired:AtomicBool::new(false),warned:AtomicBool::new(false),recovery_guilty:AtomicBool::new(false),tgid:1,comm:*b"host-test\0\0\0\0\0\0\0",mirror:Mutex(StdMutex::new(Some(Mirror{word})))}} + // This fixture has no submitters waiting for queue budget. + fn wake_budget_waiters(&self) {} __STATUS__ } mod g17 {use super::*;__POLICY__} diff --git a/tools/asahi/g17-command-inputs-tests.py b/tools/asahi/g17-command-inputs-tests.py index df6d364cb69be..a2f0a696039f4 100755 --- a/tools/asahi/g17-command-inputs-tests.py +++ b/tools/asahi/g17-command-inputs-tests.py @@ -66,13 +66,19 @@ def build_harness(mutation=None): status: i32, }} +/// The queue budget the lists are charged to; not modelled. +struct Budget; + /// A submission's input fences not yet signalled without error. struct Inputs {{ fences: Vec, }} impl Inputs {{ - fn new<'a>(inputs: impl IntoIterator) -> Result>> {{ + fn new<'a>( + inputs: impl IntoIterator, + _budget: Option<&kernel::sync::Arc>, + ) -> Result>> {{ let fences: Vec = inputs.into_iter().filter(|fence| fence.status <= 0).copied().collect(); Ok((!fences.is_empty()).then(|| kernel::sync::Arc::new(Self {{ fences }}))) }} @@ -94,25 +100,25 @@ def build_harness(mutation=None): let b = Fence {{ id: 2, status: 0 }}; let done = Fence {{ id: 3, status: 1 }}; let all = [a, b, done]; - let shared = Inputs::new(all.iter()).unwrap(); + let shared = Inputs::new(all.iter(), None).unwrap(); // 1. No source covers an input: the command shares the submission's list. - let none = command_inputs(shared.as_ref(), all.iter(), |_| false).unwrap(); + let none = command_inputs(shared.as_ref(), all.iter(), |_| false, None).unwrap(); assert!(std::sync::Arc::ptr_eq(&none.as_ref().unwrap().0, shared.as_ref().unwrap()), "an uncovered command must share the submission's list"); assert_eq!(ids(&none), vec![1, 2]); // 2. Sources cover a: the command waits on b only, in a list of its own. - let part = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id == 1).unwrap(); + let part = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id == 1, None).unwrap(); assert_eq!(ids(&part), vec![2], "a partly covered command must wait on its uncovered inputs only"); assert!(!std::sync::Arc::ptr_eq(&part.as_ref().unwrap().0, shared.as_ref().unwrap())); // 3. Sources cover a and b; done has signalled: nothing to wait for. - let covered = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id != 3).unwrap(); + let covered = command_inputs(shared.as_ref(), all.iter(), |fence| fence.id != 3, None).unwrap(); assert!(covered.is_none(), "a command its sources cover must wait on no input"); // 4. Nothing unsignalled in the submission: nothing to wait for. - assert!(command_inputs(None, [done].iter(), |_| false).unwrap().is_none()); + assert!(command_inputs(None, [done].iter(), |_| false, None).unwrap().is_none()); println!("PASS g17 command inputs"); }}