diff --git a/drivers/gpu/drm/asahi/g17/channel.rs b/drivers/gpu/drm/asahi/g17/channel.rs index a97c1e18acfa8..6541f32d02bda 100644 --- a/drivers/gpu/drm/asahi/g17/channel.rs +++ b/drivers/gpu/drm/asahi/g17/channel.rs @@ -24,6 +24,10 @@ const _: () = assert!(super::telemetry::STATISTICS_RING_RECORDS == STATISTICS_SL static CONTROL_PUBLISHED: AtomicU64 = AtomicU64::new(0); /// The largest count of published records the firmware is known to have consumed. static CONTROL_CONSUMED: AtomicU64 = AtomicU64::new(0); +/// The latest scheduler release, as the count of records published up to it. +static RELEASE_PUBLISHED: AtomicU64 = AtomicU64::new(0); +/// The latest scheduler release the firmware is known to have consumed, counted the same way. +static RELEASE_CONSUMED: AtomicU64 = AtomicU64::new(0); /// Firmware progress fences for host identities and storage that the firmware may still /// name after their owner let go of them. @@ -49,6 +53,20 @@ pub(crate) fn control_witnessed() -> u64 { CONTROL_CONSUMED.load(Ordering::Acquire) } +/// The latest scheduler release the firmware is known to have consumed, as a record count +/// like [`control_published`]. The release carries what the older firmware's DestroyContext +/// does (a context page and its bytes 0, 1, 4 and 0x23, here 0x26), and that command also +/// flushes the firmware data cache (`flush_fw_cache` in `gpu.rs`). Once this exceeds the +/// fence of returned firmware-cached storage, a flush ran after the firmware last named it. +pub(crate) fn release_witnessed() -> u64 { + RELEASE_CONSUMED.load(Ordering::Acquire) +} + +/// The record just published is a scheduler release. Call under the device mutex. +pub(crate) fn published_release() { + RELEASE_PUBLISHED.store(CONTROL_PUBLISHED.load(Ordering::Acquire), Ordering::Release); +} + /// Records how far the firmware consumed the control ring. Call under the device mutex, /// which also serializes publication, with cursors read after any publication by the caller. /// A restarted firmware has nothing pending, so everything published so far counts. @@ -59,6 +77,10 @@ pub(crate) fn observe_control(consumer: u32, producer: u32) { let pending = u64::from(producer.wrapping_sub(consumer) & (DEVICE_CONTROL_SLOTS - 1)); let consumed = CONTROL_PUBLISHED.load(Ordering::Acquire).saturating_sub(pending); CONTROL_CONSUMED.fetch_max(consumed, Ordering::AcqRel); + let release = RELEASE_PUBLISHED.load(Ordering::Acquire); + if release <= consumed { + RELEASE_CONSUMED.fetch_max(release, Ordering::AcqRel); + } } /// Firmware rings whose contents do not affect host scheduling. diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index cebeb73c78d9a..534dd580453ea 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -850,10 +850,12 @@ impl WorkStateLease { /// The render channel of `pair` for a publication. When both channels are bound to other /// pairs, the least recently used one whose every publication `retired(qids, ordinal)` /// moves to `pair`; otherwise [`RENDER_CHANNEL_PENDING`]: the caller waits for retirement - /// instead of failing the client. + /// instead of failing the client. `required`: the channel the pair's queue records already + /// carry, the only one it may take. pub(crate) fn render_channel( &self, pair: u8, + required: Option, retired: impl Fn([u8; 2], u64) -> bool, ) -> Result { let (index, previous) = self @@ -861,7 +863,7 @@ impl WorkStateLease { .work .lock() .render - .bind(pair, retired) + .bind(pair, required, retired) .ok_or(RENDER_CHANNEL_PENDING)?; if let Some(previous) = previous { static REBINDS: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0); diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index 5af933d0584da..6f9027bbaa85d 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -220,6 +220,11 @@ pub(super) struct RenderSlots { used: [u64; 2], epoch: u64, } +/// Whether channel `index` may serve a pair whose queue records carry `required`. +fn allows(required: Option, index: usize) -> bool { + required.is_none_or(|slot| slot as usize == index) +} + impl RenderSlots { pub(super) const fn new() -> Self { Self { @@ -231,26 +236,29 @@ impl RenderSlots { epoch: 0, } } - fn get(&mut self, pair: u8) -> Option { + fn get(&mut self, pair: u8, required: Option) -> Option { if let Some(index) = self.pairs.iter().position(|value| *value == Some(pair)) { return Some(index as u32); } - let index = self.pairs.iter().position(Option::is_none)?; + let index = (0..2).find(|&index| allows(required, index) && self.pairs[index].is_none())?; self.pairs[index] = Some(pair); Some(index as u32) } /// The channel of `pair`, rebinding the least recently used channel whose publications - /// have all retired (`retired(qids, ordinal)`) when both are bound to other pairs. `None`: - /// no channel can move yet. + /// have all retired (`retired(qids, ordinal)`) when both are bound to other pairs. With + /// `required`, the channel the pair's queue records already carry, only that channel may + /// bind to it. `None`: no channel can move yet. pub(super) fn bind( &mut self, pair: u8, + required: Option, retired: impl Fn([u8; 2], u64) -> bool, ) -> Option<(u32, Option)> { - if let Some(index) = self.get(pair) { + if let Some(index) = self.get(pair, required) { return Some((index, None)); } let index = (0..2) + .filter(|&index| allows(required, index)) .filter(|index| self.last[*index].is_none_or(|(qids, ordinal)| retired(qids, ordinal))) .min_by_key(|index| self.used[*index])?; let previous = self.pairs[index]; @@ -425,6 +433,27 @@ mod tests { } } + #[test] + fn a_pair_takes_only_the_channel_its_records_carry() { + let retired = |_: [u8; 2], _: u64| true; + let mut slots = RenderSlots::new(); + // A pair whose records carry channel 1 takes it although channel 0 is free. + assert_eq!(slots.bind(5, Some(1), retired), Some((1, None))); + assert_eq!(slots.bind(6, None, retired), Some((0, None))); + assert!(slots.published(5, [10, 11], 1)); + assert!(slots.published(6, [12, 13], 2)); + // A third pair takes the least recently used retired channel. + assert_eq!(slots.bind(7, None, retired), Some((1, Some(5)))); + assert!(slots.published(7, [14, 15], 3)); + // Pair 5's records carry channel 1: while pair 7's publications run it waits, although + // channel 0 has retired, and it takes channel 1 once they retire. + let running = |qids: [u8; 2], _: u64| qids != [14, 15]; + assert_eq!(slots.bind(5, Some(1), running), None); + assert_eq!(slots.bind(5, Some(1), retired), Some((1, Some(7)))); + // Unconstrained, the same move takes the least recently used retired channel. + assert_eq!(slots.bind(7, None, running), Some((0, Some(6)))); + } + #[test] fn releases_return_nodes_to_their_engine() { let states = WorkStates::new(); diff --git a/drivers/gpu/drm/asahi/g17/fw/queue.rs b/drivers/gpu/drm/asahi/g17/fw/queue.rs index 3de7282c2c020..44073e2e63fda 100644 --- a/drivers/gpu/drm/asahi/g17/fw/queue.rs +++ b/drivers/gpu/drm/asahi/g17/fw/queue.rs @@ -267,8 +267,10 @@ pub(crate) struct QueueRecordArgs { /// Description of one hardware queue, named by its work-ring slots. /// /// The host writes it whole at queue creation and changes the owner fields of -/// an idle queue with [`QueueRecord::set_compute_owner`] or, for render -/// queues, field by field (`render/memory.rs`). +/// an idle compute queue with [`QueueRecord::set_compute_owner`]. Render +/// queue records are never retargeted: another owner gets new records, and +/// G17P writes the work slot (`unk_38`) only before the records' first kick +/// (`render/memory.rs`). #[repr(C, packed)] #[derive(Copy, Clone, Debug)] pub(crate) struct QueueRecord { @@ -327,6 +329,23 @@ impl QueueRecord { } } + /// Whether the record names this owner with this profile. + pub(crate) fn names_owner( + &self, + job_list_va: u64, + scheduler_va: u64, + owner_pid: u32, + policy: Policy, + ) -> bool { + let (job_list, scheduler, pid, priority, current) = + (self.job_list_va, self.scheduler_va, self.owner_pid, self.priority, self.policy); + job_list == job_list_va + && scheduler == scheduler_va + && pid == owner_pid + && priority == [u32::from(policy.priority()); 2] + && current == u32::from(policy.policy()) + } + /// Hands an idle compute queue to a new owner. /// /// Replaces the job head, process identity and scheduler page, and clears `unk_38`. diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index af6fe96731158..33e1979220c56 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -631,6 +631,15 @@ struct Retained { /// Firmware progress after which the previous owner's references are gone /// (see [`super::channel::control_fence`]). fence: u64, + /// Cached queue records: reused only once a scheduler release published after `fence` + /// is consumed (see [`super::channel::release_witnessed`]). + flush: bool, +} + +impl Retained { + fn ready(&self, witnessed: u64, released: u64) -> bool { + if self.flush { released > self.fence } else { self.fence <= witnessed } + } } struct PoolInner { @@ -806,6 +815,7 @@ impl Pool { let family_index = family as usize; let begin = family_index * POOL_SLOTS; let witnessed = super::channel::control_witnessed(); + let released = super::channel::release_witnessed(); self.reap_deferred(witnessed); // On the A18 Pro a cached work state carries a ReturnMark, allocated before an entry is // taken so that a failure loses no returned object, and is never reused before its fence. @@ -830,7 +840,7 @@ impl Pool { }) else { continue; }; - let ready = entry.fence <= witnessed; + let ready = entry.ready(witnessed, released); if oldest.is_none_or(|(_, order, best_ready)| { (ready && !best_ready) || (ready == best_ready && entry.order < order) }) { @@ -940,6 +950,10 @@ impl Pool { let begin = family * POOL_SLOTS; inner.returns += 1; let order = inner.returns; + // The firmware writes cached queue records, and meeting their fence does not show that + // it no longer holds their lines. A release published after the fence does: it flushes + // the firmware data cache. + let flush = lease.family == Family::QueueState && lease.prefix != 0; let fence = match lease.family { // On the A18 Pro a work state's owner records how far its address reached the // firmware: one never named needs no fence, and one whose owner's release was @@ -967,6 +981,7 @@ impl Pool { poisoned: lease.poisoned, order, fence, + flush, }); return; } @@ -1137,18 +1152,20 @@ impl Pool { pub(crate) fn write_capacity(&self, f: &mut kernel::fmt::Formatter<'_>) -> kernel::fmt::Result { let inner = self.inner.lock(); let witnessed = super::channel::control_witnessed(); + let released = super::channel::release_witnessed(); + let waiting = |entry: &&Retained| !entry.ready(witnessed, released); for family in 0..POOL_FAMILIES { let entries = &inner.returned[family * POOL_SLOTS..(family + 1) * POOL_SLOTS]; writeln!(f, concat!("cached_objects_{} used={} total={} returned={} poisoned={} ", "waiting={} overruns={} uncached={}"), family, inner.reserved[family], POOL_SLOTS, entries.iter().flatten().count(), entries.iter().flatten().filter(|entry| entry.poisoned).count(), - entries.iter().flatten().filter(|entry| entry.fence > witnessed).count(), + entries.iter().flatten().filter(waiting).count(), inner.fence_overruns[family], inner.uncached[family])?; } writeln!(f, "cached_object_bytes used={} total={}", inner.bytes, POOL_BYTES)?; writeln!(f, "cached_objects_fenced waiting={} overruns={}", - inner.returned.iter().flatten().filter(|entry| entry.fence > witnessed).count(), + inner.returned.iter().flatten().filter(waiting).count(), inner.fence_overruns.iter().sum::())?; writeln!(f, "workstate_returns unseen={} released={} strict={}", inner.work_returns[RETURN_UNSEEN], inner.work_returns[RETURN_RELEASED], diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index 5d63169e007a9..162dd7ffe8680 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -881,8 +881,10 @@ impl Pair { let parents = self.kicks.each_ref().map(kick::Queue::parent); let work = packet.completion.work_state()?; // A channel moves to this pair only after every publication made through it is - // visible on both of its rings (the stamps cover ordinal + 1). - let work_slot = work.render_channel(self.slot, |old, published| { + // visible on both of its rings (the stamps cover ordinal + 1). Once the G17P queue + // records carry a work slot, only that channel serves this graph. + let required = self.memory.graph.work_slot; + let work_slot = work.render_channel(self.slot, required, |old, published| { host.stamps(old).is_ok_and(|stamps| { stamps.into_iter().all(|stamp| retirement::stamp_covers(stamp, published)) }) @@ -3429,14 +3431,10 @@ impl Pair { return Err(EBUSY); } alloc.uat.vm_context_mask(context.vm())?; - // On M5 only the same logical context (a pool rebind) keeps the graph: - // any other context gets its own graph and queue records, and a live - // queue record is never retargeted. - let keep_graph = if self.memory.graph.is_m5() { - Arc::ptr_eq(self.context(), &context) - } else { - Arc::ptr_eq(self.context().status(), context.status()) - }; + // Only the same logical context (a pool rebind) keeps the graph: any + // other context, even of the same VM, gets its own graph and queue + // records, so a queue record is never retargeted in place. + let keep_graph = Arc::ptr_eq(self.context(), &context); let (memory, aliases, kicks) = if keep_graph { if metrics.is_some() || buffer_id.is_some() || pm_generation.is_some() { return Err(EINVAL); @@ -3515,11 +3513,11 @@ impl Pair { let foreign = binding.memory.is_some(); let same_context = Arc::ptr_eq(self.context(), &binding.context); if let Some(memory) = binding.memory.as_mut() { - // A VM holds one graph's pool mappings per slot. On M5 a new - // context of the same VM gets its own graph: move the drained - // outgoing graph's mappings out first, and back if the install fails. + // A VM holds one graph's pool mappings per slot. A new context of + // the same VM gets its own graph: move the drained outgoing graph's + // mappings out first, and back if the install fails. let same_vm = Arc::ptr_eq(self.context().status(), binding.context.status()); - let moved = if self.memory.graph.is_m5() && same_vm { + let moved = if same_vm { self.memory.take_pool_mappings() } else { None @@ -3551,11 +3549,11 @@ impl Pair { } } } - } else { - // The same logical context keeps its M5 queue records: their host - // words already name it, and a rewrite would store firmware-owned - // words back while the previous kick may still execute. - self.memory.set_owner(self.qids(), &binding.context, !same_context)?; + } else if !self.memory.names_owner(self.qids(), &binding.context)? { + // The same logical context keeps its queue records, which already + // name it. They are never rewritten: a store could revert, or be + // missed by, a firmware-cached line of a queue that ran before. + return Err(EINVAL); } let wait_for_pool_release = self.memory.graph.is_m5() && same_context diff --git a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs index ee973609ad3d3..6d793bccd375a 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render/memory.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render/memory.rs @@ -39,9 +39,12 @@ const M5_USAGE_PAIR_BYTES: usize = 2 * M5_USAGE_BYTES; /// in its slot ([`crate::g17::fw::Variant::lead_commands`]). pub(super) const LEAD: usize = 0xc0; const DEPTH: usize = queues::RENDER_DEPTH as usize; -/// Offsets of the priority pair and the policy word in a queue record. -const PRIORITY: usize = core::mem::offset_of!(queue::QueueRecord, priority); -const POLICY: usize = core::mem::offset_of!(queue::QueueRecord, policy); +/// The G17P queue records at the start of a queue-state object, one per QID, in whole pages. +const RECORD_BYTES: usize = ((fw::kick::QID_MAX as usize + 1) * size_of::()) + .next_multiple_of(mmu::UAT_PGSZ); +static_assert!(RECORD_BYTES <= POINTERS[0]); +/// Offset of the work slot in a G17P queue record. +const WORK_SLOT: usize = core::mem::offset_of!(queue::QueueRecord, unk_38); struct Aliases { client: mmu::KernelMapping, @@ -104,6 +107,9 @@ pub(super) struct Graph { pub(super) owners: [Option; RECORDS], /// Host words of the pointer blocks in this firmware build. pub(super) pointers: fw::variant::PointerLayout, + /// The work slot both G17P queue records carry, once written for the graph's first + /// publication. It never changes after that (see `Memory::bind_work_slot`). + pub(super) work_slot: Option, m5: bool, } impl Graph { @@ -145,14 +151,20 @@ impl Graph { context.vm(), TA_BYTES..TA_BYTES + FRAGMENT_BYTES, )?) }; - // Both firmware and host write queue records (in-place retargeting and - // work-slot binding on G17P, and zeroing on pool reuse everywhere). Keep - // the whole queue-state object uncached while retaining it in the pool. + // Firmware-cached G17 lines are not coherent with host stores and cannot be flushed, so + // the host never stores to a cached line the firmware may hold. On G17P the queue + // records are cached: the host writes each record below, and its work slot before the + // graph's first kick (`Memory::bind_work_slot`), never after a kick named it; another + // context gets its own graph rather than a retargeted one. The firmware's copy of every + // host word is then the value in memory. The pool reuses cached queue records only after + // a scheduler release published after their return was consumed, which flushes the + // firmware data cache. The pointer blocks, job list and item rings stay uncached, as + // does the whole object on M5. let mut queues = pool.allocate( alloc, Family::QueueState, GRAPH_SIZE, - 0, + if m5 { 0 } else { RECORD_BYTES }, prot, CpuMap::WriteCombined, )?; @@ -203,6 +215,7 @@ impl Graph { support, owners: [None; RECORDS], pointers, + work_slot: None, m5, }) } @@ -975,6 +988,10 @@ impl Memory { } impl Memory { + /// Binds `ordinal`'s commands to work slot `slot`. On G17P both queue records carry the slot + /// as well. They are firmware-cached, so it is written only for the graph's first + /// publication, before any kick names them; every later publication must use the same slot, + /// which the context's render channel keeps for this pair ([`Graph::work_slot`]). pub(super) fn bind_work_slot(&mut self, ordinal: u64, qids: [u8; 2], slot: u32) -> Result { if slot >= 4 || !self.owns(ordinal) { return Err(EINVAL); @@ -982,14 +999,19 @@ impl Memory { if self.graph.m5 { return fw::m5::render_assembly::bind_work_slot(self.graph.m5_storage(ordinal)?, slot); } - let queues = [ - self.graph - .queues - .word(usize::from(qids[1]) * size_of::() + 0x38)?, - self.graph - .queues - .word(usize::from(qids[0]) * size_of::() + 0x38)?, - ]; + match self.graph.work_slot { + Some(bound) if bound != slot => return Err(EINVAL), + Some(_) => {} + None => { + for qid in [qids[1], qids[0]] { + self.graph + .queues + .word(self.graph.queue_offset(qid) + WORK_SLOT)? + .store(slot, Ordering::Relaxed); + } + self.graph.work_slot = Some(slot); + } + } let ta = self .graph .descriptors @@ -1000,9 +1022,6 @@ impl Memory { .descriptors .pointer(self.graph.offset(1, ordinal), size_of::())? .cast::(); - for word in queues { - word.store(slot, Ordering::Relaxed); - } // SAFETY: The generation owns these prepared, unpublished POD views. // Packed fields are assigned by value without an unaligned reference. unsafe { @@ -1013,88 +1032,27 @@ impl Memory { Ok(()) } - /// Retargets both retired queue records to `context`. A context of another - /// scheduling profile also replaces the priority and policy words, after - /// the owner fields; the same profile leaves them untouched. - /// `rewrite`: store the M5 records even when their host-owned words - /// already name `context`; without it that no-op read-modify-write, which - /// would also store back firmware-owned words of a possibly running queue, - /// is skipped. G17P always retargets. - pub(super) fn set_owner(&self, qids: [u8; 2], context: &Context, rewrite: bool) -> Result { - if self.graph.m5 { - let records = qids.map(|qid| self.graph.queues.pointer(self.graph.queue_offset(qid), - size_of::())); - let [first, second] = records; - let pointers = [first?, second?].map(|p| p.cast::()); - // SAFETY: Both complete records are in bounds. The caller owns - // retired queues exclusively; build both updates before storing. - unsafe { - let mut values = pointers.map(|p| p.read_unaligned()); - if !rewrite { - let mut named = true; - for value in &values { - named &= value.names_owner(context.work_head_va(), context.scheduler_va(), - context.owner_pid(), context.policy())?; - } - if named { - return Ok(()); - } - } - for value in &mut values { - value.set_compute_owner(context.work_head_va(), context.scheduler_va(), - context.owner_pid(), context.policy())?; - } - for (pointer, value) in pointers.into_iter().zip(values) { - pointer.write_unaligned(value); - } - } - core::sync::atomic::fence(Ordering::Release); - return Ok(()); - } - let offsets = qids.map(|qid| usize::from(qid) * size_of::()); - let base = self.graph.queues.pointer(0, GRAPH_SIZE)?; - // Check every field before the first update, retaining the required - // job-head pair, PID pair, then packed scheduler-pointer pair order. - for at in offsets { - self.graph.queues.pointer(at + 0x10, 8)?; - self.graph.queues.pointer(at + 0x48, 4)?; - self.graph.queues.pointer(at + 0x9c, 8)?; - self.graph.queues.pointer(at + PRIORITY, 8)?; - self.graph.queues.pointer(at + POLICY, 4)?; - } - let policy = context.policy(); - // SAFETY: Both queues are retired before retargeting. Complete byte - // views were checked above; packed scheduler words use unaligned stores. - unsafe { - for at in offsets { - base.add(at + 0x10) - .cast::() - .write_unaligned(context.work_head_va()); - } - for at in offsets { - base.add(at + 0x48) - .cast::() - .write_unaligned(context.owner_pid()); - } - for at in offsets { - base.add(at + 0x9c) - .cast::() - .write_unaligned(context.scheduler_va()); - } - for at in offsets { - let words = base.add(at + PRIORITY).cast::<[u32; 2]>(); - let priority = [u32::from(policy.priority()); 2]; - if words.read_unaligned() != priority { - words.write_unaligned(priority); - } - let word = base.add(at + POLICY).cast::(); - if word.read_unaligned() != u32::from(policy.policy()) { - word.write_unaligned(u32::from(policy.policy())); - } - } + /// Whether both queue records name `context`. A graph is kept only for the context its + /// records were written for, so a rebind never retargets them in place. + pub(super) fn names_owner(&self, qids: [u8; 2], context: &Context) -> Result { + let (job_list, scheduler, pid, policy) = (context.work_head_va(), context.scheduler_va(), + context.owner_pid(), context.policy()); + let mut named = true; + for qid in qids { + let at = self.graph.queue_offset(qid); + named &= if self.graph.m5 { + let record = self.graph.queues.pointer(at, size_of::())?; + // SAFETY: The complete record is in bounds; it is copied out by value. + unsafe { record.cast::().read_unaligned() } + .names_owner(job_list, scheduler, pid, policy)? + } else { + let record = self.graph.queues.pointer(at, size_of::())?; + // SAFETY: As above. + unsafe { record.cast::().read_unaligned() } + .names_owner(job_list, scheduler, pid, policy) + }; } - core::sync::atomic::fence(Ordering::Release); - Ok(()) + Ok(named) } } diff --git a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs index 1c57ed12adcef..14eb8c8e4a990 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/render/prepare.rs @@ -336,14 +336,10 @@ impl super::super::Backend { if firmware.queues.teardown.releasing(pair.context()) { return Err(EBUSY); } - // On M5 a different logical context, even of the same VM, - // gets its own graph; only a pool rebind of the same - // context keeps the graph and its queue records. - let foreign = if resources.uat.is_m5() { - !Arc::ptr_eq(pair.context(), &self.context) - } else { - !Arc::ptr_eq(pair.context().status(), self.context.status()) - }; + // A different logical context, even of the same VM, gets + // its own graph; only a pool rebind of the same context + // keeps the graph and its queue records (`Pair::prepare_bind`). + let foreign = !Arc::ptr_eq(pair.context(), &self.context); if foreign { firmware .queues diff --git a/drivers/gpu/drm/asahi/g17/runtime/teardown.rs b/drivers/gpu/drm/asahi/g17/runtime/teardown.rs index 2127f7dfc977c..081a698cec6e2 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/teardown.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/teardown.rs @@ -128,10 +128,12 @@ impl Host for Service<'_> { self.render.control_backpressured() } fn publish_release(&mut self, page_va: u64, id: [u8; 4]) -> Result { - Rings::publish_control( + let next = Rings::publish_control( self.init, &ControlRecord::SchedulerStateRelease(self.init.scheduler_release(page_va, id)), - ) + )?; + crate::g17::channel::published_release(); + Ok(next) } fn notify(&mut self) -> Result { self.primary.notify(MSG_CONTROL_NOTIFY) diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 681aaac2860e9..753dc03d7ea08 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -25,10 +25,16 @@ BASE's reuse limited to met fences. - Source rules: every accessor that hands the address to the firmware marks it, and only the release path of `retain_linked_work` marks it released. -- Cache policy (linux#3170 and its G17P follow-up): records the host rewrites - in place (render queue records, the compute graph, M5 scheduler pages) stay - uncached on every G17; work nodes and compute descriptors are uncached on M5 - and keep their firmware-cached prefix on G17P. +- Cache policy (linux#3170 and its G17P follow-ups): records the host rewrites + in place (the compute graph, M5 scheduler pages) stay uncached on every G17; + work nodes and compute descriptors are uncached on M5 and keep their + firmware-cached prefix on G17P. Render queue records are uncached on M5 and + firmware-cached on G17P, where the host never stores to one after a kick + named it: another context gets a new graph instead of a retargeted one, the + work slot is written only before the graph's first kick, and the context's + render channel keeps that slot. A returned cached queue state is reused only + after a scheduler release published after its fence was consumed, under + either release policy, so churn never exhausts the family. `--mutation` applies one known-bad change to the compiled copy; the run must then fail. @@ -78,8 +84,26 @@ 'm5-cached-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', 'UAT_PGSZ'), # M5 compute descriptors are firmware-cached again. 'm5-cached-descriptors': ('policy-compute', 'if alloc.uat.is_m5() { 0 } else { size }', 'size'), - # Render queue records, which the host retargets in place, are firmware-cached again. - 'cached-queue-records': ('policy-memory', 'GRAPH_SIZE,\n 0,\n', 'GRAPH_SIZE,\n 0x8000,\n'), + # M5 render queue records are firmware-cached. + 'm5-cached-queue-records': ('policy-memory', 'if m5 { 0 } else { RECORD_BYTES }', 'RECORD_BYTES'), + # G17P render queue records lose their cached records (the linux#3170 q4 cost on J700). + 'uncached-g17p-queue-records': ('policy-memory', 'if m5 { 0 } else { RECORD_BYTES }', '0'), + # The G17P work slot is stored again on every publication. + 'rebound-work-slot': ('policy-memory', 'Some(bound) if bound != slot => return Err(EINVAL),\n' + ' Some(_) => {}\n None => {', '_ => {'), + # A context of the same VM keeps the pair's graph, so its records are retargeted. + 'retarget-same-vm': ('policy-prepare', 'let foreign = !Arc::ptr_eq(pair.context(), &self.context);', + 'let foreign = !Arc::ptr_eq(pair.context().status(), self.context.status());'), + # The render channel ignores the work slot the records carry. + 'unbound-channel': ('policy-render', 'let required = self.memory.graph.work_slot;', 'let required = None;'), + # Cached queue records are reused at their owner's release, with no later flush. + 'queue-records-no-flush': ('object', 'let flush = lease.family == Family::QueueState && lease.prefix != 0;', + 'let flush = false;'), + # A release published before the return counts as the flush. + 'queue-records-early-flush': ('object', 'if self.flush { released > self.fence }', + 'if self.flush { released >= self.fence }'), + # Cached queue records are kept until firmware stop (the J700 q4 cost once 64 graphs retired). + 'queue-records-until-stop': ('object', 'if self.flush { released > self.fence }', 'if self.flush { false }'), # G17P work nodes lose their cached prefix (the linux#3170 light-submission cost). 'uncached-g17p-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', '0'), } @@ -233,18 +257,28 @@ def context_source(text): pub mod channel { use core::sync::atomic::{AtomicU64, Ordering}; @CHANNEL@ - /// Sets the published and consumed control-record counts. + /// Sets the published and consumed control-record counts, with no release among them. pub fn set(published: u64, consumed: u64) { assert!(consumed <= published); CONTROL_PUBLISHED.store(published, Ordering::SeqCst); CONTROL_CONSUMED.store(consumed, Ordering::SeqCst); + RELEASE_PUBLISHED.store(0, Ordering::SeqCst); + RELEASE_CONSUMED.store(0, Ordering::SeqCst); } pub fn publish() { CONTROL_PUBLISHED.fetch_add(1, Ordering::SeqCst); } + /// Publishes a scheduler release. + pub fn release() { + RELEASE_PUBLISHED.store(CONTROL_PUBLISHED.fetch_add(1, Ordering::SeqCst) + 1, Ordering::SeqCst); + } /// The firmware consumes up to `records` more of the published records. pub fn consume(records: u64) { let published = CONTROL_PUBLISHED.load(Ordering::SeqCst); - let consumed = CONTROL_CONSUMED.load(Ordering::SeqCst); - CONTROL_CONSUMED.store(published.min(consumed + records), Ordering::SeqCst); + let consumed = published.min(CONTROL_CONSUMED.load(Ordering::SeqCst) + records); + CONTROL_CONSUMED.store(consumed, Ordering::SeqCst); + let release = RELEASE_PUBLISHED.load(Ordering::SeqCst); + if release <= consumed { + RELEASE_CONSUMED.fetch_max(release, Ordering::SeqCst); + } } } @@ -287,6 +321,8 @@ def context_source(text): match family { 0 if variant == 3 => (2 * page, page), 1 => (2 * page, page), + // Compare reusable queue state with BASE. cached_queue_reuse covers cached records. + 2 => (page, 0), _ => (page, page), } } @@ -399,7 +435,8 @@ def context_source(text): fn fence(pool: &Pool, family: Family, id: u64) -> Option { let inner = pool.inner.lock(); let begin = family as usize * POOL_SLOTS; - inner.returned[begin..begin + POOL_SLOTS].iter().flatten().find(|e| e.object.id == id).map(|e| e.fence) + inner.returned[begin..begin + POOL_SLOTS].iter().flatten() + .find(|e| e.object.id == id).map(|e| e.fence) } fn returns(pool: &Pool) -> [u64; 3] { @@ -455,6 +492,55 @@ def context_source(text): println!("uncached pooled: prefix == 0 skips firmware caching while keeping fencing, reuse and retention"); } + /// A returned cached queue state waits for a release published after its fence to be + /// consumed, then is reused: retired graphs never exhaust the family. + pub fn cached_queue_reuse() { + for after_release in [true, false] { + crate::forget_unmapped(); + crate::channel::set(0, 0); + let next = Cell::new(1); + let alloc = Allocator { next: &next }; + let pool = Pool::new(after_release).unwrap(); + let page = mmu::UAT_PGSZ; + let queues = || pool.allocate(&alloc, Family::QueueState, 2 * page, page, 0, CpuMap::WriteCombined) + .unwrap(); + let fresh = |id: u64, what: &str| { + let other = queues(); + assert_ne!(other.id, id, "{what}, after_release={after_release}"); + assert!(!unmapped(id)); + }; + // A release published before the return, even consumed after it, is no flush. + crate::channel::release(); + let mut old = queues(); + old.bytes_mut()[0] = 0x42; + let id = old.id; + drop(old); + crate::channel::consume(1); + fresh(id, "reused after a release published before its return"); + crate::channel::publish(); + crate::channel::consume(1); + fresh(id, "reused without a release after its return"); + crate::channel::release(); + fresh(id, "reused before the later release was consumed"); + crate::channel::consume(1); + let reused = queues(); + assert_eq!(reused.id, id, "not reused after a later release, after_release={after_release}"); + assert_eq!(reused.bytes[0], 0, "reused queue state is zeroed"); + drop(reused); + // Retired graphs with releases between them never fall back to uncached records. + for generation in 0..4 * POOL_SLOTS { + let graph = queues(); + assert!(graph.lease.is_some(), "generation {generation} fell back to uncached records"); + drop(graph); + crate::channel::release(); + crate::channel::consume(1); + } + assert!(crate::count(&snapshot(&pool), "cached_objects_2", "used=") < POOL_SLOTS as u64); + pool.stop_after_firmware(); + } + println!("cached queues: reused after a later consumed release, never before, under both fence policies"); + } + /// Each return class decides the fence; reuse never waits on a met fence. pub fn return_classes() { let next = Cell::new(1); @@ -683,7 +769,7 @@ def context_source(text): let inner = pool.inner.lock(); let begin = Family::WorkState as usize * POOL_SLOTS; (inner.reserved[1], inner.returned[begin..begin + POOL_SLOTS].iter().flatten() - .any(|e| e.fence <= witnessed)) + .any(|e| e.ready(witnessed, crate::channel::release_witnessed()))) }; let object = work_state(&pool, &alloc); match expected.remove(&object.id) { @@ -931,6 +1017,7 @@ def context_source(text): } fn main() { + now::cached_queue_reuse(); now::uncached_pooled(); now::return_classes(); now::full_family(); @@ -1003,7 +1090,7 @@ def source_rules(context, observation, tree): print('source: records and commands mark the work state; only a consumed empty-list release releases it') -def cache_policy(context, compute, memory): +def cache_policy(context, compute, memory, render, prepare): """The firmware-cached prefix each pooled G17 object family gets. Returns the failures.""" failures = [] @@ -1024,8 +1111,24 @@ def need(text, pattern, what): 'compute graph uncached') if 'Family::QueueState' in compute: failures.append('compute graph not pooled') - # Render queue records, retargeted and bound to work slots in place, stay uncached. - need(memory, r'Family::QueueState,\s*GRAPH_SIZE,\s*0,\s*prot,', 'render queue records uncached') + # Render queue records: uncached on M5, the record pages cached on G17P. + need(memory, r'Family::QueueState,\s*GRAPH_SIZE,\s*if m5 \{ 0 \} else \{ RECORD_BYTES \},\s*prot,', + 'render queue records: M5 uncached, G17P cached') + # A G17P record is never stored to after a kick named it. The work slot is stored only + # while the graph has none, and a different one is refused. + slot = block(memory, 'pub(super) fn bind_work_slot(') + need(slot, r'Some\(bound\) if bound != slot => return Err\(EINVAL\),\s*Some\(_\) => \{\}\s*None => \{' + r'[^}]*\+ WORK_SLOT\)\?\s*\.store\(slot, Ordering::Relaxed\);\s*\}\s*' + r'self\.graph\.work_slot = Some\(slot\);', + 'render work slot stored only before the first kick') + if len(re.findall(r'WORK_SLOT\)', memory)) != 1 or 'write_unaligned' in memory: + failures.append('render queue records stored outside the first work-slot binding') + # Only the same context keeps a graph; any other gets new records. + need(prepare, r'let foreign = !Arc::ptr_eq\(pair\.context\(\), &self\.context\);', 'new graph per context') + need(render, r'let keep_graph = Arc::ptr_eq\(self\.context\(\), &context\);', 'graph kept per context') + # The render channel of a pair keeps the slot its records carry. + need(render, r'let required = self\.memory\.graph\.work_slot;\s*' + r'let work_slot = work\.render_channel\(self\.slot, required,', 'render channel keeps the work slot') return failures @@ -1042,20 +1145,26 @@ def main(): check=True, capture_output=True, text=True).stdout # BASE's decisions with reuse limited to met fences: a full family never overruns. base = replace(base_text, 'Some((index, _, ready)) if ready || !room => {', 'Some((index, _, ready)) if ready => {') + # BASE predates uncached queue state. A zero prefix keeps its lease and needs no conversion. + base = replace(base, 'if !reserved {\n return Ok(result);', + 'if !reserved || prefix == 0 {\n return Ok(result);') source_rules(ctx, observation, DRIVER) policy = {'context': ctx, 'compute': (DRIVER / 'g17/queue/compute.rs').read_text(), - 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text()} + 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text(), + 'render': (DRIVER / 'g17/queue/render.rs').read_text(), + 'prepare': (DRIVER / 'g17/runtime/render/prepare.rs').read_text()} if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): where, old, new = MUTATIONS[args.mutation] policy[where[len('policy-'):]] = replace(policy[where[len('policy-'):]], old, new) - failures = cache_policy(policy['context'], policy['compute'], policy['memory']) + failures = cache_policy(policy['context'], policy['compute'], policy['memory'], policy['render'], + policy['prepare']) for failure in failures: print(f'FAIL line 0: cache policy: {failure}') if failures: return 1 - print('cache policy: in-place rewritten records uncached everywhere; work nodes and compute descriptors ' - 'uncached on M5 and cached on G17P') + print('cache policy: in-place rewritten records uncached everywhere; work nodes, compute descriptors and ' + 'render queue records uncached on M5 and cached on G17P, render records never rewritten') if args.mutation and MUTATIONS[args.mutation][0].startswith('policy-'): return 0 @@ -1068,9 +1177,10 @@ def main(): else: methods, node = (replace(methods, old, new), node) if old in methods else (methods, replace(node, old, new)) channel = '\n'.join(re.search(r'(?ms)^(?:///[^\n]*\n)*static ' + name + r': AtomicU64 = AtomicU64::new\(0\);', chan).group(0) - for name in ['CONTROL_PUBLISHED', 'CONTROL_CONSUMED']) + for name in ['CONTROL_PUBLISHED', 'CONTROL_CONSUMED', 'RELEASE_PUBLISHED', 'RELEASE_CONSUMED']) channel += '\n' + '\n'.join(block(chan, 'pub(crate) fn ' + name + '()') - for name in ['control_fence', 'control_published', 'control_witnessed']) + for name in ['control_fence', 'control_published', 'control_witnessed', + 'release_witnessed']) code = (PRELUDE.replace('@CHANNEL@', channel).replace('@BASE@', pool_source(base)).replace('@NOW@', now) .replace('@PAGES@', pages).replace('@METHODS@', methods).replace('@NODE@', node)) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index e829bcd9434dc..a6716bb34963c 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -419,8 +419,11 @@ def mutations(flag, names, base, expect=KILL): 'g17-object-fence-tests.py': [([], PASS)] + mutations('--mutation', ('overrun-full-family', 'unmap-uncached', 'reap-early', 'stop-keeps-deferred', 'unseen-strict', 'retain-not-sticky', 'node-unmarked', 'no-release', - 'm5-cached-nodes', 'm5-cached-descriptors', 'cached-queue-records', - 'uncached-g17p-nodes', 'defer-unexposed', 'unexposed-head'), []), + 'm5-cached-nodes', 'm5-cached-descriptors', 'm5-cached-queue-records', + 'uncached-g17p-queue-records', 'rebound-work-slot', 'retarget-same-vm', + 'unbound-channel', 'uncached-g17p-nodes', 'defer-unexposed', + 'unexposed-head', 'queue-records-no-flush', 'queue-records-early-flush', + 'queue-records-until-stop'), []), 'g17-output-fence-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-member-done', 'set-error-when-signalled', 'check-outside-lock'), []),