From f8a66712676000fc5073343deba301770483eb2d Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:34:15 +1100 Subject: [PATCH 1/3] drm/asahi: m5: clear pool storage before handing the job to another VM The M5 backend has one render pair and one compute queue for all clients. When a submission comes from a VM other than the current owner, rebind_vm() maps the retained USC pool, parameter buffer and compute storage into the new VM at the same addresses. Their contents were left as the previous VM's work wrote them. Zero the data storage before another VM maps it: the USC blocks, the parameter-buffer blocks, scene scratch and discard page, and the compute operand, preemption and robustness storage. rebind_vm() only runs once the pair has fully retired, and submissions are synchronous, so no work still uses the memory. Construction leaves the same storage zeroed. The USC directory and free list, the page list and the metrics are allocator and parameter-manager state that the retained firmware records and cursors refer to. They are kept unchanged. A same-VM resubmission does not clear anything. Add a host test that runs the production hand-over against mocks and checks every data object is zero when the next VM maps it, with the previous code and each clear removed as mutants. Signed-off-by: Ryan Murray --- .../drm/asahi/m5/resources/graphics_job.rs | 12 +- .../drm/asahi/m5/resources/graphics_usc.rs | 10 +- .../asahi/m5/resources/parameter_buffer.rs | 11 +- tools/asahi/m5-client-handoff-tests.py | 273 ++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 5 files changed, 303 insertions(+), 4 deletions(-) create mode 100644 tools/asahi/m5-client-handoff-tests.py diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs index 0245811e9b5db..c21d700c8ef36 100644 --- a/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_job.rs @@ -8,6 +8,7 @@ use super::parameter_buffer::{M5ParameterBuffer, BLOCK_BYTES, PAGE_LIST_BYTES, P use super::target_memory::M5TargetMemory; use crate::{driver::AsahiDrmDevice, m5::render_desc, m5::render, mmu}; use crate::m5::completion::MAX_GRAPHICS_GENERATION; +use core::sync::atomic::{fence, Ordering}; use kernel::prelude::*; const HIGH: u64 = 0xffff_fc20_c100_0000; @@ -271,8 +272,9 @@ impl M5GraphicsJob { /// for the new VM and the pools are aliased into it. The previous VM's /// render targets are not used in the new VM: they stay cached under the /// previous VM for its next turn, and the next application frame takes or - /// allocates targets in the new VM. The caller publishes the new roots - /// before the next draw. + /// allocates targets in the new VM. Pool data storage is cleared before + /// the new VM maps it; allocator and parameter-manager state is kept. The + /// caller publishes the new roots before the next draw. pub(super) fn rebind_vm(&mut self, dev: &AsahiDrmDevice, vm: &mmu::Vm) -> Result { if self.owns_vm(vm) { return Ok(()); } if self.scheduler_status()? != [2, 0] { return Err(EBUSY); } @@ -286,6 +288,12 @@ impl M5GraphicsJob { for alias in self.parameter_buffer.alias_into(vm)? { aliases.push(alias, GFP_KERNEL)?; } + // Compute operands and the preemption page released by the previous + // VM may still hold its data; clear them, and restore the zero + // robustness page, before another VM maps them. + self.compute_storage.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + // Order the clears before the new roots and the next draw are published. + fence(Ordering::SeqCst); let storage = self.compute_storage.iova(); if let Some(alias) = self.compute_storage.map_alias_at_with_guards( vm, storage, mmu::PROT_GPU_SHARED_RW, 2)? { diff --git a/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs index 1d5bd727ee719..867ef48a34606 100644 --- a/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs +++ b/drivers/gpu/drm/asahi/m5/resources/graphics_usc.rs @@ -110,9 +110,17 @@ impl M5GraphicsUsc { /// addresses, reproducing each allocation's guard reservation, so every /// firmware record naming the directory, free list or blocks stays valid /// across a render client handoff. The returned aliases must be kept for - /// as long as that VM may submit. + /// as long as that VM may submit. The caller has verified that all work + /// using the pool has retired. pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { let range = crate::m5::vm_layout::auxiliary_range(&vm.kernel_range()).ok_or(EINVAL)?; + // Blocks released by the previous VM may still hold its shader stack + // and spill data; clear them before another VM maps them. The + // directory and free list are allocator state that the firmware's + // cursors refer to, so they are kept (see below). + for block in self.blocks.iter_mut() { + block.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + } let mut aliases = KVec::new(); let alias = |object: &mut MappedObject, size: usize, guards: usize, aliases: &mut KVec| -> Result { diff --git a/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs index 3c6b955b6c799..901c099eac795 100644 --- a/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs +++ b/drivers/gpu/drm/asahi/m5/resources/parameter_buffer.rs @@ -90,9 +90,18 @@ impl M5ParameterBuffer { /// Map the retained pool into another application VM at the same compact /// addresses with the original two-page guard reservations, so the /// firmware's parameter-manager records keep naming valid pages after a - /// render client handoff. + /// render client handoff. The caller has verified that all work using + /// the pool has retired. pub(super) fn alias_into(&mut self, vm: &mmu::Vm) -> Result> { let range = vm_layout::compact_range(&vm.kernel_range()).ok_or(EINVAL)?; + // Blocks, scene scratch and the discard page released by the previous + // VM may still hold its scene data; clear them before another VM maps + // them. The page list and metrics are parameter-manager state named + // by the retained firmware records and are kept. + for object in Iterator::chain(self.blocks.iter_mut(), + [&mut self.scene_scratch, &mut self.discard]) { + object.with_bytes_mut(|out| { out.fill(0); Ok(()) })?; + } let mut aliases = KVec::new(); let alias = |object: &mut MappedObject, aliases: &mut KVec| -> Result { let end = object.iova() diff --git a/tools/asahi/m5-client-handoff-tests.py b/tools/asahi/m5-client-handoff-tests.py new file mode 100644 index 0000000000000..0ebd1c116441d --- /dev/null +++ b/tools/asahi/m5-client-handoff-tests.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Compile the production M5 render-job handoff with mock mappings. + +M5GraphicsJob::rebind_vm, M5GraphicsMemory::rebind and both pools' +alias_into must clear the data storage the previous VM used (USC blocks, +parameter-buffer blocks, scene scratch, discard page, compute storage) before +another VM maps it, keep the allocator and parameter-manager state the +firmware refers to (USC directory and free list, page list, metrics), clear +nothing for a same-VM resubmission and nothing before full retirement. + +--mutations also runs the unfixed source and each clear removed; every one +must be killed. +""" +from pathlib import Path +import os +import subprocess +import sys +import tempfile + +LINUX = Path(__file__).resolve().parents[2] +RESOURCES = 'drivers/gpu/drm/asahi/m5/resources/' +FILES = {'usc': 'graphics_usc.rs', 'pb': 'parameter_buffer.rs', + 'memory': 'graphics_memory.rs', 'job': 'graphics_job.rs'} +BASE = 'c5e25e0925351' + + +def item(source, 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].replace('pub(super) ', '') + + +def current(): + return {key: (LINUX / RESOURCES / name).read_text() for key, name in FILES.items()} + + +def original(): + return {key: subprocess.run(['git', '-C', str(LINUX), 'show', f'{BASE}:{RESOURCES}{name}'], + check=True, capture_output=True, text=True).stdout + for key, name in FILES.items()} + + +PRELUDE = r''' +#![allow(warnings)] +use std::cell::RefCell; +use std::sync::atomic::{fence, Ordering}; +type Error = i32; +type Result = core::result::Result; +const EINVAL: i32 = -22; const EOVERFLOW: i32 = -75; const ERANGE: i32 = -34; +const EFAULT: i32 = -14; const EBUSY: i32 = -16; const ENOTSUPP: i32 = -524; +const GFP_KERNEL: () = (); +macro_rules! dev_dbg { ($($t:tt)*) => {} } +struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn push(&mut self, value: T, _: ()) -> Result { self.0.push(value); Ok(()) } +} +impl core::ops::Deref for KVec { type Target = Vec; fn deref(&self) -> &Vec { &self.0 } } +impl core::ops::DerefMut for KVec { fn deref_mut(&mut self) -> &mut Vec { &mut self.0 } } +impl IntoIterator for KVec { + type Item = T; type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } +} +mod mmu { + pub type Prot = u32; + pub const PROT_GPU_SHARED_RW: Prot = 3; + pub const UAT_PGSZ: usize = 0x4000; + pub struct KernelMapping(pub &'static str, pub u64); + pub struct VmJobGuard(pub u64); + #[derive(Clone)] + pub struct Vm(pub u64); + impl Vm { + pub fn id(&self) -> u64 { self.0 } + pub fn kernel_range(&self) -> core::ops::Range { 0x10_0000_0000..0x20_0000_0000 } + pub fn retain_job(&self) -> super::Result { Ok(VmJobGuard(self.0)) } + } + pub struct M5ExecutionContext { pub vm: Vm } + impl M5ExecutionContext { + pub fn rebind(&mut self, vm: &Vm) -> super::Result { self.vm = vm.clone(); Ok(()) } + pub fn vm(&self) -> &Vm { &self.vm } + pub fn context_id(&self) -> u8 { 3 } + pub fn roots(&self) -> [u64; 2] { [0, 0] } + } +} +mod m5 { pub mod vm_layout { + pub fn compact_range(r: &core::ops::Range) -> Option> { Some(r.clone()) } + pub fn auxiliary_range(r: &core::ops::Range) -> Option> { Some(r.clone()) } +} } +use m5::vm_layout; +struct AsahiDrmDevice; +impl AsahiDrmDevice { fn as_ref(&self) -> &Self { self } } +thread_local! { static MAPS: RefCell> = RefCell::new(Vec::new()); } +struct MappedObject { name: &'static str, bytes: Vec, iova: u64, logical_size: usize, home: u64 } +impl MappedObject { + fn new(name: &'static str, iova: u64, logical_size: usize) -> Self { + Self { name, bytes: vec![0; 256], iova, logical_size, home: 1 } + } + fn iova(&self) -> u64 { self.iova } + fn with_bytes_mut(&mut self, f: impl FnOnce(&mut [u8]) -> Result) -> Result { f(&mut self.bytes) } + fn map_alias_at_with_guards(&mut self, vm: &mmu::Vm, address: u64, _: mmu::Prot, _: usize) + -> Result> { + let zero = self.bytes.iter().all(|b| *b == 0); + MAPS.with(|m| m.borrow_mut().push((self.name, vm.id(), zero))); + if vm.id() == self.home { return if address == self.iova { Ok(None) } else { Err(EINVAL) }; } + Ok(Some(mmu::KernelMapping(self.name, vm.id()))) + } +} +// graphics_usc.rs +const DIRECTORY_ENTRIES: usize = 0x80000; +const BLOCK_BYTES: usize = 0x20_0000; +const BLOCK_COUNT: usize = 19; +struct M5GraphicsUsc { directory: MappedObject, freelist: MappedObject, blocks: KVec } +impl M5GraphicsUsc { + fn validate_mappings(&self, _: &mmu::Vm) -> Result { Ok(()) } +@@USC@@ +} +// parameter_buffer.rs +struct M5ParameterBuffer { blocks: [MappedObject; 3], page_list: MappedObject, metrics: MappedObject, + scene_scratch: MappedObject, discard: MappedObject } +impl M5ParameterBuffer { + fn validate(&self, _: &mmu::Vm) -> Result { Ok(()) } +@@PB@@ +} +// graphics_memory.rs +struct M5GraphicsMemory { context: mmu::M5ExecutionContext, user_mappings: Option, + pages: KVec, usc: M5GraphicsUsc, output_first: Option } +impl M5GraphicsMemory { + fn vm(&self) -> &mmu::Vm { self.context.vm() } +@@MEMORY@@ +} +// graphics_job.rs +struct M5GraphicsJob { program: M5GraphicsMemory, parameter_buffer: M5ParameterBuffer, + compute_storage: MappedObject, vm_aliases: KVec, generation: u32, + status: [u32; 2], stamps: [u32; 5] } +impl M5GraphicsJob { + fn scheduler_status(&mut self) -> Result<[u32; 2]> { Ok(self.status) } + fn progress(&mut self) -> Result<[u32; 5]> { Ok(self.stamps) } +@@OWNS@@ +@@JOB@@ +} +const DATA: [&str; 25] = ["usc0", "usc1", "usc2", "usc3", "usc4", "usc5", "usc6", "usc7", "usc8", + "usc9", "usc10", "usc11", "usc12", "usc13", "usc14", "usc15", "usc16", "usc17", "usc18", + "pb0", "pb1", "pb2", "scene", "discard", "compute"]; +const KEPT: [&str; 4] = ["directory", "freelist", "page_list", "metrics"]; +fn objects(job: &mut M5GraphicsJob) -> Vec<&mut MappedObject> { + let usc = &mut job.program.usc; + let pb = &mut job.parameter_buffer; + let mut out: Vec<&mut MappedObject> = vec![&mut usc.directory, &mut usc.freelist]; + out.extend(usc.blocks.0.iter_mut()); + out.extend(pb.blocks.iter_mut()); + out.extend([&mut pb.page_list, &mut pb.metrics, &mut pb.scene_scratch, &mut pb.discard, + &mut job.compute_storage]); + out +} +fn fill(job: &mut M5GraphicsJob, value: u8) { + for object in objects(job) { object.bytes.fill(value); } +} +fn snapshot(job: &mut M5GraphicsJob) -> Vec<(&'static str, Vec)> { + objects(job).into_iter().map(|o| (o.name, o.bytes.clone())).collect() +} +fn handoff(job: &mut M5GraphicsJob, vm: u64, value: u8) { + MAPS.with(|m| m.borrow_mut().clear()); + fill(job, value); + job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(vm)).unwrap(); + let maps = MAPS.with(|m| m.borrow().clone()); + for name in DATA.iter() { + let entry = maps.iter().find(|(n, v, _)| n == name && *v == vm) + .unwrap_or_else(|| panic!("{} not mapped into vm {}", name, vm)); + assert!(entry.2, "{} still holds the previous VM data when vm {} maps it", name, vm); + } + for object in objects(job) { + if KEPT.contains(&object.name) { + assert!(object.bytes.iter().all(|b| *b == value), "{} allocator state must be kept", object.name); + } + } + assert!(job.owns_vm(&mmu::Vm(vm))); +} +fn main() { + let mut iova = 0x10_0000_0000u64; + let mut next = |size: usize| { let at = iova; iova += (size as u64 + 0xc000 + 0x7fff) & !0x7fff; at }; + let usc_blocks = (0..BLOCK_COUNT).map(|i| MappedObject::new(DATA[i], next(BLOCK_BYTES), BLOCK_BYTES)).collect(); + let usc = M5GraphicsUsc { + directory: MappedObject::new("directory", next(DIRECTORY_ENTRIES * 8), DIRECTORY_ENTRIES * 8), + freelist: MappedObject::new("freelist", next(0x4000), 0x4000), blocks: KVec(usc_blocks) }; + let pb = M5ParameterBuffer { + blocks: [MappedObject::new("pb0", next(0x80000), 0x80000), MappedObject::new("pb1", next(0x80000), 0x80000), + MappedObject::new("pb2", next(0x80000), 0x80000)], + page_list: MappedObject::new("page_list", next(0x1c000), 0x1c000), + metrics: MappedObject::new("metrics", next(0x4000), 0x4000), + scene_scratch: MappedObject::new("scene", next(0x4000), 0x4000), + discard: MappedObject::new("discard", next(0x8000), 0x8000) }; + let mut job = M5GraphicsJob { + program: M5GraphicsMemory { context: mmu::M5ExecutionContext { vm: mmu::Vm(1) }, + user_mappings: None, pages: KVec::new(), usc, output_first: None }, + parameter_buffer: pb, compute_storage: MappedObject::new("compute", next(0x28000), 0x28000), + vm_aliases: KVec::new(), generation: 7, status: [2, 0], stamps: [2, 0x700, 0, 0x700, 0] }; + // Client 1 (first owner) hands to client 2, which hands back, then to 3. + handoff(&mut job, 2, 0xa5); + assert_eq!(job.vm_aliases.len(), DATA.len() + KEPT.len(), "views of every pool object in vm 2"); + handoff(&mut job, 1, 0x5a); + assert!(job.vm_aliases.is_empty(), "the first owner keeps its own mappings"); + handoff(&mut job, 3, 0x3c); + // Same-VM resubmission: no clear. + fill(&mut job, 0x77); + let before = snapshot(&mut job); + job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(3)).unwrap(); + assert!(before == snapshot(&mut job), "same-VM resubmission must not clear"); + // Not retired: nothing is cleared while firmware may still use the pools. + for (status, stamps) in [([1, 0], [2, 0x700, 0, 0x700, 0]), ([2, 0], [2, 0x600, 0, 0x700, 0]), + ([2, 0], [2, 0x700, 0, 0x600, 0]), ([2, 1], [2, 0x700, 0, 0x700, 0])] { + job.status = status; job.stamps = stamps; + assert_eq!(job.rebind_vm(&AsahiDrmDevice, &mmu::Vm(4)).err(), Some(EBUSY)); + assert!(before == snapshot(&mut job), "busy job storage must be untouched"); + } + println!("PASS 3 client handoffs clear 25 data objects before the next VM maps them; allocator state kept; same-VM and 4 unretired cases untouched"); +} +''' + + +def fixture(src): + return (PRELUDE.replace('@@USC@@', item(src['usc'], 'pub(super) fn alias_into(')) + .replace('@@PB@@', item(src['pb'], 'pub(super) fn alias_into(')) + .replace('@@MEMORY@@', item(src['memory'], 'pub(super) fn rebind(')) + .replace('@@OWNS@@', item(src['job'], 'pub(super) fn owns_vm(')) + .replace('@@JOB@@', item(src['job'], 'pub(super) fn rebind_vm('))) + + +def run(tmp, name, code): + path = Path(tmp) / (name + '.rs') + binary = path.with_suffix('') + path.write_text(code) + subprocess.run([os.environ.get('RUSTC', 'rustc'), '--edition=2021', str(path), '-o', str(binary)], + check=True) + return subprocess.run([str(binary)], capture_output=True, text=True) + + +def drop(src, key, text): + assert text in src[key], (key, text) + return {**src, key: src[key].replace(text, '')} + + +def main(): + src = current() + mutations = [ + ('unfixed-' + BASE, original), + ('no-usc-block-clear', lambda: drop(src, 'usc', 'block.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ('no-parameter-buffer-clear', lambda: drop(src, 'pb', 'object.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ('no-compute-storage-clear', lambda: drop(src, 'job', + 'self.compute_storage.with_bytes_mut(|out| { out.fill(0); Ok(()) })?;')), + ] + with tempfile.TemporaryDirectory(prefix='m5-client-handoff-') as tmp: + result = run(tmp, 'fixed', fixture(src)) + assert result.returncode == 0, result.stderr + print(result.stdout.strip()) + if '--mutations' not in sys.argv[1:]: + return + killed = 0 + for name, make in mutations: + result = run(tmp, name.replace('-', '_'), fixture(make())) + assert result.returncode != 0 and 'still holds the previous VM data' in result.stderr, \ + (name, result.stdout, result.stderr) + killed += 1 + print('PASS mutant killed:', name) + print(f'PASS {killed}/{len(mutations)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 1f0d5963f9290..ef6b042b17881 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -206,6 +206,7 @@ def mutations(flag, names, base, expect=KILL): 'g15-retention-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], + 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery', 'quarantine', 'epoch', 'cutoff', 'whole-batch', 'legacy-format', 'read-drain'), out()), From 01455ee8bbd3782bee57c18a01db3e04892634e0 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 09:34:59 +1100 Subject: [PATCH 2/3] drm/asahi: g18: clear client storage when the render or compute job changes VM The single application render job and the application compute job are handed from one client VM to the next by re-aliasing their objects at the same addresses. Only the render targets were cleared, so PB blocks (including grown ones), the scene scratch, the discard page and the USC scratch blocks of the render and compute pools still held what the previous VM's work left there. Once the job has retired and the previous VM's views are dropped, clear that storage before another VM maps it. Allocator structures, the PB block table, page list and ring cursors, and the pool directory, block list and descriptor are kept as they are: they hold only the owners' addresses and their cursors are owned by the PM/USC. A replacement compute pool that retains the old scratch objects inherits the last VM. The same VM again clears nothing. The job context only reads the command graph (the RCE register lists), so map the client view read-only, as g17 maps M5 command storage. Add a host test that runs the production paths against a model of the mappings, with mutants including the previous code. Signed-off-by: Ryan Murray --- drivers/gpu/drm/asahi/g18/buffer/pool.rs | 23 + .../drm/asahi/g18/buffer/pool_application.rs | 1 + .../asahi/g18/buffer/pool_shared_compute.rs | 2 + .../asahi/g18/queue/graphics_application.rs | 23 + .../g18/runtime/graphics_job_application.rs | 11 +- tools/asahi/g18-client-handoff-tests.py | 483 ++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 7 files changed, 543 insertions(+), 1 deletion(-) create mode 100644 tools/asahi/g18-client-handoff-tests.py diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool.rs b/drivers/gpu/drm/asahi/g18/buffer/pool.rs index f080fecd7afc3..2c70e112d7f97 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool.rs @@ -86,6 +86,9 @@ pub(crate) struct G18UmaPoolMemory { low_bias: u64, hardware_slot: u32, block_stride: u64, + /// The client VM an application path last aliased the scratch blocks + /// into; None before the first. + client_vm: Option, } impl G18UmaPoolMemory { @@ -109,10 +112,29 @@ impl G18UmaPoolMemory { || !self.process_aliases.is_empty() { return Err(EINVAL); } + self.clear_scratch_for(vm)?; self.alias_into_process(dev, uat, vm)?; Ok(core::mem::replace(&mut self.process_aliases, KVec::new())) } + /// The scratch blocks hold the private memory of the last client VM's + /// threads. Storage released by that VM may still hold its data; clear + /// it before another VM maps it (construction leaves it zero). The + /// directory, block list, state and descriptor are kept: they name the + /// pool's own objects and the hardware owns their allocation cursors. + /// The caller proved the pool's last job retired and dropped the + /// previous VM's aliases. The same VM again clears nothing. + fn clear_scratch_for(&mut self, vm: &mmu::Vm) -> Result { + if self.client_vm.is_some_and(|id| id != vm.id()) { + for block in self.scratch.iter_mut() { + block.with_bytes_mut(|bytes| { bytes.fill(0); Ok(()) })?; + } + fence(Ordering::SeqCst); + } + self.client_vm = Some(vm.id()); + Ok(()) + } + /// The retained backing plan; application compute bounds its SMA pair by it. pub(crate) fn scratch_plan(&self) -> Option { self.scratch_plan @@ -283,6 +305,7 @@ impl G18UmaPoolMemory { descriptor_loaded: false, render: false, low_bias, hardware_slot, block_stride: if low_bias == 0 { BLOCK_DATA_STRIDE } else { 0x300000 }, + client_vm: None, }) } diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs b/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs index 3e1e012966a0c..cd27b47a18016 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool_application.rs @@ -23,6 +23,7 @@ impl G18UmaPoolMemory { pub(crate) fn application_aliases(&mut self, uat: &mmu::Uat, vm: &mmu::Vm) -> Result> { if !self.render || self.scratch_plan.is_none() {return Err(EINVAL);} + self.clear_scratch_for(vm)?; let mut aliases=KVec::new(); for (index,page) in self.directory.iter_mut().enumerate() { let address=DIRECTORY_BASE+self.layout.page_offset(index as u32).ok_or(EINVAL)?; diff --git a/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs b/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs index f8e9a17cf7817..6540fe263cb53 100644 --- a/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs +++ b/drivers/gpu/drm/asahi/g18/buffer/pool_shared_compute.rs @@ -70,6 +70,8 @@ impl G18UmaPoolMemory { let mut pool = Self::new_layout(dev, uat, high.clone(), 12, true, false, bias, 1, G18_COMPUTE_BLOCK_BYTES)?; pool.prepare_shared_compute_retaining(dev, uat, high, plan, Some(self))?; + // The retained scratch objects carry the last client's data along. + pool.client_vm = self.client_vm; Ok(pool) } diff --git a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs index 6420db7232025..5efb185812dfd 100644 --- a/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs +++ b/drivers/gpu/drm/asahi/g18/queue/graphics_application.rs @@ -242,6 +242,29 @@ impl G18ParameterBuffer { Ok(aliases) } + /// Storage the previous VM's renders wrote (every block, grown ones + /// included, the scene scratch and the discard page) may still hold its + /// data; clear it before another VM maps it. Construction leaves it zero. + /// The page list, block table, scene records, metrics and ring cursors + /// are kept: they name the PB's own objects and the PM owns their + /// progress. The caller proved the render retired and dropped the + /// previous VM's aliases. + pub(crate) fn clear_client_data(&mut self) -> Result { + let clear = |object: &mut MappedObject| { + object.with_bytes_mut(|bytes| { + bytes.fill(0); + Ok(()) + }) + }; + for block in self.blocks.iter_mut() { + clear(block)?; + } + clear(&mut self.scene_scratch)?; + clear(&mut self.discard)?; + fence(Ordering::SeqCst); + Ok(()) + } + /// Blocks backed so far: the initial ones plus every growth. fn backed_blocks(&self) -> Result { let bytes: usize = self.blocks.iter().map(|block| block.logical_size).sum(); diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs index be1f057c31be0..61390620e20da 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs @@ -89,6 +89,10 @@ impl ApplicationJob { if remap { self.job.program.rebind_retired(&self.storage)?; self.user_aliases.clear();self.pool_aliases.clear(); + // The last frame retired (checked above) and the previous VM's + // views are gone: clear what its renders left before this VM + // maps the PB. The pool scratch is cleared as it is aliased. + if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;} } if self.generation==0 { let alias=self.job.graph.map_alias_at(uat.kernel_lower_vm(),va::GRAPHICS_JOB_LOW, @@ -110,8 +114,13 @@ impl ApplicationJob { } } if remap { + // The job context only reads the commands' register lists here + // (the RCE addresses encode_into places at GRAPHICS_JOB_LOW); + // firmware uses GRAPHICS_JOB_HIGH. The client view is read-only, + // as g17 maps M5 command storage, so the client's own GPU work + // cannot rewrite commands after the kernel encoded and audited them. self.user_aliases.push(self.job.graph.map_alias_at(vm,va::GRAPHICS_JOB_LOW, - mmu::PROT_GPU_SHARED_RW)?,GFP_KERNEL)?; + mmu::PROT_GPU_SHARED_RO)?,GFP_KERNEL)?; let aliases=self.job.parameter_buffer.application_aliases(vm)?; for alias in aliases {self.user_aliases.push(alias,GFP_KERNEL)?;} } diff --git a/tools/asahi/g18-client-handoff-tests.py b/tools/asahi/g18-client-handoff-tests.py new file mode 100644 index 0000000000000..13f55ea292f13 --- /dev/null +++ b/tools/asahi/g18-client-handoff-tests.py @@ -0,0 +1,483 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G18 client hand-over of the application render and compute owners against a model. + +The harness extracts from drivers/gpu/drm/asahi/g18 ApplicationJob and ApplicationJob::prepare() +(runtime/graphics_job_application.rs), G18ParameterBuffer::application_aliases() and +clear_client_data() (queue/graphics_application.rs), G18UmaPoolMemory::application_aliases() +(buffer/pool_application.rs), compute_application_aliases() and clear_scratch_for() +(buffer/pool.rs) and replacement_shared_compute() (buffer/pool_shared_compute.rs), and compiles +them with host rustc against a model of the GEM objects and their GPU mappings. The model's GPU +work of a VM writes the VM's id through each of its writable views of the PB blocks, scene +scratch, discard page, render targets and pool scratch blocks. + +What it shows: +- when the render job goes to another VM, no live view of that VM reaches a byte another VM + wrote, PB blocks added by growth included, and the previous VM's views are gone first; +- the same VM again, and a target regrowth of the same VM, clear nothing; +- the client view of the command graph is read-only; +- the compute pool's scratch blocks are cleared when another VM is given them, also when a + replacement pool retains the old scratch objects, and not for the same VM; +- source checks: both owners refuse a job that has not retired before any of this, the session + aliases the render pool only after prepare(), and the compute attempt drops the previous + aliases before it aliases the pool. + +--mutations runs every mutant, including the code at c5e25e0925351 (before the fix), and +requires each to fail. +""" +import argparse +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +G18 = 'drivers/gpu/drm/asahi/g18/' +PREPARE = G18 + 'runtime/graphics_job_application.rs' +PB = G18 + 'queue/graphics_application.rs' +POOL = G18 + 'buffer/pool.rs' +POOL_APP = G18 + 'buffer/pool_application.rs' +POOL_SHARED = G18 + 'buffer/pool_shared_compute.rs' +SESSION = G18 + 'boot/session.rs' +COMPUTE = G18 + 'initdata/application_compute.rs' +BASE = 'c5e25e0925351' + + +def item(source, signature, optional=False): + if optional and signature not in source: + return '' + 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] + + +MODEL = r''' +#![allow(dead_code, unused_variables, unused_mut, unused_imports)] +use std::cell::RefCell; +use std::ops::Range; +use std::rc::Rc; +use std::sync::atomic::{fence, Ordering}; +type Result = std::result::Result; +const EBUSY: i32 = 16; const EINVAL: i32 = 22; const EOVERFLOW: i32 = 75; const EFAULT: i32 = 14; +const ENOENT: i32 = 2; +#[derive(Clone, Copy)] struct Flags; +const GFP_KERNEL: Flags = Flags; +type KBox = Box; +struct KVec(Vec); +impl KVec { + fn new() -> Self { KVec(Vec::new()) } + fn push(&mut self, v: T, _: Flags) -> Result { self.0.push(v); Ok(()) } + fn clear(&mut self) { self.0.clear() } + fn len(&self) -> usize { self.0.len() } + fn is_empty(&self) -> bool { self.0.is_empty() } + fn iter(&self) -> std::slice::Iter<'_, T> { self.0.iter() } + fn iter_mut(&mut self) -> std::slice::IterMut<'_, T> { self.0.iter_mut() } +} +impl IntoIterator for KVec { + type Item = T; type IntoIter = std::vec::IntoIter; + fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } +} +#[macro_export] +macro_rules! g18_kick_info { ($($t:tt)*) => {}; } +struct AsahiDrmDevice; +impl AsahiDrmDevice { fn as_ref(&self) -> &Self { self } } + +type Data = Rc>>; +struct Live { key: usize, vm: u64, addr: u64, prot: mmu::Prot, data: Data } +thread_local! { + static LIVE: RefCell> = RefCell::new(Vec::new()); + static NEXT: RefCell = RefCell::new(0); + static CLEARS: RefCell = RefCell::new(0); +} +mod mmu { + use super::*; + #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Prot { Rw, Ro } + pub const PROT_GPU_SHARED_RW: Prot = Prot::Rw; + pub const PROT_GPU_SHARED_RO: Prot = Prot::Ro; + #[derive(Clone)] pub struct Vm { pub id: u64 } + impl Vm { + pub fn id(&self) -> u64 { self.id } + pub fn retain_t8140_job(&self) -> Result { Ok(T8140VmJobGuard) } + pub fn translate_iova(&self, a: u64) -> Result { Ok(a) } + } + pub struct T8140VmJobGuard; + pub struct Uat { pub lower: Vm } + impl Uat { pub fn kernel_lower_vm(&self) -> &Vm { &self.lower } } + pub struct KernelMapping { key: usize } + impl KernelMapping { + pub fn new(vm: &Vm, addr: u64, prot: Prot, data: &Data) -> Self { + let key = NEXT.with(|n| { let mut n = n.borrow_mut(); *n += 1; *n }); + LIVE.with(|l| { + let mut l = l.borrow_mut(); + assert!(!l.iter().any(|m| m.vm == vm.id && m.addr == addr), + "VA {:#x} mapped twice in VM {}: the previous views were not dropped", addr, vm.id); + l.push(Live { key, vm: vm.id, addr, prot, data: data.clone() }); + }); + KernelMapping { key } + } + } + impl Drop for KernelMapping { + fn drop(&mut self) { LIVE.with(|l| l.borrow_mut().retain(|m| m.key != self.key)); } + } +} +struct MappedObject { data: Data, iova: u64, logical_size: usize } +impl MappedObject { + fn new(iova: u64, size: usize) -> Self { + MappedObject { data: Rc::new(RefCell::new(vec![0; size])), iova, logical_size: size } + } + fn shared(&self, iova: u64) -> Self { MappedObject { data: self.data.clone(), iova, logical_size: self.logical_size } } + fn iova(&self) -> u64 { self.iova } + fn with_bytes_mut(&mut self, f: impl FnOnce(&mut [u8]) -> Result) -> Result { + let mut bytes = self.data.borrow_mut(); + let all_zero_before = bytes.iter().all(|&b| b == 0); + let r = f(&mut bytes[..]); + // Render targets are cleared every frame; count the hand-over clears only. + let target = (va::GRAPHICS_TARGET_OFFSET..va::GRAPHICS_TARGET_OFFSET + 0x30000).contains(&self.iova); + if !target && !all_zero_before && bytes.iter().all(|&b| b == 0) { CLEARS.with(|c| *c.borrow_mut() += 1); } + r + } + fn map_alias_at(&mut self, vm: &mmu::Vm, address: u64, prot: mmu::Prot) -> Result { + Ok(mmu::KernelMapping::new(vm, address, prot, &self.data)) + } + fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result { + if size > self.logical_size { *self.data.borrow_mut() = vec![0; size]; self.logical_size = size; } + Ok(()) + } +} +mod g18 { + pub mod address_map { pub const COMPACT_BIAS: u64 = 0x10_0000_0000; } + pub mod uapi { pub mod graphics_scratch { + #[derive(Clone, Copy)] pub struct G18RenderScratchSelection; + } } +} +mod va { + pub use crate::g18::address_map::COMPACT_BIAS; + pub const GRAPHICS_JOB_LOW: u64 = 0x70_1200_0000; + pub const GRAPHICS_TARGET_OFFSET: u64 = 0x0100_0000; +} +#[derive(Clone, Copy, Default)] +struct Params { + cycle: u64, record_index: u64, ta_hardware_buffer_id: u32, usc_flist_hardware_buffer_id: u32, + scissor_array: u64, depth_bias_array: u64, depth_buffer: u64, depth_aux_buffer: u64, + load_pipeline: u64, store_pipeline: u64, partial_load_pipeline: u64, partial_store_pipeline: u64, + target: usize, +} +#[derive(Clone, Copy, Default)] struct Controls; +struct RenderTarget { width: u32, height: u32 } +struct G18ApplicationRender { + parameters: Params, controls: Controls, + scratch: Option, + target: RenderTarget, vdm_base: u64, +} +mod assembly { + pub struct Plan { pub offsets: [u64; 3], pub sizes: [usize; 3] } + pub fn target_plan(p: &super::Params) -> Option { + Some(Plan { offsets: [0, 0x10000, 0x20000], sizes: [p.target; 3] }) + } + pub fn apply_target_plan(_: &mut super::Params, _: &Plan) {} + pub const TARGET_NAMES: [&str; 3] = ["a", "b", "c"]; +} +mod regs { pub fn initialize_g18_deflake(_: &mut [u8], _: u32, _: u32) -> Option<()> { Some(()) } } +#[derive(Clone, Copy)] struct Frame { generation: u32 } +impl Frame { fn new(generation: u32) -> Option { (generation != 0).then_some(Frame { generation }) } } +#[derive(Clone, Copy)] struct WalkKey; +struct Program { vm: mmu::Vm } +impl Program { + fn matches_vm(&self, vm: &mmu::Vm) -> bool { self.vm.id == vm.id } + fn rebind_retired(&mut self, vm: &mmu::Vm) -> Result { self.vm = vm.clone(); Ok(()) } +} +struct G18PbCommandFields { pb_slot: u32 } +#[derive(Clone, Copy)] +struct G18PbAddresses { page_list_low: u64, page_list_row: u64, metrics_low: u64, scene_scratch_low: u64, discard_low: u64 } +const PB_BLOCKS_LOW: u64 = 0x70_2000_0000; +const PB_BLOCK: u64 = 0x80000; +struct G18ParameterBuffer { + page_list: MappedObject, metrics: MappedObject, scene_scratch: MappedObject, + discard: MappedObject, blocks: KVec, addresses: G18PbAddresses, +} +impl G18ParameterBuffer { + fn application_scene(&mut self, _: Option<&[u8; 0x80]>) -> Result<[u8; 0x80]> { Ok([0; 0x80]) } + fn scene_cycle(&self) -> u64 { 0 } + fn metrics_record(&self) -> u64 { 0 } + fn command_fields(&self) -> G18PbCommandFields { G18PbCommandFields { pb_slot: 0 } } +@@PB@@ +} +struct G18GraphicsJob { + program: Program, targets: KVec, aliases: KVec, + graph: MappedObject, parameter_buffer: G18ParameterBuffer, parameters: Params, + controls: Controls, signals: MappedObject, encoded: Option<()>, +} +impl G18GraphicsJob { fn context_id(&self) -> u8 { 3 } } +@@JOB@@ +impl ApplicationJob { + fn encode_application(&mut self, _: &AsahiDrmDevice, _: Frame) -> Result { Ok(()) } + fn retired(&mut self) { self.retired = true; self.guard = None; } +@@PREPARE@@ +} +const DIRECTORY_BASE: u64 = 0x70_0200_0000; +const BLOCK_LIST_BASE: u64 = 0x70_0400_0000; +const BLOCK_DATA_BASE: u64 = 0x70_0500_0000; +const BLOCK_DATA_STRIDE: u64 = 0x20_0000; +const G18_COMPUTE_BLOCK_BYTES: u64 = 0x20_0000; +struct Layout; +impl Layout { fn page_offset(&self, i: u32) -> Option { Some(u64::from(i) * 0x4000) } } +#[derive(Clone, Copy)] struct G18ComputePlan; +struct G18UmaPoolMemory { + process_aliases: KVec, scratch: KVec, scratch_plan: Option<()>, + directory: KVec, block_list: MappedObject, layout: Layout, encoded: bool, + descriptor_loaded: bool, render: bool, low_bias: u64, hardware_slot: u32, client_vm: Option, +} +impl G18UmaPoolMemory { + fn model(render: bool, low_bias: u64, blocks: usize) -> Self { + let mut scratch = KVec::new(); + for i in 0..blocks { let _ = scratch.push(MappedObject::new(0x1000 * i as u64, 64), GFP_KERNEL); } + let mut directory = KVec::new(); + let _ = directory.push(MappedObject::new(0, 64), GFP_KERNEL); + G18UmaPoolMemory { process_aliases: KVec::new(), scratch, scratch_plan: Some(()), directory, + block_list: MappedObject::new(0, 64), layout: Layout, encoded: true, descriptor_loaded: true, + render, low_bias, hardware_slot: 1, client_vm: None } + } + // As the production constructor: a fresh pool has no client. + fn new_layout(_: &AsahiDrmDevice, _: &mmu::Uat, _: Range, _: u32, _: bool, _: bool, + low_bias: u64, _: u32, _: u64) -> Result { + let mut pool = Self::model(false, low_bias, 0); pool.scratch_plan = None; pool.encoded = false; + pool.descriptor_loaded = false; Ok(pool) + } + // The retained scratch objects are the same memory, plus one fresh block. + fn prepare_shared_compute_retaining(&mut self, _: &AsahiDrmDevice, _: &mmu::Uat, _: Range, + _: G18ComputePlan, retained: Option<&Self>) -> Result { + for (i, old) in retained.unwrap().scratch.iter().enumerate() { + self.scratch.push(old.shared(0x10_0000 + 0x1000 * i as u64), GFP_KERNEL)?; + } + self.scratch.push(MappedObject::new(0x20_0000, 64), GFP_KERNEL)?; + self.scratch_plan = Some(()); Ok(()) + } + fn alias_into_process(&mut self, _: &AsahiDrmDevice, _: &mmu::Uat, vm: &mmu::Vm) -> Result { + let mut aliases = KVec::new(); + for (i, block) in self.scratch.iter_mut().enumerate() { + aliases.push(block.map_alias_at(vm, BLOCK_DATA_BASE + self.low_bias + i as u64 * 0x30_0000, + mmu::PROT_GPU_SHARED_RW)?, GFP_KERNEL)?; + } + self.process_aliases = aliases; Ok(()) + } + fn audit_render_mappings(&self, _: &mmu::Uat, _: &mmu::Vm) -> Result { Ok(0) } +@@POOL@@ +} + +/// Kernel-only addresses: kept by design (they name the PB's and pool's own objects). +fn kept(addr: u64) -> bool { + let bias = va::COMPACT_BIAS; + [0x70_3000_0000u64, 0x70_3100_0000, DIRECTORY_BASE, BLOCK_LIST_BASE, va::GRAPHICS_JOB_LOW] + .iter().any(|&a| addr == a || addr == a + bias) +} +/// The GPU work of `vm` writes its id through each writable view it has. +fn gpu_work(vm: u64) { + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm && m.prot == mmu::Prot::Rw && !kept(m.addr) { m.data.borrow_mut().fill(vm as u8); } + }); +} +/// No live view of `vm` may reach a byte another VM wrote. +fn exposed(vm: u64, what: &str) { + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm { + let data = m.data.borrow(); + assert!(data.iter().all(|&b| b == 0 || b == vm as u8), + "{}: VM {} maps {:#x}, which holds VM {}'s data", what, vm, m.addr, + data.iter().find(|&&b| b != 0 && b != vm as u8).unwrap()); + } + }); +} +fn holds(object: &MappedObject, vm: u64) -> bool { object.data.borrow().iter().all(|&b| b == vm as u8) } +fn clears() -> usize { CLEARS.with(|c| *c.borrow()) } + +fn new_job() -> Box { + let mut blocks = KVec::new(); + for i in 0..2u64 { let _ = blocks.push(MappedObject::new(PB_BLOCKS_LOW + i * PB_BLOCK, 64), GFP_KERNEL); } + let pb = G18ParameterBuffer { + page_list: MappedObject::new(0x70_3000_0000, 64), metrics: MappedObject::new(0x70_3100_0000, 64), + scene_scratch: MappedObject::new(0x70_3200_0000, 64), discard: MappedObject::new(0x70_3300_0000, 64), + blocks, addresses: G18PbAddresses { page_list_low: 0x70_3000_0000, page_list_row: 0x70_3000_0000 + va::COMPACT_BIAS, + metrics_low: 0x70_3100_0000, scene_scratch_low: 0x70_3200_0000, discard_low: 0x70_3300_0000 }, + }; + let mut targets = KVec::new(); + for offset in [0u64, 0x10000, 0x20000] { + let _ = targets.push(MappedObject::new(va::GRAPHICS_TARGET_OFFSET + offset, 64), GFP_KERNEL); + } + let job = G18GraphicsJob { program: Program { vm: mmu::Vm { id: 100 } }, targets, aliases: KVec::new(), + graph: MappedObject::new(0xffff_0000, 64), parameter_buffer: pb, parameters: Params::default(), + controls: Controls, signals: MappedObject::new(0, 0xc020), encoded: None }; + Box::new(ApplicationJob { job: Box::new(job), storage: mmu::Vm { id: 100 }, user_aliases: KVec::new(), + pool_aliases: KVec::new(), guard: None, scene: [0; 0x80], generation: 0, retired: true, + client_frames: 0, scratch: None, walked: None }) +} +fn render(target: usize) -> G18ApplicationRender { + G18ApplicationRender { parameters: Params { target, ..Params::default() }, controls: Controls, + scratch: None, target: RenderTarget { width: 8, height: 8 }, vdm_base: 0 } +} +/// submit_application: prepare, the render pool once per remap, the frame, retirement. +fn frame(job: &mut ApplicationJob, pool: &mut G18UmaPoolMemory, uat: &mmu::Uat, vm: u64, target: usize) { + let vm = mmu::Vm { id: vm }; + job.prepare(&AsahiDrmDevice, uat, &vm, &render(target)).unwrap(); + if job.pool_aliases.is_empty() { job.pool_aliases = pool.application_aliases(uat, &vm).unwrap(); } + exposed(vm.id, "render hand-over"); + LIVE.with(|l| for m in l.borrow().iter() { + if m.vm == vm.id && (m.addr == va::GRAPHICS_JOB_LOW) { + assert_eq!(m.prot, mmu::Prot::Ro, "the client view of the command graph must be read-only"); + } + }); + gpu_work(vm.id); + job.retired(); +} + +fn main() { + let uat = mmu::Uat { lower: mmu::Vm { id: 0 } }; + let mut job = new_job(); + let mut pool = G18UmaPoolMemory::model(true, 0, 3); + frame(&mut job, &mut pool, &uat, 1, 64); + // A firmware TVB grow request backs a block for VM 1, aliased with its other PB views. + let mut grown = MappedObject::new(PB_BLOCKS_LOW + 2 * PB_BLOCK, 64); + for at in [grown.iova(), grown.iova() + va::COMPACT_BIAS] { + let alias = grown.map_alias_at(&mmu::Vm { id: 1 }, at, mmu::PROT_GPU_SHARED_RW).unwrap(); + job.user_aliases.push(alias, GFP_KERNEL).unwrap(); + } + job.job.parameter_buffer.blocks.push(grown, GFP_KERNEL).unwrap(); + gpu_work(1); + let before = clears(); + frame(&mut job, &mut pool, &uat, 1, 64); + frame(&mut job, &mut pool, &uat, 1, 128); + assert_eq!(clears(), before, "the same VM again (also with regrown targets) must not clear the PB or pool"); + assert!(job.job.parameter_buffer.blocks.iter().all(|b| holds(b, 1)) && pool.scratch.iter().all(|b| holds(b, 1)), + "the same VM's storage must be kept"); + for vm in [2, 2, 1, 3, 2] { frame(&mut job, &mut pool, &uat, vm, 128); } + println!("PASS render: 8 frames over 3 VMs, PB growth, target regrowth; no VM sees another's PB blocks, scene scratch, discard page or pool scratch; graph view read-only; same VM clears nothing"); + + let mut compute = G18UmaPoolMemory::model(false, 0x4000_0000, 2); + let mut owner = |pool: &mut G18UmaPoolMemory, vm: u64| { + let aliases = pool.compute_application_aliases(&AsahiDrmDevice, &uat, &mmu::Vm { id: vm }).unwrap(); + exposed(vm, "compute hand-over"); + gpu_work(vm); + aliases // the attempt keeps them until the next submission clears job.aliases + }; + let a = owner(&mut compute, 1); drop(a); + let before = clears(); + let a = owner(&mut compute, 1); drop(a); + assert_eq!(clears(), before, "the same VM's compute again must not clear the pool"); + assert!(compute.scratch.iter().all(|b| holds(b, 1))); + let a = owner(&mut compute, 2); drop(a); + let mut replacement = compute.replacement_shared_compute(&AsahiDrmDevice, &uat, 0..1, G18ComputePlan).unwrap(); + let a = owner(&mut replacement, 1); drop(a); + let a = owner(&mut replacement, 1); drop(a); + let a = owner(&mut replacement, 3); drop(a); + println!("PASS compute: 6 submissions over 3 VMs and a replacement pool retaining the scratch objects; no VM sees another's scratch; same VM clears nothing"); +} +''' + + +def build(read): + prepare_src = read(PREPARE) + pb_src = read(PB) + pool_src = read(POOL) + job = item(prepare_src, 'pub(crate) struct ApplicationJob {') + prepare = item(prepare_src, 'pub(crate) fn prepare(') + pb = (item(pb_src, 'pub(crate) fn application_aliases(&mut self, vm: &mmu::Vm)') + '\n' + + item(pb_src, 'pub(crate) fn clear_client_data(', optional=True)) + pool = (item(read(POOL_APP), 'pub(crate) fn application_aliases(&mut self, uat') + '\n' + + item(pool_src, 'pub(crate) fn compute_application_aliases(') + '\n' + + item(pool_src, 'fn clear_scratch_for(', optional=True) + '\n' + + item(read(POOL_SHARED), 'pub(crate) fn replacement_shared_compute(')) + return (MODEL.replace('@@JOB@@', job).replace('@@PREPARE@@', prepare) + .replace('@@PB@@', pb).replace('@@POOL@@', pool)) + + +def sub(old, new): + def apply(code): + assert old in code, 'mutation anchor missing: ' + old + return code.replace(old, new, 1) + return apply + + +MUTATIONS = { + 'pb-clear-dropped': sub('if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;}', ''), + 'pb-clear-every-remap': sub('if new_client && self.generation!=0 {', 'if self.generation!=0 {'), + 'pb-grown-blocks-kept': sub('for block in self.blocks.iter_mut() {\n clear(block)', 'for block in self.blocks.iter_mut().take(2) {\n clear(block)'), + 'pb-scene-scratch-kept': sub('clear(&mut self.scene_scratch)?;', ''), + 'pb-discard-kept': sub('clear(&mut self.discard)?;', ''), + 'graph-view-writable': sub('va::GRAPHICS_JOB_LOW,\n mmu::PROT_GPU_SHARED_RO)', 'va::GRAPHICS_JOB_LOW,\n mmu::PROT_GPU_SHARED_RW)'), + 'render-pool-clear-dropped': sub('{return Err(EINVAL);}\n self.clear_scratch_for(vm)?;', '{return Err(EINVAL);}'), + 'compute-pool-clear-dropped': sub(' self.clear_scratch_for(vm)?;\n self.alias_into_process(', ' self.alias_into_process('), + 'pool-clear-every-alias': sub('self.client_vm.is_some_and(|id| id != vm.id())', 'self.client_vm.is_some()'), + 'replacement-forgets-client': sub('pool.client_vm = self.client_vm;', ''), +} + + +def source_checks(read): + prepare = item(read(PREPARE), 'pub(crate) fn prepare(') + assert prepare.index('if !self.retired {return Err(EBUSY);}') < prepare.index('clear_client_data'), 'prepare: retired first' + submit = item(read(SESSION), 'fn submit_application(') + assert submit.index('job.prepare(') < submit.index('.application_aliases(vm)'), 'session: pool aliased after prepare' + attempt = item(read(COMPUTE), 'fn prepare_application_compute_attempt(') + retired = attempt.index('if !job.retired') + dropped = attempt.index('job.aliases.clear();') + aliased = attempt.index('pool.compute_application_aliases(') + assert retired < dropped < aliased, 'compute: retired, previous aliases dropped, then the pool aliased' + print('PASS source: retirement is checked first; previous views are dropped before the pools are aliased') + + +def compile_run(code, out, name, rustc): + path = out / (name + '.rs') + path.write_text(code) + binary = out / name + built = subprocess.run(rustc + ['--edition=2021', '-O', str(path), '-o', str(binary)], + capture_output=True, text=True) + if built.returncode != 0: + raise SystemExit(f'{name}: host build failed\n{built.stderr}') + return subprocess.run([str(binary)], capture_output=True, text=True) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--rustc', default=os.environ.get('HOSTRUSTC') or os.environ.get('RUSTC', 'rustc')) + p.add_argument('--mutations', action='store_true', + help=f'Also require every mutant and the code at {BASE} to fail') + a = p.parse_args() + out = (a.output or Path(tempfile.mkdtemp(prefix='g18-client-handoff-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + rustc = [a.rustc] + + def tip(path): + return (ROOT / path).read_text() + + def base(path): + return subprocess.check_output(['git', 'show', f'{BASE}:{path}'], cwd=ROOT, text=True) + + source_checks(tip) + result = compile_run(build(tip), out, 'fixed', rustc) + if result.returncode != 0: + sys.exit('FAIL fixed code\n' + result.stderr) + print(result.stdout.strip()) + if not a.mutations: + return + unchecked = sub('assert_eq!(m.prot, mmu::Prot::Ro,', 'assert!(true || m.prot == mmu::Prot::Ro,') + mutants = [(BASE, build(base)), (BASE + '-data-only', unchecked(build(base)))] + for name, apply in MUTATIONS.items(): + code = build(tip) + mutants.append((name, apply(code))) + killed = 0 + for name, code in mutants: + result = compile_run(code, out, 'mutant-' + name, rustc) + if result.returncode == 0 or 'panicked at' not in result.stderr: + sys.exit(f'FAIL mutant {name} survived\n{result.stdout}{result.stderr}') + reason = next((l for l in result.stderr.splitlines() if l and 'panicked at' not in l and 'note:' not in l), '') + print(f'PASS mutant killed: {name}: {reason.strip()}') + killed += 1 + print(f'PASS {killed}/{len(mutants)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index ef6b042b17881..6d4c1b7cfd19e 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -206,6 +206,7 @@ def mutations(flag, names, base, expect=KILL): 'g15-retention-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], + 'g18-client-handoff-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery', From 0a4f6d6576a39c4879259de5efc295d064793555 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Mon, 23 Nov 2026 10:54:21 +1100 Subject: [PATCH 3/3] drm/asahi: g18: fail a job refused before publication alone Every error a submission met after admission ended the firmware session: an address the client unmapped after admission, its VM closed, or a render target allocation it sized made submit_application() return Failure::Fatal, and no client could submit again until reboot. ApplicationJob::prepare() now commits the frame (guard, generation, retired) only after its last fallible step, so an error leaves the job retired and the next prepare() rebuilds what this one changed; the first frame's kernel alias is made once. Nothing of a render reaches the firmware before prepare() returns. A prepare error that leaves the job unpublished is a new JobFailure::Refused: the submitter gets its errno, the session and the path keep serving and the client's VM is not poisoned. The compute path does the same when the failed preparation left its owner retired with no process, command or context published. Anything else, and any error on a crashed firmware, stays fatal. Also correct the documented defaults of the g18_admit_* parameters, which are 1. Add a host test that drives the production prepare and outcome paths against the hand-over model, with the previous code as a mutant. Signed-off-by: Ryan Murray --- .../gpu/drm/asahi/g18/boot/compute_session.rs | 12 +- drivers/gpu/drm/asahi/g18/boot/recovery.rs | 5 + drivers/gpu/drm/asahi/g18/boot/session.rs | 16 +- drivers/gpu/drm/asahi/g18/drm.rs | 6 +- .../asahi/g18/initdata/application_compute.rs | 12 + .../g18/runtime/graphics_job_application.rs | 12 +- tools/asahi/g18-job-error-tests.py | 313 ++++++++++++++++++ tools/asahi/run-host-tests.py | 1 + 8 files changed, 368 insertions(+), 9 deletions(-) create mode 100644 tools/asahi/g18-job-error-tests.py diff --git a/drivers/gpu/drm/asahi/g18/boot/compute_session.rs b/drivers/gpu/drm/asahi/g18/boot/compute_session.rs index 8af55d934298f..a5c7d8b40900b 100644 --- a/drivers/gpu/drm/asahi/g18/boot/compute_session.rs +++ b/drivers/gpu/drm/asahi/g18/boot/compute_session.rs @@ -8,8 +8,16 @@ impl G18Session { translated: &crate::g18::uapi::command::TranslatedComputeCommand) -> core::result::Result<(), Failure> { self.poll_idle_faults("application compute prepare")?; - let (command, pool, generation, knobs) = self.memory.as_mut().ok_or(EIO)? - .prepare_application_compute(&self.dev, vm, translated)?; + let memory = self.memory.as_mut().ok_or(EIO)?; + let (command, pool, generation, knobs) = + match memory.prepare_application_compute(&self.dev, vm, translated) { + Ok(prepared) => prepared, + // A refusal that left the owner retired and nothing + // published fails this job only. + Err(error) => return Err(if memory.application_compute_unpublished() { + Failure::Job(JobFailure::Refused(error)) + } else { Failure::Fatal(error) }), + }; if generation == 1 { self.queue_probe.as_mut().ok_or(EIO)?.prepare_initial_context(command.context_id)?; for phase in 1..=3 { diff --git a/drivers/gpu/drm/asahi/g18/boot/recovery.rs b/drivers/gpu/drm/asahi/g18/boot/recovery.rs index fca20c69a30ca..fbdb4036c3f11 100644 --- a/drivers/gpu/drm/asahi/g18/boot/recovery.rs +++ b/drivers/gpu/drm/asahi/g18/boot/recovery.rs @@ -164,6 +164,11 @@ pub(super) enum JobFailure { Released, /// [`Self::Stranded`] as reported back to the submitting thread. Retained, + /// Refused while being prepared from the client's own state (its VM + /// closed, an address it names unmapped, an allocation it sized): nothing + /// of the job reached the firmware and its owner is back where the last + /// retirement left it. The session and the path keep serving. + Refused(Error), } /// How far a failed task reaches. diff --git a/drivers/gpu/drm/asahi/g18/boot/session.rs b/drivers/gpu/drm/asahi/g18/boot/session.rs index e0653fbd1b247..cf03052bb7b81 100644 --- a/drivers/gpu/drm/asahi/g18/boot/session.rs +++ b/drivers/gpu/drm/asahi/g18/boot/session.rs @@ -105,6 +105,7 @@ impl ApplicationOwner { Err(Failure::Fatal(error))=>error.to_errno(), Err(Failure::Job(JobFailure::Recovered(_) | JobFailure::Unbound(..) | JobFailure::Released))=>JobOutcome::Recovered as i32, Err(Failure::Job(JobFailure::Stranded(..) | JobFailure::Retained))=>JobOutcome::Stranded as i32, + Err(Failure::Job(JobFailure::Refused(error)))=>JobOutcome::Refused as i32-error.to_errno(), } } @@ -114,6 +115,8 @@ impl ApplicationOwner { 0 => Ok(()), code if code==JobOutcome::Recovered as i32 => Err(Failure::Job(JobFailure::Released)), code if code==JobOutcome::Stranded as i32 => Err(Failure::Job(JobFailure::Retained)), + code if code>JobOutcome::Refused as i32 => + Err(Failure::Job(JobFailure::Refused(Error::from_errno(JobOutcome::Refused as i32-code)))), errno => Err(Failure::Fatal(Error::from_errno(errno))), } } @@ -125,6 +128,8 @@ impl ApplicationOwner { match result { Ok(()) => Ok(()), Err(Failure::Job(JobFailure::Released)) | Err(Failure::Job(JobFailure::Recovered(_))) => Err(EIO), + // Nothing ran: the client's VM stays usable. + Err(Failure::Job(JobFailure::Refused(error))) => Err(error), Err(Failure::Job(_)) => {if let Some(status)=vm.status(){status.record(EIO);}Err(EIO)} Err(Failure::Fatal(error)) => {if let Some(status)=vm.status(){status.record(error);}Err(error)} } @@ -137,6 +142,8 @@ const TICKET_RUNNING: i32 = 1; enum JobOutcome { Recovered = 2, Stranded = 3, + /// Plus the errno: [`JobFailure::Refused`]. + Refused = 0x1000, } impl G18Runtime for ApplicationOwner { @@ -200,6 +207,9 @@ fn log_job_failure(session:&G18Session,failure:&JobFailure) { JobFailure::Unbound(r,path,unready) => dev_err!(session.device(), "G18_APP_JOB_FAILED error={:?} recovery epoch={} host={} us={} reason={:#x} slot-mask={:#x} queues=retired unbound={} path={:?} quarantined session=live recoveries={}\n", EIO,r.epoch,r.host,r.us,r.cause.reason,r.cause.slot_mask,unready,path,recovery::recoveries()), + // The submitter's own error, returned to it: not logged above debug level. + JobFailure::Refused(error) => dev_dbg!(session.device(), + "G18_APP_JOB_REFUSED error={:?} unpublished session=live\n",error), // Only the submitting thread's summaries; the worker logs the rest. JobFailure::Released | JobFailure::Retained => {} } @@ -213,7 +223,11 @@ impl G18Session { self.application_job=Some(ApplicationJob::new(self.render_job.take().ok_or(EIO)?)?); } let job=self.application_job.as_mut().ok_or(EIO)?; - job.prepare(&self.dev,&self.uat,vm,render)?; + if let Err(error)=job.prepare(&self.dev,&self.uat,vm,render) { + // Nothing is published before prepare() commits the frame: a + // job it refused leaves the owner retired, the session serves on. + return Err(if job.unpublished() {Failure::Job(JobFailure::Refused(error))} else {Failure::Fatal(error)}); + } if job.pool_aliases.is_empty() { job.pool_aliases=self.memory.as_mut().ok_or(EIO)?.application_aliases(vm)?; } diff --git a/drivers/gpu/drm/asahi/g18/drm.rs b/drivers/gpu/drm/asahi/g18/drm.rs index 14a726b24fc4c..fccae19b1a722 100644 --- a/drivers/gpu/drm/asahi/g18/drm.rs +++ b/drivers/gpu/drm/asahi/g18/drm.rs @@ -108,14 +108,14 @@ pub(crate) trait G18DrmRuntime: G18RenderJobSink { /// Adapter options fixed at registration. #[derive(Debug, Copy, Clone, Default)] pub(crate) struct G18DrmConfig { - /// Admit compute commands (module parameter `g18_admit_compute`, default 0). + /// Admit compute commands (module parameter `g18_admit_compute`, default 1). pub(crate) admit_compute: bool, /// Admit exactly the native 4x MSAA render set (module parameter - /// `g18_admit_msaa4`, default 0; msaa163). Off refuses every + /// `g18_admit_msaa4`, default 1; msaa163). Off refuses every /// multisampled render as before. pub(crate) admit_msaa4: bool, /// Admit renders carrying `DRM_ASAHI_RENDER_G18_RESOURCES` (module - /// parameter `g18_admit_graphics_scratch`, default 0). Off leaves the + /// parameter `g18_admit_graphics_scratch`, default 1). Off leaves the /// feature unadvertised and refuses the flag, so Mesa keeps refusing /// draws whose programs need a thread-private frame. pub(crate) admit_graphics_scratch: bool, diff --git a/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs b/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs index 549324f688467..28ca57d29cbd8 100644 --- a/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs +++ b/drivers/gpu/drm/asahi/g18/initdata/application_compute.rs @@ -455,6 +455,18 @@ impl G18FirmwareMemory { Ok((prepared, job.binding, generation, knobs)) } + /// Whether the compute owner is as the last retirement left it, with no + /// process, command or context published: a failed preparation that + /// leaves this true changed nothing the firmware uses. Before the owner + /// exists, its scheduler record must not be armed yet. + pub(crate) fn application_compute_unpublished(&self) -> bool { + self.compute.unpublished_idle() && match self.application_compute.as_ref() { + Some(job) => job.retired && job.guard.is_none() && job.aliases.is_empty() + && job.previous_pool.is_none() && job.previous_binding.is_none(), + None => self.scheduler.binding(0).is_err(), + } + } + /// The binding the firmware must still own before the next tag15. pub(crate) fn application_compute_previous_binding(&self) -> Result<(G18UmaPoolBinding, u32)> { let job = self.application_compute.as_ref().ok_or(EIO)?; diff --git a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs index 61390620e20da..de571e9c9f67c 100644 --- a/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs +++ b/drivers/gpu/drm/asahi/g18/runtime/graphics_job_application.rs @@ -65,6 +65,9 @@ impl ApplicationJob { if let Some(status)=self.job.vm().status(){status.record(EIO);} } pub(crate) fn retired(&mut self) {self.retired=true;self.guard=None;} + /// No frame is committed: the last one retired and none was prepared + /// since, so the firmware holds nothing of this job beyond it. + pub(crate) fn unpublished(&self) -> bool {self.retired && self.guard.is_none()} /// One of the first frames of its client: logged even when job logging /// is sparse, so every isolated client leaves a kick/retirement pair. pub(crate) fn traced(&self) -> bool {self.client_frames<=3} @@ -94,7 +97,8 @@ impl ApplicationJob { // maps the PB. The pool scratch is cleared as it is aliased. if new_client && self.generation!=0 {self.job.parameter_buffer.clear_client_data()?;} } - if self.generation==0 { + // Once: a first frame refused after this keeps the alias. + if self.generation==0 && self.job.aliases.is_empty() { let alias=self.job.graph.map_alias_at(uat.kernel_lower_vm(),va::GRAPHICS_JOB_LOW, mmu::PROT_GPU_SHARED_RW)?; self.job.aliases.push(alias,GFP_KERNEL)?; @@ -127,8 +131,6 @@ impl ApplicationJob { // Retract even an unchanged root before publish_h1's fresh lease // publication. Retain the mappings when the actual VM is unchanged. self.job.program.rebind_retired(vm)?; - self.guard=Some(guard);self.generation=frame.generation;self.retired=false; - self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)}; if remap { crate::g18_kick_info!(dev.as_ref(),"G18_APP_VM frame={} vm={} context={} target={}x{} aliases={}\n", frame.generation,vm.id(),self.job.context_id(),render.target.width,render.target.height,self.user_aliases.len()); @@ -153,6 +155,10 @@ impl ApplicationJob { self.job.signals.with_bytes_mut(|out| {out[0xc000..0xc020].fill(0);Ok(())})?; self.job.encoded=None; self.encode_application(dev,frame)?; + // Commit the frame only now: until here an error leaves the job + // retired, and the next prepare() rebuilds whatever this one changed. + self.guard=Some(guard);self.generation=frame.generation;self.retired=false; + self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)}; Ok(()) } diff --git a/tools/asahi/g18-job-error-tests.py b/tools/asahi/g18-job-error-tests.py new file mode 100644 index 0000000000000..cbe7fe65eb5c5 --- /dev/null +++ b/tools/asahi/g18-job-error-tests.py @@ -0,0 +1,313 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the G18 session's job-error classification, actual bodies, against a model. + +The harness extracts from drivers/gpu/drm/asahi/g18 JobFailure, Failure and From for +Failure (boot/recovery.rs); ApplicationOwner::outcome(), decode(), finish(), JobOutcome and the +prepare step of G18Session::submit_application() (boot/session.rs); ApplicationJob, prepare() +and unpublished() (runtime/graphics_job_application.rs, with the PB and pool bodies the hand-over +test uses, through its model); and G18FirmwareMemory::application_compute_unpublished() +(initdata/application_compute.rs). They run against a model whose client VMs can have an address +unmapped, be closed, or ask for a target larger than an allocation admits. + +What it shows: +- a render refused from the client's own state (an unmapped address it names, its VM closed, a + target allocation that fails, also on the first frame) fails that job only: its errno reaches + the submitter, the session stays live, no path is quarantined, the client's VM is not + poisoned, the job stays retired with its generation unchanged, and the next render of any + client runs; +- a prepare on a job that did not retire, and any job error on a crashed firmware, still end + the session; +- the compute owner counts as unpublished only while no process, command, context, previous + pool or held VM exists, and before it exists only while its scheduler record is unarmed; +- source checks: the compute submission classifies a failed preparation by that state, and + nothing in the render submission reaches the firmware before prepare(). + +--mutations runs every mutant, including the code at c5e25e0925351, and requires each to fail. +""" +import argparse +import importlib.util +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +spec = importlib.util.spec_from_file_location('g18_handoff', HERE / 'g18-client-handoff-tests.py') +handoff = importlib.util.module_from_spec(spec) +spec.loader.exec_module(handoff) +item, ROOT, BASE, G18 = handoff.item, handoff.ROOT, handoff.BASE, handoff.G18 +RECOVERY = G18 + 'boot/recovery.rs' +SESSION = G18 + 'boot/session.rs' +COMPUTE_SESSION = G18 + 'boot/compute_session.rs' +COMPUTE = G18 + 'initdata/application_compute.rs' +PREPARE = handoff.PREPARE + +EXTRA = r''' +thread_local! { + static UNMAPPED: RefCell> = RefCell::new(Vec::new()); + static CLOSED: RefCell> = RefCell::new(Vec::new()); + static POISONED: RefCell> = RefCell::new(Vec::new()); + static STOPPED: RefCell = RefCell::new(false); +} +const ENOMEM: i32 = 12; const EIO: i32 = 5; +const ALLOC_LIMIT: usize = 0x10000; +type Error = i32; +trait Errno { fn to_errno(&self) -> i32; fn from_errno(errno: i32) -> Self; } +impl Errno for i32 { fn to_errno(&self) -> i32 { -*self } fn from_errno(errno: i32) -> Self { -errno } } +pub struct Status(u64); +impl Status { pub fn record(&self, _: Error) { POISONED.with(|p| p.borrow_mut().push(self.0)); } } +macro_rules! dev_err { ($($t:tt)*) => {}; } +use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32}; +#[derive(Debug)] struct G18Recovery; +#[derive(Debug, Clone, Copy)] enum JobPath { Render, Compute } +impl JobPath { fn bit(&self) -> u32 { 1 << (*self as u32) } } +@@RECOVERY@@ +struct Mutex(std::sync::Mutex); +impl Mutex { fn lock(&self) -> std::sync::MutexGuard<'_, T> { self.0.lock().unwrap() } } +struct Retained(Option); +impl Retained { fn stop(&mut self, _: &str) -> Result { STOPPED.with(|s| *s.borrow_mut() = true); Ok(()) } } +struct Memory; +impl Memory { fn quarantine_application_compute(&mut self) {} fn log_trace_journal(&self, _: &AsahiDrmDevice) {} } +struct G18Session { dev: AsahiDrmDevice, uat: mmu::Uat, application_job: Option>, + memory: Option, crashed: bool } +impl G18Session { + fn any_crashed(&self) -> bool { self.crashed } + fn device(&self) -> &AsahiDrmDevice { &self.dev } + fn dump_fault_evidence(&self, _: &str) {} + fn submit_prepare(&mut self, vm: &mmu::Vm, render: &G18ApplicationRender) -> core::result::Result<(), Failure> { +@@SUBMIT@@ + Ok(()) + } +} +fn log_job_failure(_: &G18Session, _: &JobFailure) {} +const TICKET_RUNNING: i32 = 1; +@@OUTCOME_ENUM@@ +struct ApplicationOwner; +impl ApplicationOwner { +@@OWNER@@ +} + +struct ComputeMemory { process: bool } +impl ComputeMemory { fn unpublished_idle(&self) -> bool { !self.process } } +struct ApplicationCompute { retired: bool, guard: Option, aliases: KVec, + previous_pool: Option<()>, previous_binding: Option<()> } +struct Scheduler { armed: bool } +impl Scheduler { fn binding(&self, _: usize) -> Result<()> { if self.armed { Ok(()) } else { Err(EINVAL) } } } +struct G18FirmwareMemory { compute: ComputeMemory, application_compute: Option>, scheduler: Scheduler } +impl G18FirmwareMemory { +@@COMPUTE@@ +} + +struct Device { session: Mutex, failed: AtomicBool, quarantined: AtomicU32 } +impl Device { + fn job(&self, f: impl FnOnce(&mut ApplicationJob) -> R) -> R { + f(self.session.lock().0.as_mut().unwrap().application_job.as_mut().unwrap()) + } + /// One render through the ticket, as submit_render: prepare, then retire on success. + fn render(&self, vm: u64, scissor: u64, target: usize, retire: bool) -> Result { + let v = mmu::Vm { id: vm }; + let mut r = render(target); + r.parameters.scissor_array = scissor; + let code = ApplicationOwner::outcome(&self.session, &self.failed, &self.quarantined, |s| s.submit_prepare(&v, &r)); + let result = ApplicationOwner::finish(&v, ApplicationOwner::decode(code)); + if result.is_ok() && retire { self.job(|j| j.retired()); } + result + } + fn live(&self) -> bool { !self.failed.load(Ordering::Acquire) && !STOPPED.with(|s| *s.borrow()) } +} +fn device(crashed: bool) -> Device { + let session = G18Session { dev: AsahiDrmDevice, uat: mmu::Uat { lower: mmu::Vm { id: 0 } }, + application_job: Some(new_job()), memory: Some(Memory), crashed }; + STOPPED.with(|s| *s.borrow_mut() = false); + Device { session: Mutex(std::sync::Mutex::new(Retained(Some(session)))), failed: AtomicBool::new(false), + quarantined: AtomicU32::new(0) } +} +fn refused(d: &Device, result: Result, errno: i32, what: &str, generation: u32) { + assert_eq!(result, Err(errno), "{}: the submitter must get the job's own errno", what); + assert!(d.live(), "{}: a client's own error must not end the session", what); + assert_eq!(d.quarantined.load(Ordering::Acquire), 0, "{}: no path may be quarantined", what); + assert!(POISONED.with(|p| p.borrow().is_empty()), "{}: nothing ran, the client's VM stays usable", what); + assert!(d.job(|job| job.unpublished() && job.generation == generation), + "{}: the refused job must stay retired at generation {}", what, generation); +} +const SCISSOR: u64 = 0x5000; + +fn main() { + let d = device(false); + d.render(1, SCISSOR, 64, true).unwrap(); + d.render(1, SCISSOR, 64, true).unwrap(); + UNMAPPED.with(|u| u.borrow_mut().push((2, SCISSOR))); + let r = d.render(2, SCISSOR, 64, true); refused(&d, r, EFAULT, "unmapped scissor", 2); + UNMAPPED.with(|u| u.borrow_mut().clear()); + d.render(2, SCISSOR, 64, true).unwrap(); + CLOSED.with(|c| c.borrow_mut().push(3)); + let r = d.render(3, SCISSOR, 64, true); refused(&d, r, ENOENT, "closed VM", 3); + let r = d.render(1, SCISSOR, ALLOC_LIMIT * 2, true); refused(&d, r, ENOMEM, "target allocation", 3); + let r = d.render(2, SCISSOR, ALLOC_LIMIT * 2, true); refused(&d, r, ENOMEM, "target allocation, another VM", 3); + d.render(1, SCISSOR, 64, true).unwrap(); + assert_eq!(d.job(|j| j.generation), 4); + d.render(2, SCISSOR, ALLOC_LIMIT, true).unwrap(); + println!("PASS render: unmapped address, closed VM and failed target allocation fail their job only; the session, its path and the client VMs serve on"); + + drop(d); + let d = device(false); + UNMAPPED.with(|u| u.borrow_mut().push((1, SCISSOR))); + let r = d.render(1, SCISSOR, 64, true); refused(&d, r, EFAULT, "first frame", 0); + UNMAPPED.with(|u| u.borrow_mut().clear()); + d.render(1, SCISSOR, 64, true).unwrap(); + d.render(2, SCISSOR, 64, true).unwrap(); + println!("PASS render: a first frame refused after its kernel aliases were made is prepared again"); + + drop(d); + let d = device(false); + d.render(1, SCISSOR, 64, false).unwrap(); + assert!(d.render(1, SCISSOR, 64, true).is_err() && !d.live(), "a job that did not retire must still end the session"); + drop(d); + let d = device(true); + UNMAPPED.with(|u| u.borrow_mut().push((1, SCISSOR))); + assert!(d.render(1, SCISSOR, 64, true).is_err() && !d.live(), "a crashed firmware must still end the session"); + UNMAPPED.with(|u| u.borrow_mut().clear()); + println!("PASS render: an unretired job and a crashed firmware stay fatal"); + compute(); +} +''' + +COMPUTE_MAIN = r''' +fn compute() { + let idle = || ApplicationCompute { retired: true, guard: None, aliases: KVec::new(), previous_pool: None, previous_binding: None }; + let memory = |job: Option, process: bool, armed: bool| G18FirmwareMemory { + compute: ComputeMemory { process }, application_compute: job.map(Box::new), scheduler: Scheduler { armed } }; + assert!(memory(Some(idle()), false, true).application_compute_unpublished(), "a retired idle owner is unpublished"); + assert!(memory(None, false, false).application_compute_unpublished(), "before the owner exists nothing is armed"); + for (name, m) in [ + ("bound process", memory(Some(idle()), true, true)), + ("unretired", memory(Some(ApplicationCompute { retired: false, ..idle() }), false, true)), + ("held VM", memory(Some(ApplicationCompute { guard: Some(mmu::T8140VmJobGuard), ..idle() }), false, true)), + ("previous pool", memory(Some(ApplicationCompute { previous_pool: Some(()), ..idle() }), false, true)), + ("previous binding", memory(Some(ApplicationCompute { previous_binding: Some(()), ..idle() }), false, true)), + ("armed record without owner", memory(None, false, true)), + ] { + assert!(!m.application_compute_unpublished(), "compute owner with {} must stay fatal", name); + } + println!("PASS compute: only a retired, unbound owner (or an unarmed one not yet built) makes a failed preparation a job failure"); +} +''' + + +def build(read): + code = handoff.build(read).replace('fn main() {', 'fn handoff_main() {', 1) + for old, new in [ + ('pub fn retain_t8140_job(&self) -> Result { Ok(T8140VmJobGuard) }', + 'pub fn retain_t8140_job(&self) -> Result {\n' + ' if CLOSED.with(|c| c.borrow().contains(&self.id)) { Err(ENOENT) } else { Ok(T8140VmJobGuard) } }\n' + ' pub fn status(&self) -> Option { Some(Status(self.id)) }'), + ('pub fn translate_iova(&self, a: u64) -> Result { Ok(a) }', + 'pub fn translate_iova(&self, a: u64) -> Result {\n' + ' if UNMAPPED.with(|u| u.borrow().contains(&(self.id, a))) { Err(EFAULT) } else { Ok(a) } }'), + ('fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result {', + 'fn regrow_wc_at(&mut self, _: &AsahiDrmDevice, _: &mmu::Vm, _: u64, size: usize) -> Result {\n' + ' if size > ALLOC_LIMIT { return Err(ENOMEM); }'), + ('fn retired(&mut self) { self.retired = true; self.guard = None; }', + 'fn retired(&mut self) { self.retired = true; self.guard = None; }\n fn quarantine(&mut self) {}\n' + # The code before the fix has no such method; the model states the same property. + + (item(read(PREPARE), 'pub(crate) fn unpublished(', optional=True) + or 'fn unpublished(&self) -> bool { self.retired && self.guard.is_none() }')), + ]: + assert code.count(old) == 1, old + code = code.replace(old, new) + recovery = read(RECOVERY) + rec = '\n'.join(item(recovery, s).replace('pub(super) ', '') for s in + ('pub(super) enum JobFailure {', 'pub(super) enum Failure {', 'impl From for Failure {')) + session = read(SESSION) + submit = item(session, 'fn submit_application(') + start = submit.index('let job=self.application_job.as_mut().ok_or(EIO)?;') + end = submit.index('if job.pool_aliases.is_empty()') + owner = '\n'.join(item(session, s) for s in ('fn outcome(', 'fn decode(', 'fn finish(')) + compute = item(read(COMPUTE), 'pub(crate) fn application_compute_unpublished(', optional=True) + extra = (EXTRA.replace('@@RECOVERY@@', rec).replace('@@SUBMIT@@', submit[start:end]) + .replace('@@OUTCOME_ENUM@@', item(session, 'enum JobOutcome {')).replace('@@OWNER@@', owner) + .replace('@@COMPUTE@@', compute)) + extra += COMPUTE_MAIN if compute else 'fn compute() {}\n' + return code + extra + + +sub = handoff.sub +MUTATIONS = { + 'prepare-commits-early': lambda c: sub( + ' // Commit the frame only now: until here an error leaves the job\n' + ' // retired, and the next prepare() rebuilds whatever this one changed.\n' + ' self.guard=Some(guard);self.generation=frame.generation;self.retired=false;\n' + ' self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)};\n', '')( + sub(' self.job.program.rebind_retired(vm)?;\n', + ' self.job.program.rebind_retired(vm)?;\n' + ' self.guard=Some(guard);self.generation=frame.generation;self.retired=false;\n' + ' self.client_frames=if new_client {1} else {self.client_frames.saturating_add(1)};\n')(c)), + 'first-frame-alias-repeated': sub('if self.generation==0 && self.job.aliases.is_empty() {', 'if self.generation==0 {'), + 'refusal-always-fatal': sub('Failure::Job(JobFailure::Refused(error))} else {Failure::Fatal(error)}', + 'Failure::Fatal(error)} else {Failure::Fatal(error)}'), + 'refusal-ignores-state': sub('if job.unpublished() {Failure::Job', 'if true {Failure::Job'), + 'refusal-lost-in-ticket': sub(' code if code>JobOutcome::Refused as i32 =>', ' code if false =>'), + 'refusal-poisons-vm': sub('Err(Failure::Job(JobFailure::Refused(error))) => Err(error),', + 'Err(Failure::Job(JobFailure::Refused(error))) => {if let Some(status)=vm.status(){status.record(error);}Err(error)}'), + 'compute-ignores-process': sub('self.compute.unpublished_idle() && match', 'match'), + 'compute-unbuilt-always': sub('None => self.scheduler.binding(0).is_err(),', 'None => true,'), + 'compute-ignores-previous-pool': sub('&& job.previous_pool.is_none() ', ''), +} + + +def source_checks(read): + compute = item(read(COMPUTE_SESSION), 'pub(super) fn submit_application_compute(') + arm = compute[compute.index('.prepare_application_compute(&self.dev, vm, translated)'):] + arm = arm[:arm.index('if generation == 1')] + assert 'memory.application_compute_unpublished()' in arm and 'Failure::Job(JobFailure::Refused(error))' in arm \ + and 'Failure::Fatal(error)' in arm, arm + submit = item(read(SESSION), 'fn submit_application(') + before = submit[:submit.index('job.prepare(')] + for word in ('send_message', 'publish', 'install_records'): + assert word not in before, 'render submission reaches the firmware before prepare: ' + word + print('PASS source: compute classifies a failed preparation by the owner state; nothing of a render is published before prepare()') + + +def main(): + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument('--output', type=Path, help='Work directory (default: a temporary one)') + p.add_argument('--rustc', default=os.environ.get('HOSTRUSTC') or os.environ.get('RUSTC', 'rustc')) + p.add_argument('--mutations', action='store_true', + help=f'Also require every mutant and the code at {BASE} to fail') + a = p.parse_args() + out = (a.output or Path(tempfile.mkdtemp(prefix='g18-job-error-'))).resolve() + out.mkdir(parents=True, exist_ok=True) + rustc = [a.rustc] + + def tip(path): + return (ROOT / path).read_text() + + def base(path): + return subprocess.check_output(['git', 'show', f'{BASE}:{path}'], cwd=ROOT, text=True) + + source_checks(tip) + result = handoff.compile_run(build(tip), out, 'fixed', rustc) + if result.returncode != 0: + sys.exit('FAIL fixed code\n' + result.stdout + result.stderr) + print(result.stdout.strip()) + if not a.mutations: + return + # The code before the fix with only the hand-over test's read-only graph check relaxed. + unchecked = sub('assert_eq!(m.prot, mmu::Prot::Ro,', 'assert!(true || m.prot == mmu::Prot::Ro,') + mutants = [(BASE, unchecked(build(base)))] + mutants += [(name, apply(build(tip))) for name, apply in MUTATIONS.items()] + killed = 0 + for name, code in mutants: + result = handoff.compile_run(code, out, 'mutant-' + name, rustc) + if result.returncode == 0 or 'panicked at' not in result.stderr: + sys.exit(f'FAIL mutant {name} survived\n{result.stdout}{result.stderr}') + reason = next((l for l in result.stderr.splitlines() if l and 'panicked at' not in l and 'note:' not in l), '') + print(f'PASS mutant killed: {name}: {reason.strip()}') + killed += 1 + print(f'PASS {killed}/{len(mutants)} mutants killed') + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index 6d4c1b7cfd19e..b48f571e84254 100755 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -207,6 +207,7 @@ def mutations(flag, names, base, expect=KILL): 'g15-stats-drain-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'g15-zero-words-tests.py': [([], PASS), (['--mutations'], PASS)], 'g18-client-handoff-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], + 'g18-job-error-tests.py': [(out('--output'), PASS), (out('--output') + ['--mutations'], PASS)], 'm5-client-handoff-tests.py': [([], PASS), (['--mutations'], PASS)], 'g17-telemetry-integration-tests.py': [(out(), PASS)] + mutations('--mutation', ('fields', 'range', 'timestamp', 'age', 'delivery',