diff --git a/drivers/gpu/drm/asahi/g17/context.rs b/drivers/gpu/drm/asahi/g17/context.rs index 75d0b5990eb37..47a7c048dd86a 100644 --- a/drivers/gpu/drm/asahi/g17/context.rs +++ b/drivers/gpu/drm/asahi/g17/context.rs @@ -199,6 +199,56 @@ pub(crate) struct FirmwarePages { /// The queue record still names the context's execution identity and QoS ID. _hold: Arc, _qos: Arc, + /// The context's [`Kill`], so that a queue it was detached from still sees a kill of it that + /// the firmware has not finished ([`Self::kill_unfinished`]). + kill: Arc, +} + +impl FirmwarePages { + /// As [`Context::kill_unfinished`], for the context these pages belong to. + pub(crate) fn kill_unfinished(&self) -> bool { + self.kill.unfinished() + } + /// As [`Context::acknowledge_kill`]. + pub(crate) fn acknowledge_kill(&self, cookie: u64) { + self.kill.acknowledge(cookie) + } +} + +/// A context's kill: the cookie of its published ContextKill (0 before; cookies start at 1), and +/// whether the firmware acknowledged that cookie (`Event::ContextKilled`). A context is killed +/// at most once. +pub(crate) struct Kill { + cookie: AtomicU64, + acknowledged: AtomicBool, +} + +impl Kill { + fn new() -> Self { + Self { cookie: AtomicU64::new(0), acknowledged: AtomicBool::new(false) } + } + fn publish(&self, cookie: u64) { + self.cookie.store(cookie, Ordering::Release); + } + fn published(&self) -> bool { + self.cookie.load(Ordering::Acquire) != 0 + } + /// The firmware acknowledged ContextKill `cookie`: this kill is finished if it is this one. + fn acknowledge(&self, cookie: u64) { + if cookie != 0 && self.cookie.load(Ordering::Acquire) == cookie { + self.acknowledged.store(true, Ordering::Release); + } + } + /// Published, and the firmware has not acknowledged it. The scheduler page's killed word is + /// no witness of this kill: on the M4 Pro (25G83) it read set 4 us after a kill was + /// published, in the same host pass, before the host could have seen its acknowledgement. + fn unfinished(&self) -> bool { + self.published() && !self.acknowledged.load(Ordering::Acquire) + } + /// Published, and the firmware acknowledged it. + fn finished(&self) -> bool { + self.published() && self.acknowledged.load(Ordering::Acquire) + } } pub(crate) struct Context { @@ -211,9 +261,9 @@ pub(crate) struct Context { scheduler: Arc, scheduler_generation: u32, published: AtomicBool, - /// A kill of this context was published, through a compute queue or on its render pairs' - /// behalf. A context is killed at most once. - kill_published: AtomicBool, + /// 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, /// 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, @@ -371,6 +421,7 @@ impl Context { Arc::pin_init(new_mutex!(render_id, "G17 context render pool identity"), GFP_KERNEL)?; let order = Arc::pin_init(new_mutex!(Order::new(), "G17 context admission order"), GFP_KERNEL)?; + let kill = Arc::new(Kill::new(), GFP_KERNEL)?; let order_wait = Arc::pin_init(new_condvar!("G17 context admission order wait"), GFP_KERNEL)?; Ok(Self { @@ -381,7 +432,7 @@ impl Context { scheduler, scheduler_generation, published: AtomicBool::new(false), - kill_published: AtomicBool::new(false), + kill, kill_seen: AtomicU64::new(u64::MAX), closed_generation: AtomicU64::new(u64::MAX), closed_for_open_client: AtomicBool::new(false), @@ -551,6 +602,7 @@ impl Context { _work: self.work.clone(), _hold: self.hold.clone(), _qos: self.qos.clone(), + kill: self.kill.clone(), } } /// Called once the firmware consumed this context's scheduler release. If its work list @@ -610,14 +662,35 @@ impl Context { Ok(head) } - /// Record that a kill of this context was published (see `kill_published`). - pub(crate) fn note_kill_published(&self) { - self.kill_published.store(true, Ordering::Release); + /// Record that the kill of this context, ContextKill `cookie`, was published. + pub(crate) fn note_kill_published(&self, cookie: u64) { + self.kill.publish(cookie); } /// A kill of this context was published. pub(crate) fn kill_published(&self) -> bool { - self.kill_published.load(Ordering::Acquire) + self.kill.published() + } + + /// The firmware acknowledged ContextKill `cookie` (`Event::ContextKilled`); a no-op unless it + /// is this context's kill. + pub(crate) fn acknowledge_kill(&self, cookie: u64) { + self.kill.acknowledge(cookie) + } + + /// A kill of this context was published and the firmware has not acknowledged it yet. The + /// firmware handles a kill after its publication and walks the context's queues meanwhile, + /// so none of them may have its pool released before then (`compute::Queue::vacate_candidate`). + pub(crate) fn kill_unfinished(&self) -> bool { + self.kill.unfinished() + } + + /// A kill of this context was published and the firmware acknowledged it (its own + /// ContextKilled event). The scheduler page's killed word does not prove this kill finished. + // No caller yet: for ending a closed context's pending kill on its acknowledgement. + #[allow(dead_code)] + pub(crate) fn kill_acknowledged(&self) -> bool { + self.kill.finished() } /// This context's queue closed at the host's recovery `generation`, under the device mutex: diff --git a/drivers/gpu/drm/asahi/g17/queue/compute.rs b/drivers/gpu/drm/asahi/g17/queue/compute.rs index 0b26a25b36f11..114b2e5a067db 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute.rs @@ -2054,6 +2054,15 @@ impl Queue { // Borrow acquisition is serialized by the device mutex. Avoid // touching the separate loan counter for an otherwise busy queue. && !self.source_hint.has_readers(&self.source_readers) + // A successor of the same VM would take this pool without a release while the + // firmware still walks the killed context's queues (see `vacate_candidate`). + && !self.kill_unfinished() + } + /// The context this queue's record names has a kill published that the firmware has not + /// finished, whether its owner is still bound or exited and left only its pages. + fn kill_unfinished(&self) -> bool { + self.context().is_some_and(|context| context.kill_unfinished()) + || self.retained_owner.as_ref().is_some_and(|pages| pages.kill_unfinished()) } pub(crate) fn bind_owner(&mut self, owner: u64, context: Arc) -> Result { self.bind_owner_channel(owner, context, 0) @@ -2257,11 +2266,19 @@ impl Queue { }) } /// An idle retained queue whose USC backing may be given back. + /// + /// Never while the context this queue's record names has a kill published that the firmware + /// has not finished, whether its owner is still bound or exited and left only its pages. The + /// firmware handles a kill after its publication and walks the context's queues meanwhile; + /// an idle one is no exit candidate, so no kill marks it. When its FreeListRelease went out + /// within about 2 ms of the kill, the M4 Pro firmware crashed in agx_scheduler handling the + /// kill (2026-11-29 and the earlier crashes on that path). pub(crate) fn vacate_candidate(&self) -> bool { self.pool_phase == PoolPhase::Populated && self.pool.populated() && (self.reusable() || self.recycled_pending()) && !self.source_hint.has_readers(&self.source_readers) + && !self.kill_unfinished() } /// A recycled killed queue still holding the backing its killed work used. pub(crate) fn recycled_pending(&self) -> bool { diff --git a/drivers/gpu/drm/asahi/g17/queue/compute/exit.rs b/drivers/gpu/drm/asahi/g17/queue/compute/exit.rs index 04bbd8cfb2313..ee41bce9ca2ef 100644 --- a/drivers/gpu/drm/asahi/g17/queue/compute/exit.rs +++ b/drivers/gpu/drm/asahi/g17/queue/compute/exit.rs @@ -230,6 +230,17 @@ impl Queue { && now.saturating_sub(exit.announced.unwrap_or(exit.published)) < POLL_NS }) } + /// The firmware acknowledged ContextKill `cookie`. If it is the kill of the context this + /// queue's record names, bound or retained after its owner exited, that kill is finished + /// (`Context::kill_unfinished`): every kill's acknowledgement passes every compute queue. + pub(crate) fn acknowledge_context_kill(&self, cookie: u64) { + if let Some(context) = self.context() { + context.acknowledge_kill(cookie); + } + if let Some(pages) = &self.retained_owner { + pages.acknowledge_kill(cookie); + } + } /// Event consumption and record_exit are serialized by the device mutex. /// A kill pins this exact queue transaction through its final witness; /// duplicate, unknown and terminal cookies cannot acknowledge another owner. diff --git a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs index e4fa40ed22f8c..735fa893a0076 100644 --- a/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs +++ b/drivers/gpu/drm/asahi/g17/runtime/compute_exit.rs @@ -179,6 +179,7 @@ impl super::Registry { let mut matched = false; for entry in self.compute.iter_mut().flatten() { if let Some(mut queue) = entry.queue.as_deref_mut() { + queue.acknowledge_context_kill(cookie); matched |= queue.acknowledge_exit(cookie); } } @@ -376,7 +377,7 @@ impl Firmware { // killed before anything below can fail. Keep the killed graph until processor // stop, and the held render identities until this context's scheduler release // is consumed or processors stop. - context.note_kill_published(); + context.note_kill_published(cookie); self.note_guilty_kill(context, hold, "compute exit"); let mut queue = self.queues.compute[index] .as_mut() @@ -603,7 +604,7 @@ impl Firmware { // Publication is irrevocable, so mark the context killed before anything below // can fail. The held pairs stay held until this context's scheduler release is // consumed (`release_killed_slots` at detach). - context.note_kill_published(); + context.note_kill_published(cookie); self.note_guilty_kill(context, hold, "render kill"); self.queues.teardown.record_render_kill(index, cookie, now)?; record_kill_wait(self.queues.teardown.take_kill_wait(index, now)); diff --git a/tools/asahi/g17-capacity-fault-tests.py b/tools/asahi/g17-capacity-fault-tests.py index a51fee042923e..c0c4ee8437dbd 100644 --- a/tools/asahi/g17-capacity-fault-tests.py +++ b/tools/asahi/g17-capacity-fault-tests.py @@ -142,6 +142,8 @@ def fixture(): channel_error: bool, heavy_run: u8, pending_failed: KVec<(u64, CompletionFence)>, } impl Queue { + // No context of these cases has a kill pending (`Queue::kill_unfinished`). + fn kill_unfinished(&self) -> bool { false } fn valid_ticket(&self, _: &Active, _: &Ticket) -> Result { Ok(()) } fn qos_owner(&self) -> u64 { 1 } fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) } diff --git a/tools/asahi/g17-growth-tests.py b/tools/asahi/g17-growth-tests.py index f763fd5b5ff80..f37dc6added6c 100644 --- a/tools/asahi/g17-growth-tests.py +++ b/tools/asahi/g17-growth-tests.py @@ -47,6 +47,7 @@ def fixture(): active:Fifo{len:0},replays:Fifo{len:0},quarantined:false,released:false,retirement_ready:true, retired_by_teardown:false,released_at:0,exit:None,needs_fresh_backing:false,source_hint:ReaderHint,source_readers:AtomicU32::new(0)}} impl Queue { + fn kill_unfinished(&self)->bool{false} fn clear_binding_note(&mut self){if self.binding_noted{if let Some(binding)=&self.binding{binding.context.note_compute_binding(false);}self.binding_noted=false;}} fn clear_owner(&mut self,stamp:bool){self.clear_binding_note();self.owner=None;self.channel_index=0;if stamp{self.released_at=now_ns();}} ''' + item(source,'pub(crate) fn release_owner(') + item(source,'pub(crate) fn reusable(') + '\n}\n' diff --git a/tools/asahi/g17-kill-vacate-tests.py b/tools/asahi/g17-kill-vacate-tests.py new file mode 100755 index 0000000000000..b4904c8f16c87 --- /dev/null +++ b/tools/asahi/g17-kill-vacate-tests.py @@ -0,0 +1,325 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""No compute pool release while the pool's context has a kill the firmware has not acknowledged. + +The production `Registry::vacate_idle_pools` (runtime.rs), the only publisher of a compute pool's +FreeListRelease, and the Queue predicates it reads (queue/compute.rs, queue/compute/exit.rs) +and the production kill state of a context and of its retained pages (context.rs), are +compiled against host stubs for the pool, the control ring and the scheduler page. +This is not GPU execution. + +Checks: +- An idle, released queue of a context whose kill is published but not yet acknowledged is not + vacated: no FreeListRelease, its pool stays populated. On the M4 Pro (2026-11-29, and every + earlier crash of the same firmware path) such a queue's release went out within ~2 ms of + the kill, and the firmware crashed handling the kill (NULL+8 in agx_scheduler). +- The same while the context's scheduler page already shows it killed: on the M4 Pro (m4.207, + 2026-11-29) the page's killed word read set 4 us after the kill was published, the firmware + had not acknowledged that kill, the pool release went out and the firmware crashed 150 ms + later. The page's word does not witness a particular kill. +- Once the firmware acknowledged the kill's own cookie, or for a context never killed, it is + vacated as before. Another cookie's acknowledgement leaves it held. The acknowledgement + reaches a detached queue through the pages it retained. +- Source rules: every ContextKill the runtime publishes (compute exit, which carries exit, + guilty and compute-exit kills, and the render-only kill) marks its context's kill published + with its cookie right after publication, so every kill route reaches this gate; and the + kill acknowledgement (`acknowledge_compute_exit`) passes every compute queue's context. +""" +from pathlib import Path +import argparse +import os +import re +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi/g17' + + +def item(source, signature, after=None): + if after is not None: + source = source[source.index(after):] + assert source.count(signature) == 1, signature + start = source.index(signature) + begin = source.index('{', start) + depth, end = 1, begin + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def fixture(): + compute = (ROOT / 'queue/compute.rs').read_text() + runtime = (ROOT / 'runtime.rs').read_text() + context = (ROOT / 'context.rs').read_text() + exit = (ROOT / 'queue/compute/exit.rs').read_text() + kill = '\n'.join(item(context, name) for name in ['impl FirmwarePages {', 'pub(crate) struct Kill {', + 'impl Kill {']) + methods = '\n'.join(item(context, name, after='impl Context {') for name in [ + 'pub(crate) fn note_kill_published(', 'pub(crate) fn kill_published(&self)', + 'pub(crate) fn acknowledge_kill(', 'pub(crate) fn kill_unfinished(&self)', + 'pub(crate) fn kill_acknowledged(']) + queue = '\n'.join(item(compute, name) for name in [ + 'pub(crate) fn reusable(&self)', 'pub(crate) fn vacate_candidate(', 'pub(crate) fn recycled_pending(', + 'pub(crate) fn needs_fresh_backing(', 'pub(crate) fn released_at(', 'pub(crate) fn vacate(', + 'fn kill_unfinished(&self)']) + queue += '\n' + item(exit, 'pub(crate) fn acknowledge_context_kill(') + vacate = item(runtime, 'pub(super) fn vacate_idle_pools(').replace('pub(super) ', '') \ + .replace('super::initdata::', 'initdata::') + retry = [line for line in runtime.splitlines() if 'const POOL_RETRY_NS: u64' in line] + assert len(retry) == 1 + return r''' +#![allow(dead_code, unused_imports, unused_variables)] +use std::cell::Cell; +use std::sync::Arc; +use std::sync::atomic::{fence, AtomicBool, AtomicU32, AtomicU64, Ordering}; +type Result = std::result::Result; +const EIO: i32 = -5; +const EBUSY: i32 = -16; +const EAGAIN: i32 = -11; +const GFP_KERNEL: () = (); +struct KVec(Vec); +impl KVec { + fn with_capacity(n: usize, _: ()) -> Result { Ok(Self(Vec::with_capacity(n))) } + fn push(&mut self, v: T, _: ()) -> Result { self.0.push(v); Ok(()) } +} +impl std::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl std::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +pub mod initdata { pub struct InitData; } +mod crate_g17 { pub fn now_ns() -> u64 { 1 } } +pub mod g17 { pub fn now_ns() -> u64 { 1 } pub use super::initdata; } +macro_rules! crate_now { () => { 1 } } + +/// The scheduler page: only its killed word (State 0x34), which the gate must not read. +pub struct SchedulerStorage { killed: Cell } +pub struct Context { kill: Arc, scheduler: Arc } +impl Context { +''' + methods + r''' +} +pub struct Binding { context: Arc } +/// The pages an exited owner leaves with its detached queue. +pub struct FirmwarePages { _scheduler: Arc, kill: Arc } +''' + kill + r''' +/// The cookie of the context's kill. +const COOKIE: u64 = 7; +/// The firmware's side of the stub: the context's kill and the page. +struct Killed { context: Arc } +impl Killed { + /// The kill is published (`note_kill_published`), and, `acknowledged`, the firmware + /// acknowledged it (`acknowledge_kill`) and set the page's killed word. + fn new(published: bool, acknowledged: bool) -> Self { + let context = Arc::new(Context { kill: Arc::new(Kill::new()), + scheduler: Arc::new(SchedulerStorage { killed: Cell::new(0) }) }); + if published { + context.note_kill_published(COOKIE); + } + if acknowledged { + context.acknowledge_kill(COOKIE); + context.scheduler.killed.set(1); + } + Self { context } + } + /// The page shows the context killed, but not by this kill (set before it was published). + fn page_already_killed(self) -> Self { self.context.scheduler.killed.set(1); self } +} +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum PoolPhase { Populated, ReleaseSent(u32), Vacant } +pub struct Fifo { len: usize } +pub struct ReaderHint; +impl ReaderHint { fn has_readers(&self, count: &AtomicU32) -> bool { count.load(Ordering::Acquire) != 0 } } +pub struct Pool { pages: bool } +impl Pool { + fn populated(&self) -> bool { self.pages } + fn release_record(&self, _generation: u64) -> u64 { 0 } +} +pub enum ControlRecord { FreeListRelease(u64) } +thread_local! { static PUBLISHED: Cell = Cell::new(0); } +pub struct Rings; +impl Rings { + fn publish_control(_: &initdata::InitData, _: &ControlRecord) -> Result { + Ok(PUBLISHED.with(|p| { p.set(p.get() + 1); p.get() })) + } +} +pub struct Queue { + qid: u8, growing: bool, channel_error: bool, installed: bool, configuration: Option<()>, + pool_phase: PoolPhase, needs_fresh_backing: bool, exit: Option<()>, owner: Option, + released: bool, retirement_ready: bool, quarantined: bool, active: Fifo, replays: Fifo, + previous: Option<()>, source_hint: ReaderHint, source_readers: AtomicU32, pool: Pool, + binding: Option, released_at: u64, free_list_generation: u64, release_sent_ns: Option, + retained_owner: Option, +} +mod crate_g17_now { } +impl Queue { + fn qid(&self) -> u8 { self.qid } + fn context(&self) -> Option<&Arc> { self.binding.as_ref().map(|binding| &binding.context) } +''' + queue.replace('crate::g17::now_ns()', 'g17::now_ns()') + r''' +} +pub struct Entry { queue: Option> } +pub struct Registry { compute: Vec> } +impl Registry { +''' + '\n'.join(retry) + '\n' + vacate + r''' +} + +/// An idle queue whose owner closed, its pool still populated, bound to `context`. +fn released(qid: u8, context: &Arc) -> Queue { + released_as(qid, context, false) +} + +/// As `released`; `detached`: the owner exited and only its retained pages remain. +fn released_as(qid: u8, context: &Arc, detached: bool) -> Queue { + Queue { qid, growing: false, channel_error: false, installed: true, configuration: None, + pool_phase: PoolPhase::Populated, needs_fresh_backing: true, exit: None, owner: None, + released: true, retirement_ready: true, quarantined: false, active: Fifo { len: 0 }, + replays: Fifo { len: 0 }, previous: None, source_hint: ReaderHint, source_readers: AtomicU32::new(0), + pool: Pool { pages: true }, + binding: (!detached).then(|| Binding { context: context.clone() }), + released_at: 0, free_list_generation: 0, release_sent_ns: None, + retained_owner: detached.then(|| FirmwarePages { _scheduler: context.scheduler.clone(), + kill: context.kill.clone() }) } +} + +fn context(published: bool, acknowledged: bool) -> Arc { + Killed::new(published, acknowledged).context +} + +fn phase(registry: &Registry) -> PoolPhase { + registry.compute[0].as_ref().unwrap().queue.as_ref().unwrap().pool_phase +} + +fn main() { + let init = initdata::InitData; + // As before: a context never killed, or one whose kill the firmware acknowledged. + for (published, acknowledged) in [(false, false), (true, true)] { + let mut registry = Registry { compute: vec![Some(Entry { queue: Some(Box::new(released(64, &context(published, acknowledged)))) })] }; + assert_eq!(registry.vacate_idle_pools(&init, 0, 10, 5).unwrap().0, 1); + assert!(matches!(phase(®istry), PoolPhase::ReleaseSent(_))); + } + println!("PASS reference: an idle pool of an unkilled context, or of an acknowledged kill, is released"); + // The crash: the context's kill is published, the firmware has not acknowledged it. + let mut registry = Registry { compute: vec![Some(Entry { queue: Some(Box::new(released(64, &context(true, false)))) })] }; + let (published, _) = registry.vacate_idle_pools(&init, 0, 10, 5).unwrap(); + assert_eq!(published, 0, "a pool release went out while its context's kill was unacknowledged"); + assert_eq!(phase(®istry), PoolPhase::Populated); + // As in the gpubench crash: the client exited and its queue is detached. + let mut registry = Registry { compute: vec![Some(Entry { queue: Some(Box::new(released_as(64, &context(true, false), true))) })] }; + let (published, _) = registry.vacate_idle_pools(&init, 0, 10, 5).unwrap(); + assert_eq!(published, 0, "a detached queue's pool release went out while its context's kill was unacknowledged"); + let mut registry = Registry { compute: vec![Some(Entry { queue: Some(Box::new(released_as(64, &context(true, true), true))) })] }; + assert_eq!(registry.vacate_idle_pools(&init, 0, 10, 5).unwrap().0, 1, "an acknowledged kill holds a detached queue"); + println!("PASS kill outstanding: no pool release while the context's kill is unacknowledged, bound or detached"); + // m4.207: the page already shows the context killed, but the firmware has not acknowledged + // this kill. Bound and detached. + for detached in [false, true] { + let killed = Killed::new(true, false).page_already_killed(); + let mut registry = Registry { compute: vec![Some(Entry { queue: Some(Box::new(released_as(64, &killed.context, detached))) })] }; + let (published, _) = registry.vacate_idle_pools(&init, 0, 10, 5).unwrap(); + assert_eq!(published, 0, "a pool release went out on the page's killed word before the kill's acknowledgement (detached {detached})"); + } + println!("PASS page already killed: the scheduler page's killed word does not stand in for the kill's acknowledgement"); + // The acknowledgement reaches the queue (`acknowledge_compute_exit` passes every compute + // queue): another kill's cookie leaves the pool held, this kill's releases it. + for detached in [false, true] { + let killed = Killed::new(true, false).page_already_killed(); + let mut registry = Registry { compute: vec![Some(Entry { queue: Some(Box::new(released_as(64, &killed.context, detached))) })] }; + registry.compute[0].as_ref().unwrap().queue.as_ref().unwrap().acknowledge_context_kill(COOKIE + 1); + assert_eq!(registry.vacate_idle_pools(&init, 0, 10, 5).unwrap().0, 0, + "another kill's acknowledgement released the pool (detached {detached})"); + registry.compute[0].as_ref().unwrap().queue.as_ref().unwrap().acknowledge_context_kill(COOKIE); + assert_eq!(registry.vacate_idle_pools(&init, 0, 10, 5).unwrap().0, 1, + "the kill's own acknowledgement did not release the pool (detached {detached})"); + } + println!("PASS acknowledged: the kill's own acknowledgement releases the pool, bound or detached; another's does not"); + // `Context::kill_acknowledged`: only a published kill that its own cookie acknowledged. + assert!(!Killed::new(false, false).context.kill_acknowledged(), "no kill counts as acknowledged"); + assert!(!Killed::new(true, false).page_already_killed().context.kill_acknowledged(), + "an unacknowledged kill counts as acknowledged on the page word"); + let other = Killed::new(true, false); + other.context.acknowledge_kill(COOKIE + 1); + assert!(!other.context.kill_acknowledged(), "another kill's acknowledgement counts"); + assert!(Killed::new(true, true).context.kill_acknowledged(), "an acknowledged kill does not count"); + println!("PASS kill acknowledged: only the kill's own acknowledgement makes it acknowledged"); + // A successor of the same VM takes a released, warm queue's pool without a release + // (`reusable`): never while the kill of the context its record names is unfinished, bound or + // detached. + let warm = |context: &Arc, detached: bool| { + let mut q = released_as(64, context, detached); + q.needs_fresh_backing = false; + q + }; + for detached in [false, true] { + assert!(warm(&context(false, false), detached).reusable(), "an unkilled context's queue was not reusable"); + assert!(!warm(&context(true, false), detached).reusable(), + "a queue was reusable while its context's kill was unacknowledged (detached {detached})"); + assert!(!warm(&Killed::new(true, false).page_already_killed().context, detached).reusable(), + "a queue was reusable on the page's killed word before the kill's acknowledgement (detached {detached})"); + assert!(warm(&context(true, true), detached).reusable(), + "a queue stayed unreusable after its context's kill was acknowledged (detached {detached})"); + } + println!("PASS rebind: no successor takes a queue while its context's kill is unfinished, bound or detached"); +} +''' + + +# Each drops part of the gate; the run must then fail. +MUTATIONS = { + # Only a bound owner's kill holds the pool: a detached queue (its owner exited) is released. + 'bound-only': (' || self.retained_owner.as_ref().is_some_and(|pages| pages.kill_unfinished())\n', ''), + # No kill holds the pool. + 'no-gate': (' self.context().is_some_and(|context| context.kill_unfinished())\n' + ' || self.retained_owner.as_ref().is_some_and(|pages| pages.kill_unfinished())\n', + ' false\n'), + # Only the pool release is gated: a same-VM successor takes the queue during the kill. + 'reuse-ungated': ("(see `vacate_candidate`).\n && !self.kill_unfinished()\n", "(see `vacate_candidate`).\n"), + # Any kill's acknowledgement finishes the context's kill. + 'any-cookie': ('if cookie != 0 && self.cookie.load(Ordering::Acquire) == cookie {', 'if cookie != 0 {'), + # The acknowledgement reaches only a bound queue's context, not a detached queue's pages. + 'bound-ack-only': (' if let Some(pages) = &self.retained_owner {\n pages.acknowledge_kill(cookie);\n }\n', ''), +} + + +def source_rules(): + """Every ContextKill publication marks its context's kill published with its cookie, and the + kill acknowledgement passes every compute queue's context before anything else.""" + control = (ROOT / 'runtime/compute_exit.rs').read_text() + sites = [m.start() for m in re.finditer(r'ControlRecord::ContextKill\(', control)] + assert len(sites) >= 2, sites + for at in sites: + rest = control[at:] + mark = rest.find('context.note_kill_published(cookie);') + # The next publication site, if any, must come after this one's mark. + later = rest.find('ControlRecord::ContextKill(', 1) + assert mark != -1 and (later == -1 or mark < later), control[at:at + 300] + ack = item(control, 'pub(super) fn acknowledge_compute_exit(') + loop = ack.index('for entry in self.compute.iter_mut().flatten() {') + assert ack.find('return') > ack.index('queue.acknowledge_context_kill(cookie);') > loop, ack + print(f'PASS source: all {len(sites)} ContextKill publications mark the kill published; every queue sees its acknowledgement') + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split('\n', 1)[0]) + ap.add_argument('--mutation', choices=sorted(MUTATIONS)) + args = ap.parse_args() + source_rules() + code = fixture() + if args.mutation: + old, new = MUTATIONS[args.mutation] + assert code.count(old) == 1, old + code = code.replace(old, new) + with tempfile.TemporaryDirectory(prefix='g17-kill-vacate-') as tmp: + path = Path(tmp) / 'vacate.rs' + path.write_text(code) + binary = path.with_suffix('') + built = subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', '-Awarnings', str(path), + '-o', str(binary)], capture_output=True, text=True) + if built.returncode: + print(built.stdout + built.stderr) + print('kill-vacate harness did not compile') + return 1 + ran = subprocess.run([str(binary)], capture_output=True, text=True) + print(ran.stdout + ran.stderr, end='') + return ran.returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/asahi/g17-m5-sibling-compute-tests.py b/tools/asahi/g17-m5-sibling-compute-tests.py index 5348ee32380c5..0d845fd203172 100755 --- a/tools/asahi/g17-m5-sibling-compute-tests.py +++ b/tools/asahi/g17-m5-sibling-compute-tests.py @@ -382,6 +382,7 @@ def build_harness(mutation=None): self.channel_index = 0; Ok(self.unpublished) }} + fn acknowledge_context_kill(&self, _cookie: u64) {{}} fn acknowledge_exit(&mut self, cookie: u64) -> bool {{ if self.exit_cookie == Some(cookie) {{ self.exit_acked = true; diff --git a/tools/asahi/g17-m5-sibling-rearm-tests.py b/tools/asahi/g17-m5-sibling-rearm-tests.py index f690f4473cd17..ecc40cca1f85b 100755 --- a/tools/asahi/g17-m5-sibling-rearm-tests.py +++ b/tools/asahi/g17-m5-sibling-rearm-tests.py @@ -275,7 +275,11 @@ def build(mutation=None): fn new(id: u32, vm: u32) -> Arc { Arc::new(Self { id, vm: Vm(vm), current: true }) } fn vm(&self) -> &Vm { &self.vm } fn is_current(&self) -> bool { self.current } + fn kill_unfinished(&self) -> bool { false } } +/// The pages an exited owner leaves with its detached queue. +pub struct FirmwarePages; +impl FirmwarePages { fn kill_unfinished(&self) -> bool { false } } #[derive(Debug)] pub struct Pages(u32); @@ -326,10 +330,12 @@ def build(mutation=None): previous: Option<()>, source_hint: SourceHint, source_readers: AtomicU32, rearm_for: Option, pool: Pool, graph: Graph, binding: Option, release_sent_ns: Option, free_list_generation: u64, released_at: u64, claims: u32, awaiting_witness: bool, - channel_index: u8, sustained: bool, + channel_index: u8, sustained: bool, retained_owner: Option, } impl Queue { @@QUEUE@@ + // No context of these cases has a kill pending (`Queue::kill_unfinished`). + fn kill_unfinished(&self) -> bool { false } fn qid(&self) -> u8 { self.qid } fn sustained(&self) -> bool { self.sustained } /// The production entry check of bind_owner_channel(); the views of the new VM are not modelled. @@ -405,7 +411,7 @@ def build(mutation=None): graph: Graph { ring: Some(DescriptorRing), m5: true }, binding: Some(Binding { context: context.clone(), pool_alias: None, descriptors: None }), release_sent_ns: None, free_list_generation: 1, released_at: 0, claims: 0, awaiting_witness: false, - channel_index: 0, sustained: true, + channel_index: 0, sustained: true, retained_owner: None, } } /// An idle queue whose owner released it at `released_at`; its pool still serves `vm`. diff --git a/tools/asahi/g17-object-fence-tests.py b/tools/asahi/g17-object-fence-tests.py index 87c2396c1dcd5..960bfb8afb883 100644 --- a/tools/asahi/g17-object-fence-tests.py +++ b/tools/asahi/g17-object-fence-tests.py @@ -828,6 +828,7 @@ def context_source(text): pub mod mmu { pub struct ContextHold; } pub struct QosLease; pub struct WorkStorage { pub object: PooledObject } + pub struct Kill; @PAGES@ pub struct Context { work: Arc>, @@ -837,6 +838,7 @@ def context_source(text): scheduler: Arc, hold: Arc, qos: Arc, + kill: Arc, /// The work-list head the firmware left. head: Cell<[u64; 2]>, } @@ -857,7 +859,7 @@ def context_source(text): let (id, work_base, work_mark) = (object.id, object.gpu_va(), object.return_mark()); 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), + scheduler: Arc::new(SchedulerStorage), hold: Arc::new(mmu::ContextHold), qos: Arc::new(QosLease), kill: Arc::new(Kill), head: Cell::new([0, work_base + (UAT_PGSZ + 0x400) as u64]), }); (context, id) diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index ec411fc648a87..ec0548228c3af 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -448,6 +448,8 @@ def mutations(flag, names, base, expect=KILL): + mutations('--mutation', ('queue-under-lock', 'binding-under-lock', 'drain-under-lock', 'drain-local-on-eagain', 'finish-stops-at-error', 'early-return-skips-finish', 'overwrite-full'), []), + 'g17-kill-vacate-tests.py': [([], PASS)] + + mutations('--mutation', ('bound-only', 'no-gate', 'any-cookie', 'bound-ack-only', 'reuse-ungated'), []), 'g17-kill-route-tests.py': [([], PASS)] + mutations('--mutation', ('no-executed-route', 'no-executed-input', 'kill-twice', 'executed-on-m5', 'unsafe-wait', 'guilty-waits-delay', 'no-guilty-input', 'owed-blocks-kill',