diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 1941c12ec5c66..d1fe49db85f35 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -264,6 +264,9 @@ pub(crate) struct Context { /// The kill of this context, through a compute queue or on its render pairs' behalf. Shared /// with the [`FirmwarePages`] a queue keeps after its owner exited. kill: Arc, + /// A stampless-retired render group of this context was later released through pair-wide + /// drain instead of observing post-maintenance completion stamps. + stampless_drained: AtomicBool, /// The host's recovery generation when it first saw the kill of this context done (its /// scheduler page's killed state), `u64::MAX` before ([`Self::restarted_since_kill`]). kill_seen: AtomicU64, @@ -370,18 +373,23 @@ impl Context { let scheduler_generation = super::ids::OBJECTS.object()?; let scheduler = Arc::new(scheduler, GFP_KERNEL)?; // Both firmware and host write work nodes (reused every 63 submissions - // and zeroed on pool reuse). M5 keeps the whole work-state object - // uncached. G17P maps the node page firmware-cached: the host rewrites - // a node only after `WorkStorage::drained` has read the firmware's - // final `completed` count from memory, and zeroes a returned object - // only once its pool fence is met, so it never rewrites a node the - // firmware is still updating. The counter page, which the host writes - // on every kick, stays uncached. + // and zeroed on pool reuse). Map the node page firmware-cached on all + // G17 (G17P and M5): within a context a node slot is rewritten only + // after every command holding its `WorkStateLease` has retired with + // post-maintenance completion stamps (including stampless render, where + // `Active` retains `WorkStateLease` until those stamps arrive; any + // unstamped drain pins the slot via `WorkStateLease::pin_until_stop` so + // later submissions in the same context never acquire it). Across + // contexts, `Pool::allocate` never overruns a pool fence for + // firmware-cached objects, and `retain_linked_work` keeps a killed, + // failed, stampless-drained, or still-linked context's work storage + // out of pool reuse until firmware stop. The counter page, which the + // host writes on every kick, stays uncached. let mut object = pool.allocate( alloc, Family::WorkState, 2 * UAT_PGSZ, - if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }, + UAT_PGSZ, mmu::PROT_FW_SHARED_RW, CpuMap::WriteCombined, )?; @@ -427,6 +435,7 @@ impl Context { scheduler_generation, published: AtomicBool::new(false), kill, + stampless_drained: AtomicBool::new(false), kill_seen: AtomicU64::new(u64::MAX), closed_generation: AtomicU64::new(u64::MAX), closed_for_open_client: AtomicBool::new(false), @@ -612,12 +621,23 @@ impl Context { /// cursor snapshot that proved the release consumed, so the witness already covers it. pub(crate) fn retain_linked_work(&self, pool: &Arc) -> bool { // An unreadable head counts as linked: retaining is the safe side. + // A killed context, stampless-drained render context, or failed VM may + // leave firmware-cached work nodes dirty without a normal stamped + // completion: keep the storage out of reuse until firmware stop even if + // the list head is empty. let linked = self.work_head().map_or(true, |head| head != [0, self.work_head_address()]); - if linked { - self.work.lock().object.retain_until_stop(pool); - } else if let Some(mark) = &self.work_mark { - mark.released(super::channel::control_witnessed()); + let dirty = self.kill_published() + || self.stampless_drained() + || self.status.get() != 0; + let mut work = self.work.lock(); + if linked || (dirty && work.object.cached_prefix() != 0) { + work.object.retain_until_stop(pool); + } else if !dirty { + if let Some(mark) = &self.work_mark { + mark.released(super::channel::control_witnessed()); + } } + drop(work); linked } @@ -685,6 +705,16 @@ impl Context { self.kill.finished() } + /// Record that a stampless-retired render group was released via pair-wide drain. + pub(crate) fn note_stampless_drain(&self) { + self.stampless_drained.store(true, Ordering::Release); + } + + /// A stampless-retired render group of this context was released via pair-wide drain. + pub(crate) fn stampless_drained(&self) -> bool { + self.stampless_drained.load(Ordering::Acquire) + } + /// This context's queue closed at the host's recovery `generation`, under the device mutex: /// by its client (`release_queue`), or on its behalf once a GPU recovery failed its VM as /// guilty (`Firmware::close_failed_owners`). Only the first close counts. A close notes it @@ -910,6 +940,9 @@ pub(crate) struct WorkStateLease { word: AtomicU32, /// Index of the engine whose admission took the node, valid once `word` is set. engine: AtomicU8, + /// Retired through an unstamped drain: keep the slot out of same-context + /// reuse when this lease drops instead of returning it to `WorkStates`. + pinned: AtomicBool, /// The ioctl's place in its context's submission order. ordinal: u64, } @@ -925,6 +958,7 @@ impl WorkStateLease { context, word: AtomicU32::new(FREE), engine: AtomicU8::new(0), + pinned: AtomicBool::new(false), ordinal, }) } @@ -936,6 +970,7 @@ impl WorkStateLease { context, word: AtomicU32::new(FREE), engine: AtomicU8::new(0), + pinned: AtomicBool::new(false), ordinal, }) } @@ -958,6 +993,9 @@ impl WorkStateLease { if !order.admits(self.ordinal) { return Err(EBUSY); } + if self.context.states.exhausted() { + return Err(EIO); + } let engine = engine.index(); let candidate = self.context.states.allocate(engine).ok_or(EBUSY)?; if let Err(error) = work.initialize(candidate) { @@ -1060,12 +1098,25 @@ impl WorkStateLease { .payload(pair, ordinal) .ok_or(EINVAL) } + /// Keeps this lease's work-state slot out of reuse within its context and + /// retains the context's work storage out of pool reuse until firmware stop. + /// Used on unstamped drain paths whose cached work node may still hold dirty + /// firmware cache lines. + pub(crate) fn pin_until_stop(&self) { + self.pinned.store(true, Ordering::Release); + self.context.note_stampless_drain(); + } } impl Drop for WorkStateLease { fn drop(&mut self) { let word = self.word(); if word != FREE { - self.context.release_state(word, usize::from(self.engine.load(Ordering::Relaxed))); + let engine = usize::from(self.engine.load(Ordering::Relaxed)); + if self.pinned.load(Ordering::Acquire) { + self.context.pin_state(word, engine); + } else { + self.context.release_state(word, engine); + } } else { let wake = self.context.order.lock().leave(self.ordinal); self.context.notify_turn(wake); @@ -1081,6 +1132,13 @@ impl Context { self.state_returns.notify(); } } + /// Retires a slot without returning its index to `allocate`: decrementing + /// `held[engine]` may still satisfy `may_take(1, 0)` for a waiting engine. + fn pin_state(&self, word: u32, engine: usize) { + if self.states.pin(word, engine) { + self.state_returns.notify(); + } + } /// A refused publisher waits on its engine's domain. Bumping both once the turn moved past a /// refusal means one that sampled before its refused acquire() never sleeps through it. fn pass_turn(&self) { diff --git a/drivers/gpu/drm/asahi/g17/context/identity.rs b/drivers/gpu/drm/asahi/g17/context/identity.rs index 16bc0a7d8d5de..1bab8fbdf3fe4 100644 --- a/drivers/gpu/drm/asahi/g17/context/identity.rs +++ b/drivers/gpu/drm/asahi/g17/context/identity.rs @@ -30,6 +30,13 @@ pub(super) const fn may_take(free: usize, held: u32) -> bool { pub(super) struct WorkStates { next: AtomicU32, live: [AtomicU32; 64], + /// Slots retired without post-maintenance completion stamps (for example + /// stampless render groups released via pair-wide drain or recovery-dropped + /// groups). A pinned slot stays out of `allocate` for the rest of this + /// context's life so the host never rewrites a cached work node the firmware + /// may still hold dirty; `live[index]` returns to `FREE` so `older_live` + /// never stalls behind it. + pinned: AtomicU64, /// Nodes taken by each engine's admissions and not yet released. held: [AtomicU32; ENGINES], /// Indices claimed by every context sharing this one's execution context @@ -43,6 +50,7 @@ impl WorkStates { // 0x17c8.. 0x17ea on the J813). next: AtomicU32::new(0x40), live: [const { AtomicU32::new(FREE) }; 64], + pinned: AtomicU64::new(0), held: [const { AtomicU32::new(0) }; ENGINES], claims: None, } @@ -51,6 +59,12 @@ impl WorkStates { pub(super) fn shared(claims: Arc) -> Self { Self { claims: Some(claims), ..Self::new() } } + /// Every slot of this context is pinned out of reuse, so no future release + /// can ever free one. + pub(super) fn exhausted(&self) -> bool { + let mask = (1u64 << STATE_COUNT) - 1; + (self.pinned.load(Ordering::Acquire) & mask).count_ones() as usize >= STATE_COUNT + } /// Takes a node for `engine`, or none when [`may_take`] refuses. Callers serialize /// allocations of one context; releases may run concurrently. pub(super) fn allocate(&self, engine: usize) -> Option { @@ -58,14 +72,20 @@ impl WorkStates { if !may_take(STATE_COUNT.saturating_sub(self.used()), held.load(Ordering::Acquire)) { return None; } + let pinned = self.pinned.load(Ordering::Acquire); for _ in 0..64 { let word = self.next.fetch_add(1, Ordering::Relaxed); let index = (word & 63) as usize; if index != STATE_COUNT + && (pinned & (1u64 << index)) == 0 && self.live[index] .compare_exchange(FREE, word, Ordering::AcqRel, Ordering::Acquire) .is_ok() { + if (self.pinned.load(Ordering::Acquire) & (1u64 << index)) != 0 { + self.live[index].store(FREE, Ordering::Release); + continue; + } if let Some(claims) = &self.claims { if claims.fetch_or(1 << index, Ordering::AcqRel) & (1 << index) != 0 { self.live[index].store(FREE, Ordering::Release); @@ -94,6 +114,31 @@ impl WorkStates { } released } + /// Retires `word` while keeping its slot index out of reuse for the rest of + /// this context's life (cross-context pool reuse is separately prevented by + /// `Context::retain_linked_work`). + pub(super) fn pin(&self, word: u32, engine: usize) -> bool { + let index = (word & 63) as usize; + if index == STATE_COUNT || self.live[index].load(Ordering::Acquire) != word { + return false; + } + let mask = 1u64 << index; + // Set `pinned` before clearing `live[index]` so a concurrent `allocate` + // cannot observe `FREE` without also observing the pin bit. + self.pinned.fetch_or(mask, Ordering::AcqRel); + let pinned = self.live[index] + .compare_exchange(word, FREE, Ordering::AcqRel, Ordering::Acquire) + .is_ok(); + if pinned { + if let Some(claims) = &self.claims { + claims.fetch_and(!mask, Ordering::AcqRel); + } + if let Some(held) = self.held.get(engine) { + held.fetch_sub(1, Ordering::AcqRel); + } + } + pinned + } } /// How far past the oldest waiting ioctl a new ioctl may be ordered: the ordinals past the @@ -316,11 +361,22 @@ impl WorkStates { .min_by_key(|&live| live.wrapping_sub(word) as i32) } + /// Slots in use, pinned ones included. The live words (or the shared claims) are read + /// before the pin mask: `pin` sets its bit before it clears the slot's live word and + /// claim, so a slot a concurrent `pin` has just freed is seen pinned here, never free. pub(super) fn used(&self) -> usize { if let Some(claims) = &self.claims { - return claims.load(Ordering::Acquire).count_ones() as usize; + let claimed = claims.load(Ordering::Acquire); + return (claimed | self.pinned.load(Ordering::Acquire)).count_ones() as usize; } - self.live.iter().filter(|word| word.load(Ordering::Acquire) != FREE).count() + let live = self + .live + .iter() + .enumerate() + .filter(|&(i, word)| i != STATE_COUNT && word.load(Ordering::Acquire) != FREE) + .fold(0u64, |mask, (i, _)| mask | (1u64 << i)); + let pinned = self.pinned.load(Ordering::Acquire) & !(1u64 << STATE_COUNT); + (live | pinned).count_ones() as usize } } impl RenderSlots { @@ -480,4 +536,37 @@ mod tests { // An engine outside the table takes nothing. assert!(states.allocate(ENGINES).is_none()); } + + #[test] + fn pinned_slot_is_never_reused_and_never_stalls_older_live() { + let states = WorkStates::new(); + let first = states.allocate(0).unwrap(); + let pinned_index = first & 63; + let second = states.allocate(0).unwrap(); + assert_eq!(states.older_live(second), Some(first)); + assert!(states.pin(first, 0)); + assert!(!states.pin(first, 0)); + assert_eq!(states.older_live(second), None); + assert_eq!(states.used(), 2); + assert_eq!(states.held[0].load(Ordering::Acquire), 1); + assert!(states.release(second, 0)); + assert_eq!(states.used(), 1); + assert_eq!(states.held[0].load(Ordering::Acquire), 0); + // Cycling well past STATE_COUNT never hands back the pinned slot. + for _ in 0..(STATE_COUNT * 3) { + let word = states.allocate(0).unwrap(); + assert_ne!(word & 63, pinned_index); + assert!(states.release(word, 0)); + } + assert!(!states.exhausted()); + // Pinning the remaining slots exhausts the context cleanly. + for _ in 1..STATE_COUNT { + let word = states.allocate(0).unwrap(); + assert!(states.pin(word, 0)); + } + assert!(states.exhausted()); + assert_eq!(states.used(), STATE_COUNT); + assert!(states.allocate(0).is_none()); + assert!(states.allocate(1).is_none()); + } } diff --git a/drivers/gpu/drm/asahi/g17/object.rs b/drivers/gpu/drm/asahi/g17/object.rs index 91cde36365033..23033fe328e6a 100644 --- a/drivers/gpu/drm/asahi/g17/object.rs +++ b/drivers/gpu/drm/asahi/g17/object.rs @@ -759,6 +759,11 @@ impl PooledObject { pub(crate) fn return_mark(&self) -> Option> { self.lease.as_ref().and_then(|lease| lease.mark.clone()) } + + /// Length of the firmware-cached prefix of this object's mapping, or 0 when uncached. + pub(crate) fn cached_prefix(&self) -> usize { + self.lease.as_ref().map_or(0, |lease| lease.prefix) + } } impl Drop for PooledObject { diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 9a0bc7758966c..671a8e9b14a16 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -109,14 +109,17 @@ impl DescriptorRing { /// Both firmware and host write compute descriptors: the firmware updates /// an accounting word near the end of each descriptor (`+0xfac` on M5), /// and the host rewrites each slot every 32 kicks. M5 keeps them uncached - /// against the dirty-line writeback hazard of linux#3170, while retaining + /// against the dirty-line writeback hazard of linux#3170 (and because cached + /// M5 descriptors did not help light compute in linux#3389), while retaining /// their VA and fence in the pool. G17P maps them firmware-cached, as it /// does render descriptors: the host rewrites a slot only after the kick /// that last used it retired (at most `DESCRIPTORS` kicks are in flight), - /// by when that kick's accounting store is in memory. The hardware reads - /// the same pages through an uncached canonical low alias; the kernel - /// mapping, in the upper half every execution context includes, is - /// firmware-only. + /// by when that kick's accounting store is in memory. A queue recycled after + /// a kill or quarantine retains a firmware-cached descriptor ring until + /// firmware stop (`Queue::retain_ring_until_stop`) instead of returning it + /// to the reuse pool. The hardware reads the same pages through an uncached + /// canonical low alias; the kernel mapping, in the upper half every execution + /// context includes, is firmware-only. pub(crate) fn new(alloc: &Allocator<'_>, objects: &Arc) -> Result { let size = DESCRIPTORS * COMPUTE_DESCRIPTOR_SIZE; let object = objects.allocate( @@ -2365,6 +2368,16 @@ impl Queue { self.recycle_settled()?; Ok(true) } + /// Keeps this queue's descriptor ring mapped and out of pool reuse until + /// firmware stop, for queues recycled after a kill or quarantine where + /// aborted commands did not complete with post-maintenance stamps. + pub(crate) fn retain_ring_until_stop(&mut self, pool: &Arc) { + if let Some(ring) = self.graph.ring.as_mut() { + if ring.object.cached_prefix() != 0 { + ring.object.retain_until_stop(pool); + } + } + } fn recycle_settled(&mut self) -> Result { self.graph.reset_items()?; self.config_cache = None; diff --git a/drivers/gpu/drm/asahi/g17/queue/render.rs b/drivers/gpu/drm/asahi/g17/queue/render.rs index f4f6b6e9ed356..955a717fa8082 100644 --- a/drivers/gpu/drm/asahi/g17/queue/render.rs +++ b/drivers/gpu/drm/asahi/g17/queue/render.rs @@ -187,10 +187,12 @@ struct Active { /// First observation of this group executed and consumed while its stamps lagged. stamp_wait_since: Option, /// The group retired on its pass record without completion stamps and its client has its - /// result, but the firmware may still store the stamps through its descriptor: the - /// descriptor slot stays held until stamps cover the group. Also set for a group that - /// retired behind such groups: it leaves the pair after them. + /// result, but the firmware may still store the stamps through its descriptor and hold + /// dirty cache lines on its work node: both the descriptor slot and `stamps_owed_work` + /// stay held until stamps cover the group. Also set for a group that retired behind + /// such groups so it leaves the pair after them. stamps_owed: bool, + stamps_owed_work: Option>, } impl Drop for Active { @@ -1443,6 +1445,7 @@ impl Pair { abandoned_since: None, stamp_wait_since: None, stamps_owed: false, + stamps_owed_work: None, }) .map_err(|_| EBUSY)?; self.prepared = None; @@ -2549,16 +2552,23 @@ impl Pair { &front.packet, [timestamps[0], timestamps[3]], ); + if stampless || at != 0 { + // Retain the work-state lease before Deferred::Retired releases the + // submission's own lease: a pass-record retirement does not witness + // cache writeback on the firmware-cached work node, and a group + // retired behind an owed group stays in `active` until stamps cover it. + front.stamps_owed_work = Some(front.packet.completion.work_state()?); + } host.with_render_lock(|| front.packet.completion.note_render_executed()); defer(Deferred::Retired( front.packet.completion.clone(), front.packet.check_firmware_producers().map(|()| timestamps), ))?; if stampless || at != 0 { - // The pass record is no witness that the firmware is done with the descriptor: it - // can still store the completion stamps through it, and a reused slot names no - // stamp target. Keep the slot until stamps cover the group, as well as one that - // retired behind such groups so it leaves in order. + // The pass record is no witness that the firmware is done with the descriptor or + // its work node: it can still store the completion stamps through it, and a reused + // slot names no stamp target. Keep both until stamps cover the group, as well as + // one that retired behind such groups so it leaves in order. front.stamp_wait_since = None; front.stamps_owed = true; // Work of this pair retires: a later blame on it is collateral again. @@ -2753,6 +2763,7 @@ impl Pair { if failing { // decide() replays only innocent groups that never ran: like `fail_dropped`, // they fail without poisoning their VM. Restarts other VMs caused dropped them. + // retirement::abandoned() already proved stamps cover every group here. packet.completion.classify(recovery::Class::Spared); defer(Deferred::Retired(packet.completion.clone(), Err(ENODATA)))?; self.memory.retire(ordinal)?; @@ -3151,13 +3162,37 @@ impl Pair { pr_warn!("G17: render slot {}: {} groups of a killed guilty context released after a later restart (gen {})\n", self.slot, self.active.len(), generation); } + let stamps = host.stamps(self.qids()).ok(); + core::sync::atomic::fence(core::sync::atomic::Ordering::Acquire); while let Some(active) = self.active.front() { // A group retired on its pass record was reported then (`stamps_owed`): the pair-wide // proof above covers its stamps too (or the kill of its context), so only its - // descriptor is released. It has no drained result of its own. + // descriptor is released. It has no drained result of its own. When firmware stamps + // do not cover the group, pin its work-state slot against same-context reuse and + // retain the context's work storage until firmware stop. let owed = active.stamps_owed; let ordinal = active.ticket.ordinal; let context_update = active.context_update; + let lagging = ordinal.checked_add(1).is_none_or(|published| { + stamps.is_none_or(|stamps| { + !stamps + .into_iter() + .all(|stamp| retirement::stamp_covers(stamp, published)) + }) + }); + if lagging { + if owed { + if let Some(work) = &active.stamps_owed_work { + work.pin_until_stop(); + } else { + active.packet.context.note_stampless_drain(); + } + } else if let Ok(work) = active.packet.completion.work_state() { + work.pin_until_stop(); + } else { + active.packet.context.note_stampless_drain(); + } + } if !owed { let result = active.drained_result.ok_or(EIO)?; defer(Deferred::Drained(active.packet.completion.clone(), result))?; diff --git a/drivers/gpu/drm/asahi/g17/runtime.rs b/drivers/gpu/drm/asahi/g17/runtime.rs index f61ab3067f60e..25c6bd838afbc 100644 --- a/drivers/gpu/drm/asahi/g17/runtime.rs +++ b/drivers/gpu/drm/asahi/g17/runtime.rs @@ -4570,8 +4570,9 @@ impl super::Firmware { .filter_map(|entry| entry.queue.as_deref_mut()) { let busy = !queue.channel_free(); - queue.recycle_killed()?; - queue.recycle_quarantined_idle()?; + if queue.recycle_killed()? || queue.recycle_quarantined_idle()? { + queue.retain_ring_until_stop(&self.pool); + } if deferred.vacated_room() { if let Some(vacated) = queue.take_recycled_ring() { deferred.defer_vacated(vacated); diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 3a0f9a6dff734..d6f15ba97076b 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -23,16 +23,20 @@ - Without `after_release` (M4, M5) every decision, and the snapshot counts, match the pool before linux#1978 (BASE) on the same random operations, with 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-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. Cached queue-state backing stays mapped until +- Source & recovery rules: every accessor that hands the address to the + firmware marks it; only the clean release path of `retain_linked_work` marks + it released; a killed context, stampless-drained context, or failed VM retains + a firmware-cached work state until firmware stop even with an empty work list; + a compute queue recycled after a kill or quarantine retains a firmware-cached + descriptor ring until firmware stop. +- Cache policy (linux#3170 and follow-ups): records the host rewrites in place + (the compute graph, M5 scheduler pages) stay uncached on every G17; work nodes + keep their firmware-cached prefix on every G17 (G17P and M5); compute + descriptors and render queue records are uncached on M5 and firmware-cached on + G17P, where the host never stores to a render queue record 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. Cached queue-state backing stays mapped until firmware stop under either release policy; a full family falls back to fresh uncached allocations. @@ -80,10 +84,60 @@ 'node-unmarked': ('context', ' self.context.expose_work();\n', ''), # A consumed release with an empty list does not mark the work state. 'no-release': ('context', 'mark.released(super::channel::control_witnessed());', 'let _ = mark;'), - # M5 work nodes are firmware-cached again. - 'm5-cached-nodes': ('policy-context', 'if alloc.uat.is_m5() { 0 } else { UAT_PGSZ }', 'UAT_PGSZ'), - # M5 compute descriptors are firmware-cached again. + # A killed context with an empty list returns its cached work state to the pool. + 'reuse-killed-work-state': ('context', + ' let dirty = self.kill_published()\n', + ' let dirty = false\n'), + # A stampless-drained context with an empty list returns its cached work state to the pool. + 'reuse-stampless-drained-work-state': ('context', + ' || self.stampless_drained()\n', ''), + # A failed VM with an empty list returns its cached work state to the pool. + 'reuse-failed-work-state': ('context', + ' || self.status.get() != 0;\n', ';\n'), + # Stampless render drops its WorkStateLease before completion stamps arrive. + 'drop-stampless-work-lease': ( + 'policy-render', + ' front.stamps_owed_work = Some(front.packet.completion.work_state()?);\n', + '', + ), + # Pair-wide drain of a stampless render group fails to pin its work-state lease. + 'drop-stampless-drain-pin': ( + 'policy-render', + ' if let Some(work) = &active.stamps_owed_work {\n' + ' work.pin_until_stop();\n' + ' } else {\n' + ' active.packet.context.note_stampless_drain();\n' + ' }\n', + ' active.packet.context.note_stampless_drain();\n', + ), + # WorkStates::used reads the pin mask before the live words (or the shared claims), so a slot + # a concurrent pin just freed counts as free and may_take lets an engine take its peer's last + # node (linux#3389 review). + 'used-pin-first': ('identity', ' let live = self\n .live\n .iter()\n .enumerate()\n .filter(|&(i, word)| i != STATE_COUNT && word.load(Ordering::Acquire) != FREE)\n .fold(0u64, |mask, (i, _)| mask | (1u64 << i));\n let pinned = crate::race::pinned_load(&self.pinned) & !(1u64 << STATE_COUNT);\n', ' let pinned = crate::race::pinned_load(&self.pinned) & !(1u64 << STATE_COUNT);\n let live = self\n .live\n .iter()\n .enumerate()\n .filter(|&(i, word)| i != STATE_COUNT && word.load(Ordering::Acquire) != FREE)\n .fold(0u64, |mask, (i, _)| mask | (1u64 << i));\n'), + 'used-pin-first-shared': ('identity', ' let claimed = claims.load(Ordering::Acquire);\n return (claimed | crate::race::pinned_load(&self.pinned)).count_ones() as usize;\n', ' let pinned = crate::race::pinned_load(&self.pinned);\n return (claims.load(Ordering::Acquire) | pinned).count_ones() as usize;\n'), + # WorkStates::pin forgets to record the pin bit, allowing same-context reuse after unstamped drain. + 'same-context-reuse-pinned-slot': ( + 'identity', + ' self.pinned.fetch_or(mask, Ordering::AcqRel);\n', + '', + ), + # A compute queue recycled after kill/quarantine returns its cached descriptor ring to the pool. + 'reuse-recycled-descriptor-ring': ( + 'policy-runtime', + ' if queue.recycle_killed()? || queue.recycle_quarantined_idle()? {\n' + ' queue.retain_ring_until_stop(&self.pool);\n' + ' }', + ' queue.recycle_killed()?;\n' + ' queue.recycle_quarantined_idle()?;', + ), + # Work nodes lose their firmware-cached prefix (the linux#3170 light-submission cost). + 'uncached-nodes': ('policy-context', 'Family::WorkState,\n 2 * UAT_PGSZ,\n UAT_PGSZ,', + 'Family::WorkState,\n 2 * UAT_PGSZ,\n 0,'), + # M5 compute descriptors are firmware-cached again (slower light compute at depth 4, linux#3389). 'm5-cached-descriptors': ('policy-compute', 'if alloc.uat.is_m5() { 0 } else { size }', 'size'), + # M5 scheduler pages, which are zeroed and reinitialised on reuse, are firmware-cached again. + 'cached-scheduler': ('policy-context', 'Family::Scheduler,\n UAT_PGSZ,\n 0,', + 'Family::Scheduler,\n UAT_PGSZ,\n UAT_PGSZ,'), # 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). @@ -96,8 +150,6 @@ '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;'), - # 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'), } @@ -142,6 +194,26 @@ def context_source(text): return pages, methods, node +def identity_source(text): + """Extract the real WorkStates allocator, pin, older_live, used, and may_take from context/identity.rs.""" + consts = '\n'.join(re.search(r'^pub\(super\) const ' + name + r': [^;]+;', text, re.M).group(0) + for name in ['FREE', 'STATE_COUNT', 'ENGINES']) + may_take = block(text, 'pub(super) const fn may_take(') + struct = block(text, 'pub(super) struct WorkStates {') + impl1 = block(text, 'impl WorkStates {') + impl2 = block(text, 'impl WorkStates {', text.index('impl WorkStates {') + 1) + return hook_used('\n'.join([consts, may_take, struct, impl1, impl2])) + + +def hook_used(ident): + """Route used()'s pin-mask loads through crate::race, which can run a scheduled pin() + right after the load: a concurrent pin landing between used()'s reads.""" + start = ident.index(' pub(super) fn used(&self) -> usize {') + end = ident.index('\n }\n', start) + len('\n }\n') + body = ident[start:end].replace('self.pinned.load(Ordering::Acquire)', 'crate::race::pinned_load(&self.pinned)') + return ident[:start] + body + ident[end:] + + PRELUDE = r''' #![allow(dead_code, unused_imports, unused_variables, unused_mut, unused_unsafe, unused_macros)] #![allow(private_interfaces, private_bounds)] @@ -196,13 +268,19 @@ def context_source(text): impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } pub mod mmu { + use std::cell::Cell; pub type Prot = u8; pub const UAT_PGSZ: usize = 0x4000; + thread_local! { + pub static ZERO_PREFIX_CALLS: Cell = const { Cell::new(0) }; + } pub struct KernelMapping { pub iova: u64 } impl KernelMapping { pub fn iova(&self) -> u64 { self.iova } pub unsafe fn set_fw_cached_prefix(&self, prefix: usize) -> (crate::Result<[u64; 2]>, bool) { - assert!(prefix > 0, "set_fw_cached_prefix must not be called for prefix == 0"); + if prefix == 0 { + ZERO_PREFIX_CALLS.with(|c| c.set(c.get() + 1)); + } (Ok([0; 2]), true) } } @@ -246,7 +324,28 @@ def context_source(text): } } -pub mod channel { +pub mod race { + use core::sync::atomic::{AtomicU64, Ordering}; + use std::cell::RefCell; + thread_local! { static AFTER: RefCell>> = RefCell::new(None); } + /// Runs `f` once, right after the next pin-mask load in `WorkStates::used`. + pub fn after_next_pin_load(f: impl FnOnce() + 'static) { + AFTER.with(|a| *a.borrow_mut() = Some(Box::new(f))); + } + pub fn pinned_load(pinned: &AtomicU64) -> u64 { + let value = pinned.load(Ordering::Acquire); + if let Some(f) = AFTER.with(|a| a.borrow_mut().take()) { + f(); + } + value + } +} +pub mod identity { + use core::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + use std::sync::Arc; +@IDENTITY@ +} +mod channel { use core::sync::atomic::{AtomicU64, Ordering}; @CHANNEL@ /// Sets the published and consumed control-record counts. @@ -297,7 +396,7 @@ def context_source(text): ops } -/// Size and cached prefix per family; `variant` 3 gives descriptors a second size. +/// Size and uncached prefix per family for BASE parity; `variant` 3 gives descriptors a second size. pub fn geometry(family: usize, variant: usize) -> (usize, usize) { let page = mmu::UAT_PGSZ; match family { @@ -470,6 +569,8 @@ def context_source(text): pool.stop_after_firmware(); assert!(unmapped(kept_id)); assert!(unmapped(ws_id)); + assert_eq!(mmu::ZERO_PREFIX_CALLS.with(|c| c.get()), 0, + "set_fw_cached_prefix must not be called for prefix == 0"); } println!("uncached pooled: prefix == 0 skips firmware caching while keeping fencing, reuse and retention"); } @@ -827,6 +928,12 @@ def context_source(text): pub struct SchedulerStorage; pub mod mmu { pub struct ContextHold; } pub struct QosLease; + pub struct VmStatus(core::sync::atomic::AtomicI32); + impl VmStatus { + fn new() -> Self { Self(core::sync::atomic::AtomicI32::new(0)) } + fn get(&self) -> i32 { self.0.load(Ordering::Acquire) } + fn fail(&self, err: i32) { self.0.store(err, Ordering::Release); } + } pub struct WorkStorage { pub object: PooledObject } pub struct Kill; @PAGES@ @@ -839,11 +946,16 @@ def context_source(text): hold: Arc, qos: Arc, kill: Arc, + kill_published: core::sync::atomic::AtomicBool, + stampless_drained: core::sync::atomic::AtomicBool, + status: Arc, /// The work-list head the firmware left. head: Cell<[u64; 2]>, } impl Context { fn work_head(&self) -> Result<[u64; 2]> { Ok(self.head.get()) } + fn kill_published(&self) -> bool { self.kill_published.load(Ordering::Acquire) } + fn stampless_drained(&self) -> bool { self.stampless_drained.load(Ordering::Acquire) } @METHODS@ } pub struct WorkStateLease { context: Arc, word: core::sync::atomic::AtomicU32 } @@ -860,6 +972,9 @@ def context_source(text): let context = Arc::new(Context { work: Arc::new(Mutex::new(WorkStorage { object })), work_base, work_mark, exposure, scheduler: Arc::new(SchedulerStorage), hold: Arc::new(mmu::ContextHold), qos: Arc::new(QosLease), kill: Arc::new(Kill), + kill_published: core::sync::atomic::AtomicBool::new(false), + stampless_drained: core::sync::atomic::AtomicBool::new(false), + status: Arc::new(VmStatus::new()), head: Cell::new([0, work_base + (UAT_PGSZ + 0x400) as u64]), }); (context, id) @@ -922,8 +1037,51 @@ def context_source(text): drop(context); assert_eq!(super::fence(&pool, Family::WorkState, id), None, "linked work is kept"); assert!(!unmapped(id)); + + // A killed context with an empty list keeps its cached work state until stop. + let (context, killed_id) = new_context(&pool, &alloc); + let _ = context.work_head_va(); + context.kill_published.store(true, Ordering::Release); + assert!(!context.retain_linked_work(&pool)); + drop(context); + assert_eq!(super::fence(&pool, Family::WorkState, killed_id), None, + "a killed context's work state is kept out of reuse until stop"); + assert!(!unmapped(killed_id)); + + // A stampless-drained render context with an empty list keeps its cached work state until stop. + let (context, stampless_id) = new_context(&pool, &alloc); + let _ = context.work_head_va(); + context.stampless_drained.store(true, Ordering::Release); + assert!(!context.retain_linked_work(&pool)); + drop(context); + assert_eq!(super::fence(&pool, Family::WorkState, stampless_id), None, + "a stampless-drained context's work state is kept out of reuse until stop"); + assert!(!unmapped(stampless_id)); + + // A failed VM (recovery/fault) with an empty list keeps its cached work state until stop. + let (context, failed_id) = new_context(&pool, &alloc); + let _ = context.work_head_va(); + context.status.fail(-5); + assert!(!context.retain_linked_work(&pool)); + drop(context); + assert_eq!(super::fence(&pool, Family::WorkState, failed_id), None, + "a failed VM's work state is kept out of reuse until stop"); + assert!(!unmapped(failed_id)); + + // Even after advancing the control fence, a fresh allocation never reuses kept work states. + crate::channel::set(100, 100); + let next_ws = super::work_state(&pool, &alloc); + assert_ne!(next_ws.id, id); + assert_ne!(next_ws.id, killed_id); + assert_ne!(next_ws.id, stampless_id); + assert_ne!(next_ws.id, failed_id); + drop(next_ws); + + pool.stop_after_firmware(); + assert!(unmapped(id) && unmapped(killed_id) && unmapped(failed_id), + "kept work states are unmapped once firmware stops"); } - println!("context: records, commands and retained records mark the work state; a consumed release with an empty list releases it"); + println!("context: records, commands and retained records mark the work state; killed/failed/linked contexts retain until stop"); } /// Queues created and closed without work publish no control record, so the control @@ -986,7 +1144,89 @@ def context_source(text): } } +/// A pin that lands between used()'s reads must not make its slot count as free: with +/// one free slot and the requesting engine already holding a node, may_take must still +/// refuse that engine the last node (the peer's), on a private and a shared context. +fn work_states_used_sees_concurrent_pin() { + use crate::identity::{WorkStates, STATE_COUNT}; + for shared in [false, true] { + let claims = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); + let states: &'static WorkStates = + Box::leak(Box::new(if shared { WorkStates::shared(claims) } else { WorkStates::new() })); + // Engine 0 holds its node and the fillers; engine 1 holds only the node it is about + // to pin. All slots but one are taken, so exactly one slot is free. + let mine = states.allocate(0).expect("engine 0 node"); + let peer = states.allocate(1).expect("engine 1 node"); + let mut rest = Vec::new(); + for _ in 0..(STATE_COUNT - 3) { + rest.push(states.allocate(0).expect("filler")); + } + assert_eq!(states.used(), STATE_COUNT - 1, "one slot free (shared={shared})"); + crate::race::after_next_pin_load(move || assert!(states.pin(peer, 1), "concurrent pin")); + assert!(states.allocate(0).is_none(), + "engine 0 must not take the last free node while holding one, even when a pin lands mid-count (shared={shared})"); + assert_eq!(states.used(), STATE_COUNT - 1, "the pinned slot stays used (shared={shared})"); + assert!(states.allocate(1).is_some(), "the peer can still take the last node (shared={shared})"); + let _ = (mine, rest); + } + println!("WorkStates used(): a pin between its reads keeps the slot counted, so may_take still reserves the peer's node"); +} + +fn work_states_pin_prevents_same_context_reuse() { + use crate::identity::{WorkStates, STATE_COUNT}; + let states = WorkStates::new(); + let drained = states.allocate(0).expect("initial render slot"); + let drained_slot = drained & 63; + let newer = states.allocate(0).expect("newer slot"); + assert_eq!(states.older_live(newer), Some(drained)); + assert!(states.pin(drained, 0), "pinning a live slot succeeds once"); + assert!(!states.pin(drained, 0), "double pin is a no-op"); + assert_eq!(states.older_live(newer), None, "pinned slot must not stall older_live"); + assert_eq!(states.used(), 2, "pinned slot stays counted in used()"); + assert!(states.release(newer, 0)); + assert_eq!(states.used(), 1); + for _ in 0..(STATE_COUNT * 4) { + let w = states.allocate(0).expect("same-context submission"); + assert_ne!(w & 63, drained_slot, "same-context submission re-acquired pinned slot"); + assert!(states.release(w, 0)); + } + for _ in 1..(STATE_COUNT - 2) { + let w = states.allocate(0).expect("slot to pin"); + assert!(states.pin(w, 0)); + } + let r = states.allocate(0).expect("render takes 1 of 2 remaining"); + let c = states.allocate(1).expect("compute takes last remaining"); + assert!(states.release(r, 0)); + assert!(states.release(c, 1)); + for _ in 0..2 { + let w = states.allocate(0).expect("final slot to pin"); + assert!(states.pin(w, 0)); + } + assert!(states.exhausted(), "all 63 slots pinned must report exhausted()"); + assert!(states.allocate(0).is_none()); + assert!(states.allocate(1).is_none()); + let claims = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0)); + let ctx_a = WorkStates::shared(claims.clone()); + let ctx_b = WorkStates::shared(claims.clone()); + let wa = ctx_a.allocate(0).expect("shared ctx_a slot"); + let sa = wa & 63; + assert!(ctx_a.pin(wa, 0)); + assert_eq!(claims.load(std::sync::atomic::Ordering::Acquire) & (1u64 << sa), 0, + "pinned slot releases shared work-key claim for sibling context"); + assert_eq!(ctx_a.used(), 1, "pinning context still accounts for its pinned slot"); + for _ in 0..(STATE_COUNT * 2) { + let w = ctx_a.allocate(0).expect("shared ctx_a retry"); + assert_ne!(w & 63, sa, "shared context re-acquired its own pinned slot"); + assert!(ctx_a.release(w, 0)); + } + let wb = ctx_b.allocate(0).expect("sibling ctx_b slot"); + assert!(ctx_b.release(wb, 0)); + println!("same-context WorkStates pin: pinned slot never re-acquired, older_live unblocked, exhaustion clean"); +} + fn main() { + work_states_pin_prevents_same_context_reuse(); + work_states_used_sees_concurrent_pin(); now::cached_queue_lifetimes(); now::uncached_pooled(); now::return_classes(); @@ -1029,11 +1269,15 @@ def source_rules(context, observation, tree): assert context.count('object.gpu_va()') == 2 assert 'let work_base = object.gpu_va();' in context assert 'fw::WorkNode::new(self.object.gpu_va() + counter as u64, word)' in context - # A release is marked only where retain_linked_work found the list empty. + # A release is marked only where retain_linked_work found a clean, unkilled, empty-list context. linked = block(context, ' pub(crate) fn retain_linked_work(') - assert re.search(r'if linked \{\n\s+self\.work\.lock\(\)\.object\.retain_until_stop\(pool\);\n' - r'\s+\} else if let Some\(mark\) = &self\.work_mark \{\n' - r'\s+mark\.released\(super::channel::control_witnessed\(\)\);', linked), linked + assert re.search(r'let dirty = self\.kill_published\(\)\s+\|\| self\.stampless_drained\(\)\s+\|\| self\.status\.get\(\) != 0;\s+' + r'let mut work = self\.work\.lock\(\);\s+' + r'if linked \|\| \(dirty && work\.object\.cached_prefix\(\) != 0\) \{\s+' + r'work\.object\.retain_until_stop\(pool\);\s+' + r'\} else if !dirty \{\s+' + r'if let Some\(mark\) = &self\.work_mark \{\s+' + r'mark\.released\(super::channel::control_witnessed\(\)\);', linked), linked assert context.count('.released(') == 1 and context.count('.retain()') == 1 # The non-marking address only feeds comparisons with the host's own reads. users = [] @@ -1060,22 +1304,29 @@ 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, render, prepare): - """The firmware-cached prefix each pooled G17 object family gets. Returns the failures.""" +def cache_policy(context, compute, memory, runtime, render, prepare): + """The firmware-cached prefix and recovery retention policy each pooled G17 object family gets. Returns the failures.""" failures = [] def need(text, pattern, what): if not re.search(pattern, text): failures.append(what) - # Work nodes: uncached on M5, the node page cached on G17P; the counter page stays uncached. - need(context, r'pool\.allocate\(\s*alloc,\s*Family::WorkState,\s*2 \* UAT_PGSZ,\s*' - r'if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ UAT_PGSZ \},', 'work nodes: M5 uncached, G17P node page cached') + # Work nodes: the node page is cached on every G17; the counter page stays uncached. + need(context, r'pool\.allocate\(\s*alloc,\s*Family::WorkState,\s*2 \* UAT_PGSZ,\s*UAT_PGSZ,', + 'work nodes: node page cached') # M5 scheduler pages, which are zeroed and reinitialised on reuse, stay uncached. need(context, r'Family::Scheduler,\s*UAT_PGSZ,\s*0,', 'M5 scheduler pages uncached') # Compute descriptors: uncached on M5, cached on G17P. need(compute, r'Family::Descriptor,\s*size,\s*if alloc\.uat\.is_m5\(\) \{ 0 \} else \{ size \},', 'compute descriptors: M5 uncached, G17P cached') + # A compute queue recycled after kill or quarantine retains a cached descriptor ring until stop. + need(compute, r'pub\(crate\) fn retain_ring_until_stop\(&mut self, pool: &Arc\) \{\s*' + r'if let Some\(ring\) = self\.graph\.ring\.as_mut\(\) \{\s*' + r'if ring\.object\.cached_prefix\(\) != 0 \{\s*' + r'ring\.object\.retain_until_stop\(pool\);', 'compute retain_ring_until_stop helper') + need(runtime, r'if queue\.recycle_killed\(\)\? \|\| queue\.recycle_quarantined_idle\(\)\? \{\s*' + r'queue\.retain_ring_until_stop\(&self\.pool\);', 'recycled compute queues retain descriptor ring until stop') # The compute graph, whose queue record is rebound in place, is an ordinary uncached allocation. need(compute, r'let mut graph = alloc\.kernel\(GRAPH_SIZE \+ mmu::UAT_PGSZ, page, prot, cpu\)\?;', 'compute graph uncached') @@ -1099,6 +1350,18 @@ def need(text, pattern, what): # 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') + # Stampless render retains its WorkStateLease until post-maintenance stamps arrive, + # and pair-wide drain without covering stamps pins the slot via pin_until_stop(). + need(render, r'if stampless \|\| at != 0 \{[^}]*front\.stamps_owed_work = Some\(front\.packet\.completion\.work_state\(\)\?\);[^}]*\}\s*host\.with_render_lock\(\|\| front\.packet\.completion\.note_render_executed\(\)\);\s*defer\(Deferred::Retired\(', + 'stampless render retains WorkStateLease across stamps_owed') + need(render, r'if lagging \{\s*if owed \{\s*if let Some\(work\) = &active\.stamps_owed_work \{\s*work\.pin_until_stop\(\);', + 'stampless render drain pins WorkStateLease until stop when stamps lag') + need(context, r'pub\(crate\) fn pin_until_stop\(&self\) \{\s*self\.pinned\.store\(true, Ordering::Release\);\s*self\.context\.note_stampless_drain\(\);\s*\}', + 'WorkStateLease::pin_until_stop sets pinned and stampless_drained') + need(context, r'if self\.pinned\.load\(Ordering::Acquire\) \{\s*self\.context\.pin_state\(word, engine\);', + 'WorkStateLease::drop pins slot on unstamped drain') + need(context, r'if self\.context\.states\.exhausted\(\) \{\s*return Err\(EIO\);\s*\}', + 'WorkStateLease::acquire fails cleanly when all slots are pinned') return failures @@ -1122,35 +1385,39 @@ def main(): policy = {'context': ctx, 'compute': (DRIVER / 'g17/queue/compute.rs').read_text(), 'memory': (DRIVER / 'g17/queue/render/memory.rs').read_text(), + 'runtime': (DRIVER / 'g17/runtime.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'], policy['render'], - policy['prepare']) + failures = cache_policy(policy['context'], policy['compute'], policy['memory'], + policy['runtime'], 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, compute descriptors and ' - 'render queue records uncached on M5 and cached on G17P, render records never rewritten') + print('cache policy: in-place rewritten records uncached everywhere; work nodes cached on every G17; ' + '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 now = pool_source(obj) pages, methods, node = context_source(ctx) + ident = identity_source((DRIVER / 'g17/context/identity.rs').read_text()) if args.mutation: where, old, new = MUTATIONS[args.mutation] if where == 'object': now = replace(now, old, new) + elif where == 'identity': + ident = replace(ident, old, new) 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']) channel += '\n' + '\n'.join(block(chan, 'pub(crate) fn ' + name + '()') for name in ['control_fence', 'control_published', 'control_witnessed']) - code = (PRELUDE.replace('@CHANNEL@', channel).replace('@BASE@', pool_source(base)).replace('@NOW@', now) + code = (PRELUDE.replace('@CHANNEL@', channel).replace('@IDENTITY@', ident).replace('@BASE@', pool_source(base)).replace('@NOW@', now) .replace('@PAGES@', pages).replace('@METHODS@', methods).replace('@NODE@', node)) with tempfile.TemporaryDirectory() as work: diff --git a/tools/asahi/g17-quarantine-drain-tests.py b/tools/asahi/g17-quarantine-drain-tests.py index 7f1203673b0ae..f26219bd2fd3e 100644 --- a/tools/asahi/g17-quarantine-drain-tests.py +++ b/tools/asahi/g17-quarantine-drain-tests.py @@ -183,6 +183,7 @@ def fixture(): signalled: AtomicBool, accepted: AtomicBool, spared: AtomicBool, + work: Arc, result: Mutex>>, } fn discarded(error: Error) -> bool { error == ECANCELED || error == ENODATA } @@ -192,6 +193,7 @@ def fixture(): fn status(&self) -> &Arc { &self.status } fn report(&self, _: Error) {} fn signal_terminal(&self, result: Result<[u64; 4]>) { *self.result.lock() = Some(result); } + fn work_state(&self) -> Result> { Ok(self.work.clone()) } /// The real one also notes a failure in the engine's failure log around the signals. fn signal_result(&self, result: Result<[u64; 4]>) { self.signal_terminal(result); } /// The lease handling of the real complete_with_compute (checked against it above). @@ -206,13 +208,28 @@ def fixture(): } ''' + command + '\n}\n' + item(completion, 'pub(crate) enum Deferred {') + '\n' + item(completion, 'impl Deferred {') + r''' -pub struct Packet { completion: Arc } +pub struct Context { stampless_drained: AtomicBool } +impl Context { + fn note_stampless_drain(&self) { self.stampless_drained.store(true, Ordering::Release); } +} +pub struct WorkStateLease { + context: Arc, + pinned: AtomicBool, +} +impl WorkStateLease { + fn pin_until_stop(&self) { + self.pinned.store(true, Ordering::Release); + self.context.note_stampless_drain(); + } +} +pub struct Packet { completion: Arc, context: Arc } pub struct Ticket { ordinal: u64 } pub struct Active { packet: Arc, ticket: Ticket, context_update: bool, stamps_owed: bool, + stamps_owed_work: Option>, failed: bool, flist_completed: bool, drained_result: Option>, @@ -232,15 +249,24 @@ def fixture(): fn retire(&mut self, ordinal: u64) -> Result { self.retired.push(ordinal); Ok(()) } fn mark_auxiliary_dirty(&mut self) {} } +mod retirement { + pub(crate) fn stamp_covers(stamp: u32, published: u64) -> bool { + (stamp.wrapping_sub(published as u32) as i32) >= 0 + } +} /// The firmware state behind `Pair::firmware_drained`: cursors done == write, free-list /// blocks returned, and stamps covering the last publication or the context's kill acknowledged. pub trait Host { fn drained(&self) -> bool; /// No restart in progress (recovery generation, state). fn epoch(&self) -> Result<(u64, u32)> { Ok((1, 0)) } + fn stamps(&self, _qids: [u8; 2]) -> Result<[u32; 2]>; +} +pub struct FakeHost { drained: bool, stamps: [u32; 2] } +impl Host for FakeHost { + fn drained(&self) -> bool { self.drained } + fn stamps(&self, _qids: [u8; 2]) -> Result<[u32; 2]> { Ok(self.stamps) } } -pub struct FakeHost { drained: bool } -impl Host for FakeHost { fn drained(&self) -> bool { self.drained } } pub struct Pair { quarantined: bool, active: Ring, @@ -252,6 +278,7 @@ def fixture(): slot: u8, } impl Pair { + fn qids(&self) -> [u8; 2] { [0, 1] } fn firmware_drained(&self, host: &impl Host) -> Result { Ok(host.drained()) } // This fixture models no killed guilty context (`Pair::guilty_killed`). fn guilty_killed(&self, _generation: u64, _state: u32) -> bool { false } @@ -308,31 +335,35 @@ def fixture(): let pin = Arc::new(Mutex::new(None)); let vm = Arc::new(AtomicBool::new(false)); let guard = VmJobGuard { pool: pool.clone(), slot: lease.slot(), quarantined: pin.clone(), vm: vm.clone() }; + let context = Arc::new(Context { stampless_drained: AtomicBool::new(false) }); + let work = Arc::new(WorkStateLease { context, pinned: AtomicBool::new(false) }); let completion = Arc::new(Completion { status: Arc::new(Status), output: Output, sources: Some(Arc::new(Sources)), vm_job: Mutex::new(Some(guard)), render: Mutex::new(Some(lease)), is_compute: false, signalled: AtomicBool::new(false), accepted: AtomicBool::new(true), spared: AtomicBool::new(false), + work, result: Mutex::new(None), }); Command { completion, pin, vm } } fn firmware(pool: &Arc, commands: &[(&Command, u64)]) -> Firmware { let active = commands.iter().map(|(command, ordinal)| Active { - packet: Arc::new(Packet { completion: command.completion.clone() }), + packet: Arc::new(Packet { completion: command.completion.clone(), context: command.completion.work.context.clone() }), ticket: Ticket { ordinal: *ordinal }, - context_update: false, stamps_owed: false, failed: false, flist_completed: false, drained_result: None, + context_update: false, stamps_owed: false, stamps_owed_work: None, failed: false, flist_completed: false, drained_result: None, }).collect(); let pair = Pair { quarantined: false, active: Ring(active), terminal: None, memory: Memory { retired: Vec::new() }, drain_failures: 0, drain_retry_at: 0, guilty_released: false, slot: 0 }; - Firmware { queues: Queues { admission: pool.clone() }, pair: Some(Box::new(pair)), host: FakeHost { drained: false } } + Firmware { queues: Queues { admission: pool.clone() }, pair: Some(Box::new(pair)), host: FakeHost { drained: false, stamps: [0, 0] } } } fn batch() -> DeferredBatch { DeferredBatch { values: Vec::new() } } /// retire_front_command's stampless branch: the front retires on its pass record. fn stampless_retirement(firmware: &mut Firmware, deferred: &mut DeferredBatch) { let front = firmware.pair.as_mut().unwrap().active.front_mut().unwrap(); front.flist_completed = true; + front.stamps_owed_work = Some(front.packet.completion.work_state().unwrap()); deferred.push(Deferred::Retired(front.packet.completion.clone(), Ok(TICKS))).unwrap(); front.stamps_owed = true; } @@ -419,6 +450,10 @@ def fixture(): pool.release_owner(OWNER); firmware.host.drained = true; firmware.release_drained_render(usize::from(slot), &mut deferred).unwrap(); + assert!(command.completion.work.pinned.load(Ordering::Acquire), + "pair-wide drain pins the stampless work-state lease against same-context reuse"); + assert!(command.completion.work.context.stampless_drained.load(Ordering::Acquire), + "pair-wide drain marks the context stampless-drained for cross-context retention"); assert!(quarantined(&pool, slot), "a lease of the slot is still held"); assert_ne!(pool.state.lock().drained & bit(slot), 0); deferred.finish(); @@ -470,10 +505,32 @@ def fixture(): assert!(!quarantined(&pool, slot)); } +/// A drain whose stamps already cover the group does not pin its work-state slot. +fn stamped_drain_does_not_pin() { + let pool = pool(); + let command = command(&pool, lease(&pool, OWNER)); + let slot = command.completion.render.lock().as_ref().unwrap().slot(); + let mut firmware = firmware(&pool, &[(&command, 413)]); + let mut deferred = batch(); + stampless_retirement(&mut firmware, &mut deferred); + quarantine(&mut firmware, ETIMEDOUT, &mut deferred); + pool.release_owner(OWNER); + firmware.host.drained = true; + firmware.host.stamps = [414, 414]; + firmware.release_drained_render(usize::from(slot), &mut deferred).unwrap(); + assert!(!command.completion.work.pinned.load(Ordering::Acquire), + "covering stamps prove cache writeback; do not pin innocent work-state slots"); + assert!(!command.completion.work.context.stampless_drained.load(Ordering::Acquire), + "covering stamps do not mark the context stampless-drained"); + deferred.finish(); + assert!(!quarantined(&pool, slot)); +} + fn main() { watchdog_expiry(); drained_command(); witness_before_the_retirement(); + stamped_drain_does_not_pin(); failure_after_the_witness(); unquarantined_witness(); // The KUnit case of the same rule. diff --git a/tools/asahi/g17-render-owed-stamp-tests.py b/tools/asahi/g17-render-owed-stamp-tests.py index 7eda3d1bc5c07..34c7079e152b4 100755 --- a/tools/asahi/g17-render-owed-stamp-tests.py +++ b/tools/asahi/g17-render-owed-stamp-tests.py @@ -260,6 +260,9 @@ def fixture(): mod g17 { pub(crate) fn now_ns() -> u64 { crate::now_ns() } + pub(crate) mod context { + pub(crate) type WorkStateLease = crate::WorkState; + } pub(crate) mod pairs { pub(crate) fn render_heavy_run(run: u8, _start: u64, _end: u64) -> u8 { run } pub(crate) fn sustained(_run: u8) -> bool { false } @@ -323,6 +326,7 @@ def fixture(): pub struct WorkState { drained: Cell } impl WorkState { fn drained(&self) -> Result { Ok(self.drained.get()) } + fn pin_until_stop(&self) {} } /// The admission record of a render: which transitions it saw, each under the render lock. @@ -343,7 +347,7 @@ def fixture(): status: Arc, render: RenderSlot, slot: Cell>, - work: WorkState, + work: Arc, class: Cell>, interrupted: Cell, blamed: Cell, @@ -360,7 +364,7 @@ def fixture(): status, render: RenderSlot(RefCell::new(Some(RenderLease::default()))), slot: Cell::new(Some(slot)), - work: WorkState { drained: Cell::new(drained) }, + work: Arc::new(WorkState { drained: Cell::new(drained) }), class: Cell::new(None), interrupted: Cell::new(false), blamed: Cell::new(false), @@ -374,7 +378,7 @@ def fixture(): } fn status(&self) -> &Arc { &self.status } fn render_slot(&self) -> Option { self.slot.get() } - fn work_state(&self) -> Result<&WorkState> { Ok(&self.work) } + fn work_state(&self) -> Result> { Ok(self.work.clone()) } fn spared(&self) -> bool { self.class.get() == Some(recovery::Class::Spared) } fn guilty(&self) -> bool { self.class.get() == Some(recovery::Class::Guilty) } fn class(&self) -> Option { self.class.get() } @@ -448,6 +452,7 @@ def fixture(): fn vm(&self) -> &Vm { &self.vm } // No closed failed context awaits its kill in these cases (`Context::kill_pending`). fn kill_pending(&self) -> bool { false } + fn note_stampless_drain(&self) {} fn id(&self) -> u32 { self.id } } @@ -907,6 +912,7 @@ def fixture(): abandoned_since: None, stamp_wait_since: None, stamps_owed: false, + stamps_owed_work: None, }).ok().unwrap(); packet } @@ -1683,7 +1689,8 @@ def fixture(): ' if at != 0 {\n return Ok(false);\n }'), ], 'retire-pops-behind-owed': [ - (' if stampless || at != 0 {', ' if stampless {'), + (' if stampless || at != 0 {\n // The pass record is no witness', + ' if stampless {\n // The pass record is no witness'), ], 'retire-observed-rejects-step': [ (' if at == 0 && observed.as_ref().is_some_and(|observed| observed.ticket != front.ticket)', diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a6848561d62a7..ad46a97be79c4 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -618,10 +618,15 @@ 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', 'm5-cached-queue-records', - 'uncached-g17p-queue-records', 'rebound-work-slot', 'retarget-same-vm', - 'unbound-channel', 'uncached-g17p-nodes', 'defer-unexposed', - 'unexposed-head'), []), + 'reuse-killed-work-state', 'reuse-stampless-drained-work-state', + 'reuse-failed-work-state', 'drop-stampless-work-lease', + 'drop-stampless-drain-pin', 'same-context-reuse-pinned-slot', + 'used-pin-first', 'used-pin-first-shared', + 'reuse-recycled-descriptor-ring', 'uncached-nodes', + 'm5-cached-descriptors', 'cached-scheduler', + 'm5-cached-queue-records', 'uncached-g17p-queue-records', + 'rebound-work-slot', 'retarget-same-vm', 'unbound-channel', + 'defer-unexposed', 'unexposed-head'), []), 'g17-output-fence-tests.py': [([], PASS)] + mutations('--mutation', ('unlocked-member-done', 'set-error-when-signalled', 'check-outside-lock'), []),