From 8bc2fcf14647f326265f55e9f6a933588127ba4d Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Thu, 3 Dec 2026 08:33:00 -0500 Subject: [PATCH] drm/asahi: don't refuse the page tables of the driver's own client mappings A client VM's page tables are charged to its client since commit 31e8f6fe2ba7 ("drm/asahi: charge a VM's page tables to its client's memory limit"), and a table past the client's or the device's limit fails the mapping that needed it with ENOMEM. That is right for VM_BIND, which returns the error. But the driver maps its own objects into client VMs too (Vm::map_at() and Vm::map_in_range()), and G17 does so to publish a command: the views of a queue's kick and descriptor rings, of its pool pages and, on the A18 Pro, of the shared compute aperture, which is 26 mappings at a VM's first compute command. SUBMIT has accepted the command by then, so the refusal can only fail its fence. The VM and its later commands stay usable, but the failure is also what VM_STATUS and its mirror report, and Borealis takes that for a lost device. So a client whose large buffers take the memory up to the limit, which Vulkan reports as VK_ERROR_OUT_OF_DEVICE_MEMORY and applications handle, loses its device over a 16 KiB page table. Returning the refusal from SUBMIT instead would not help: Borealis also takes a failed SUBMIT for a lost device, because it has already moved the submission's semaphore payloads. Keep charging these tables, so they are visible and count against the client's next buffer and bind, but do not refuse them. They stay bounded without the limits: userspace does not place these mappings, and each is of an object that the driver made for a VM or a queue, or whose backing is itself charged. VM_BIND keeps refusing, and a failed page allocation still fails both. Every mapping of a driver's GEM object goes through VmInner::map_node(), so this covers all GPU families. The tables of kernel VMs are not charged. The host test compiles the production walk, ledger and map_node(). At either limit, main's map_node() fails with ENOMEM. The models of three other fixtures follow the new names. Fixes: 31e8f6fe2ba7 ("drm/asahi: charge a VM's page tables to its client's memory limit") Signed-off-by: DjDeveloperr --- drivers/gpu/drm/asahi/mmu.rs | 2 +- drivers/gpu/drm/asahi/pgtable.rs | 107 ++++-- tools/asahi/asahi-driver-map-charge-tests.py | 348 ++++++++++++++++++ tools/asahi/g14-v27-2-fw-window-gc-tests.py | 2 +- tools/asahi/run-host-tests.py | 3 + .../gpu/asahi-m4/test-mmu-retention.py | 4 +- .../drivers/gpu/asahi-m4/test-vm-words.py | 2 +- 7 files changed, 442 insertions(+), 26 deletions(-) create mode 100644 tools/asahi/asahi-driver-map-charge-tests.py diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index 09f1bdeb2968a..279538b848e9c 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -1254,7 +1254,7 @@ impl VmInner { let _mutation = self.mapping_mutation(); // Allocate detached RAM tables before excluding the firmware. The shadow L2 is not // the reserved shared-L2; only final leaf stores below already linked L3s are live. - self.page_table.prepare_map(node.start()..end)?; + self.page_table.prepare_driver_map(node.start()..end)?; let uat_inner = self.uat_inner.clone(); let handoff = uat_inner.lock_m4_upper(self.is_kernel)?; // Refuse a range holding another mapping's leaves before writing anything: the diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index 546131a6257c7..c56079f6f8035 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -441,6 +441,17 @@ impl Default for Prot { } } +/// What a walk does about a table that its range needs and that does not exist. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Missing { + /// Skips the part of the range below it. + Skip, + /// Allocates it if the limits of the client it is charged to admit it. + Admit, + /// Allocates it and charges it to the client whatever the limits. + Commit, +} + pub(crate) struct UatPageTable { ttb: PhysicalAddr, ttb_owned: bool, @@ -574,7 +585,8 @@ impl UatPageTable { /// Charges this page table's memory to a client from now on: the root and the tables /// allocated so far at once, whatever the client's limits, and each further table once it is /// allocated and ready to install. A table past the client's or the device's limit is freed - /// again and the map that needed it fails with `ENOMEM`; a table is charged only after every + /// again and the map that needed it fails with `ENOMEM`, except for a mapping that the driver + /// makes ([`Self::prepare_driver_map`]); a table is charged only after every /// step that can fail, so one that is not installed leaves no charge. The tables are also /// allocated as memory of the calling task's memory cgroup from then on. Everything stays /// charged until the page table is dropped, which frees the tables. @@ -595,11 +607,17 @@ impl UatPageTable { } /// Walks the leaves of `iova_range` without changing them. - fn with_pages(&mut self, iova_range: Range, alloc: bool, free: bool, cb: F) -> Result + fn with_pages( + &mut self, + iova_range: Range, + missing: Missing, + free: bool, + cb: F, + ) -> Result where F: FnMut(u64, &[Pte]) -> Result, { - self.walk(iova_range, alloc, free, false, cb) + self.walk(iova_range, missing, free, false, cb) } /// Walks the leaves of `iova_range`, which `cb` may change (`mutate`). @@ -609,7 +627,7 @@ impl UatPageTable { fn walk( &mut self, iova_range: Range, - alloc: bool, + missing: Missing, free: bool, mutate: bool, cb: F, @@ -617,8 +635,8 @@ impl UatPageTable { where F: FnMut(u64, &[Pte]) -> Result, { - let result = self.walk_inner(iova_range, alloc, free, mutate, cb); - if self.cleans_poc() && (alloc || free || mutate) { + let result = self.walk_inner(iova_range, missing, free, mutate, cb); + if self.cleans_poc() && (missing != Missing::Skip || free || mutate) { poc_barrier(); } result @@ -627,7 +645,7 @@ impl UatPageTable { fn walk_inner( &mut self, iova_range: Range, - alloc: bool, + missing: Missing, free: bool, mutate: bool, mut cb: F, @@ -636,6 +654,7 @@ impl UatPageTable { F: FnMut(u64, &[Pte]) -> Result, { let clean = self.cleans_poc(); + let alloc = missing != Missing::Skip; mod_pr_debug!( "UATPageTable::with_pages: {:#x?} alloc={} free={}\n", iova_range, @@ -741,7 +760,11 @@ impl UatPageTable { // Charge last: nothing below can fail, so a table that is // not installed is freed with no charge left behind. if let Some(charge) = charge.as_mut() { - charge.try_add(UAT_PGSZ as u64)?; + if missing == Missing::Commit { + charge.add(UAT_PGSZ as u64); + } else { + charge.try_add(UAT_PGSZ as u64)?; + } } if let Some(tables) = driver_tables.as_mut() { // Cannot fail: the room was reserved above. @@ -951,7 +974,7 @@ impl UatPageTable { let expected = (range.end - range.start) >> UAT_PGBIT; let mut visited = 0u64; let mut permitted = true; - self.with_pages(range, false, false, |_, ptes| { + self.with_pages(range, Missing::Skip, false, |_, ptes| { visited = visited.checked_add(ptes.len() as u64).ok_or(EOVERFLOW)?; for pte in ptes { let value = pte.load(Ordering::Acquire); @@ -991,7 +1014,7 @@ impl UatPageTable { let first = iova_range.start & self.ias_mask; let oas_mask = self.oas_mask; out.fill(u64::MAX); - self.with_pages(iova_range, false, false, |iova, ptes| { + self.with_pages(iova_range, Missing::Skip, false, |iova, ptes| { let index = ((iova - first) >> UAT_PGBIT) as usize; let slots = out.get_mut(index..index + ptes.len()).ok_or(EINVAL)?; for (slot, pte) in slots.iter_mut().zip(ptes) { @@ -1017,7 +1040,7 @@ impl UatPageTable { } let end = iova.checked_add(UAT_PGSZ as u64).ok_or(EINVAL)?; let mut value = 0; - self.with_pages(iova..end, false, false, |_, ptes| { + self.with_pages(iova..end, Missing::Skip, false, |_, ptes| { if let Some(pte) = ptes.first() { value = pte.load(Ordering::Relaxed); } @@ -1031,23 +1054,36 @@ impl UatPageTable { pub(crate) fn alloc_pages(&mut self, iova_range: Range) -> Result { mod_pr_debug!("UATPageTable::alloc_pages: {:#x?}\n", iova_range); - self.with_pages(iova_range, true, false, |_, _| Ok(())) + self.with_pages(iova_range, Missing::Admit, false, |_, _| Ok(())) } /// Reserve all tables for a fixed mapping before publishing any leaves. /// GPUVM and the fixed-address allocator may share a page table, so check /// that neither owns a destination leaf before allowing failure rollback. pub(crate) fn prepare_map(&mut self, range: Range) -> Result { + self.prepare_tables(range, Missing::Admit) + } + + /// [`Self::prepare_map`] for a mapping that the driver makes, such as its view of a queue's + /// rings in the client's address space. Its tables are charged to the client like all others, + /// but the limits do not refuse them: the driver also makes these mappings to publish a command + /// that SUBMIT has accepted. Then no ioctl is left to return a refusal, and userspace takes the + /// command's failed fence for a lost device. + pub(crate) fn prepare_driver_map(&mut self, range: Range) -> Result { + self.prepare_tables(range, Missing::Commit) + } + + fn prepare_tables(&mut self, range: Range, missing: Missing) -> Result { if range.is_empty() || (range.start | range.end) & UAT_PGMSK as u64 != 0 { return Err(EINVAL); } - self.with_pages(range.clone(), false, false, |_, ptes| { + self.with_pages(range.clone(), Missing::Skip, false, |_, ptes| { if ptes.iter().any(|pte| pte.load(Ordering::Acquire) != 0) { return Err(EBUSY); } Ok(()) })?; - self.alloc_pages(range) + self.with_pages(range, missing, false, |_, _| Ok(())) } fn pte_bits(&self) -> u64 { @@ -1090,7 +1126,7 @@ impl UatPageTable { let pte_bits = self.pte_bits(); let prot = self.stored(prot); - self.walk(iova_range, true, false, true, |iova, ptes| { + self.walk(iova_range, Missing::Admit, false, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { let ptev = pte.load(Ordering::Relaxed); if ptev != 0 { @@ -1139,7 +1175,7 @@ impl UatPageTable { let prot_bits = self.stored(prot).as_pte() | self.pte_bits(); let mut cursor = SegmentCursor::new(segments, offset, one_page)?; - self.walk(iova_range, true, false, true, |iova, ptes| { + self.walk(iova_range, Missing::Admit, false, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { let phys = cursor.next_page(iova + (idx * UAT_PGSZ) as u64)?; let ptev = pte.load(Ordering::Relaxed); @@ -1167,7 +1203,7 @@ impl UatPageTable { /// store: its failure path clears the whole range it asked for, which would otherwise /// also clear the other mapping's leaves. pub(crate) fn ensure_unmapped(&mut self, iova_range: Range) -> Result { - self.walk(iova_range, false, false, false, |iova, ptes| { + self.walk(iova_range, Missing::Skip, false, false, |iova, ptes| { match ptes.iter().position(|pte| pte.load(Ordering::Relaxed) != 0) { Some(idx) => { pr_err!( @@ -1189,7 +1225,7 @@ impl UatPageTable { prot ); let prot = self.stored(prot); - self.walk(iova_range, true, false, true, |iova, ptes| { + self.walk(iova_range, Missing::Admit, false, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { let ptev = pte.load(Ordering::Relaxed); if ptev & PTE_TYPE_BITS != PTE_TYPE_LEAF_TABLE { @@ -1208,7 +1244,7 @@ impl UatPageTable { pub(crate) fn unmap_pages(&mut self, iova_range: Range) -> Result { mod_pr_debug!("UATPageTable::unmap_pages: {:#x?}\n", iova_range); - self.walk(iova_range, false, false, true, |iova, ptes| { + self.walk(iova_range, Missing::Skip, false, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { if pte.load(Ordering::Relaxed) & PTE_TYPE_LEAF_TABLE == 0 { pr_err!( @@ -1225,7 +1261,7 @@ impl UatPageTable { /// Discards an aligned map operation that failed before acquiring a GPUVA owner. /// Missing tables and leaves are expected; existing table storage stays allocated. pub(crate) fn discard_partial_map(&mut self, iova_range: Range) -> Result { - self.walk(iova_range, false, false, true, |_, ptes| { + self.walk(iova_range, Missing::Skip, false, true, |_, ptes| { for pte in ptes { pte.store(0, Ordering::Relaxed); } @@ -1241,7 +1277,7 @@ impl Drop for UatPageTable { } mod_pr_debug!("UATPageTable::drop range: {:#x?}\n", &self.va_range); if self - .with_pages(self.va_range.clone(), false, true, |iova, ptes| { + .with_pages(self.va_range.clone(), Missing::Skip, true, |iova, ptes| { for (idx, pte) in ptes.iter().enumerate() { if pte.load(Ordering::Relaxed) != 0 { pr_err!( @@ -1462,6 +1498,35 @@ mod pgtable_charge_tests { Ok(()) } + static DRIVER_MAP: Ledger = Ledger::new(); + + #[test] + fn the_tables_of_a_driver_map_are_charged_but_never_refused() -> Result { + // Room for the root alone, against the client's and the device's limit. + DRIVER_MAP.set_limits(Limits { + device: PG, + client: PG, + }); + let client = Client::new()?; + let mut pt = UatPageTable::new(42, 42)?; + pt.charge_to(Usage::new(&DRIVER_MAP, client.clone())); + let range = 64 * LEAF_SPAN..66 * LEAF_SPAN; + assert_eq!(pt.prepare_map(range.clone()), Err(ENOMEM)); + assert_eq!((client.committed(), pt.tables), (PG, 0)); + assert_eq!(DRIVER_MAP.refused.load(Ordering::Relaxed), 1); + // One level-1 table and two leaf tables, past both limits. + pt.prepare_driver_map(range.clone())?; + assert_eq!((client.committed(), client.resident()), (4 * PG, 4 * PG)); + assert_eq!(pt.tables, 3); + assert_eq!(DRIVER_MAP.refused.load(Ordering::Relaxed), 1); + // They count against the next bind. + assert_eq!(pt.prepare_map(66 * LEAF_SPAN..67 * LEAF_SPAN), Err(ENOMEM)); + drop(pt); + assert_eq!(client.committed(), 0); + assert_eq!(DRIVER_MAP.user_committed.load(Ordering::Relaxed), 0); + Ok(()) + } + static REFUSE_SHARED: Ledger = Ledger::new(); #[test] diff --git a/tools/asahi/asahi-driver-map-charge-tests.py b/tools/asahi/asahi-driver-map-charge-tests.py new file mode 100644 index 0000000000000..d95446586e27b --- /dev/null +++ b/tools/asahi/asahi-driver-map-charge-tests.py @@ -0,0 +1,348 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-2.0-only OR MIT +"""Run the page-table charge of driver mappings and binds, actual bodies, at the memory limits. + +The harness compiles from drivers/gpu/drm/asahi/pgtable.rs the page-table walk (walk(), +walk_inner(), free_table()) with alloc_pages(), prepare_map(), prepare_driver_map(), charge_to() +and Drop; from memacct.rs Ledger::reserve(), Usage, try_add_within() and sub(); and from mmu.rs +VmInner::map_node(), which makes every mapping of the driver in a client's address space. They run +against a model of the page allocator that counts live pages. + +What it shows: +- at the client's limit and at the device's, map_node() succeeds: its tables are allocated and + charged, and nothing is counted as refused; +- at the same limits the tables of a bind (alloc_pages() and prepare_map()) are refused with + ENOMEM, charged nothing and freed, also right after a driver mapping went past the limit; +- below the limits both paths charge the same; +- a driver mapping whose leaves are taken still fails with EBUSY before a table is allocated, and + one the page allocator has no page for still fails with ENOMEM, charging only the tables kept; +- dropping the page table gives back every page and every charged byte. +Source checks: bind_object() and sm_step_map() do not use the driver path. + +Not shown: kernel or GPU execution, the memory cgroup, or which submissions need a new table. +""" +import argparse +import json +from pathlib import Path +import re +import subprocess + +ROOT = Path(__file__).resolve().parents[2] / 'drivers/gpu/drm/asahi' + +MUTATIONS = { + # The driver path refuses again. + 'admit-driver-map': ('pgtable.rs', 'self.prepare_tables(range, Missing::Commit)', + 'self.prepare_tables(range, Missing::Admit)'), + 'map-node-admits': ('mmu.rs', 'self.page_table.prepare_driver_map(node.start()..end)?;', + 'self.page_table.prepare_map(node.start()..end)?;'), + # Binds are no longer bounded. + 'commit-prepared-bind': ('pgtable.rs', 'self.prepare_tables(range, Missing::Admit)', + 'self.prepare_tables(range, Missing::Commit)'), + 'commit-bind': ('pgtable.rs', 'self.with_pages(iova_range, Missing::Admit, false, |_, _| Ok(()))', + 'self.with_pages(iova_range, Missing::Commit, false, |_, _| Ok(()))'), + # Driver tables are not counted. + 'uncharged-driver-map': ('pgtable.rs', 'charge.add(UAT_PGSZ as u64);', ''), +} + + +def item(source, signature): + start = source.index(signature) + opening = source.index('{', start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] + + +def optional(source, signature): + return item(source, signature) if signature in source else '' + + +PRELUDE = r''' +#![allow(dead_code, unused_imports, unused_macros, unused_variables, unused_mut, unused_unsafe, unexpected_cfgs, unreachable_code)] +use std::cell::Cell; +use std::collections::HashMap; +use std::mem::size_of; +use std::ops::Range; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +type Error = i32; +type Result = std::result::Result; +const EIO: Error = -5; +const ENOMEM: Error = -12; +const EBUSY: Error = -16; +const EINVAL: Error = -22; +const EOVERFLOW: Error = -75; +type PhysicalAddr = u64; +type Gfp = u32; +const GFP_KERNEL: Gfp = 1; +const GFP_KERNEL_ACCOUNT: Gfp = 3; +const __GFP_ZERO: Gfp = 4; +macro_rules! pr_err { ($($t:tt)*) => { { let _ = format!($($t)*); } } } +macro_rules! pr_warn { ($($t:tt)*) => { panic!($($t)*) } } +macro_rules! mod_pr_debug { ($($t:tt)*) => { { let _ = format!($($t)*); } } } +macro_rules! dev_err { ($($t:tt)*) => { panic!("dev_err") } } +fn align(value: u64, to: u64) -> u64 { (value + to - 1) & !(to - 1) } +fn clean_poc(_: *const u8, _: usize) {} +fn poc_barrier() {} +mod mem { pub fn sync() {} } +struct KVec(Vec); +impl KVec { + fn new() -> Self { Self(Vec::new()) } + fn reserve(&mut self, n: usize, _: Gfp) -> Result { self.0.reserve(n); Ok(()) } + fn push_within_capacity(&mut self, v: T) -> Result { self.0.push(v); Ok(()) } + fn contains(&self, v: &T) -> bool { self.0.contains(v) } + fn retain(&mut self, f: impl FnMut(&mut T) -> bool) { self.0.retain_mut(f) } + fn swap_remove(&mut self, i: usize) -> T { self.0.swap_remove(i) } + fn iter(&self) -> std::slice::Iter<'_, T> { self.0.iter() } +} +// The page allocator: fake physical addresses inside the 42-bit output range. +#[repr(C, align(16384))] +struct Frame([u8; 16384]); +thread_local! { + static FRAMES: std::cell::RefCell>> = Default::default(); + static NEXT: Cell = const { Cell::new(0x8_0000_0000) }; + /// Pages the allocator still has. + static ROOM: Cell = const { Cell::new(usize::MAX) }; +} +fn live() -> usize { FRAMES.with(|f| f.borrow().len()) } +struct Page(u64); +impl Page { + fn alloc_page(_: Gfp) -> Result { + if ROOM.get() == 0 { return Err(ENOMEM); } + ROOM.set(ROOM.get() - 1); + let phys = NEXT.get(); + NEXT.set(phys + 16384); + FRAMES.with(|f| f.borrow_mut().insert(phys, Box::new(Frame([0; 16384])))); + Ok(Page(phys)) + } + fn phys(&self) -> u64 { self.0 } + fn into_phys(self) -> u64 { let p = self.0; std::mem::forget(self); p } + unsafe fn from_phys(phys: u64) -> Page { Page(phys) } + unsafe fn borrow_phys(phys: &u64) -> Option { FRAMES.with(|f| f.borrow().contains_key(phys)).then_some(*phys) } + fn with_pointer_into_page(&self, offset: usize, len: usize, + f: impl FnOnce(*mut u8) -> Result) -> Result { + assert!(offset + len <= 16384); + let p = FRAMES.with(|m| m.borrow_mut().get_mut(&self.0).expect("live page").0.as_mut_ptr()); + f(unsafe { p.add(offset) }) + } +} +impl Drop for Page { + fn drop(&mut self) { assert!(FRAMES.with(|f| f.borrow_mut().remove(&self.0)).is_some(), "double free"); } +} +struct ReservedTables; +impl ReservedTables { fn contains(&self, _: u64) -> bool { false } } +unsafe fn with_table(_: Option<&ReservedTables>, phys: u64, offset: usize, len: usize, + f: impl FnOnce(*mut u8) -> Result) -> Result { + std::mem::ManuallyDrop::new(Page(phys)).with_pointer_into_page(offset, len, f) +} +struct Client { committed: AtomicU64, resident: AtomicU64 } +impl Client { + fn new() -> Arc { Arc::new(Self { committed: AtomicU64::new(0), resident: AtomicU64::new(0) }) } + fn committed(&self) -> u64 { self.committed.load(Ordering::Relaxed) } + fn resident(&self) -> u64 { self.resident.load(Ordering::Relaxed) } +} +''' + +MODEL = r''' +// What map_node() needs of a VM: no firmware handoff, no invalidation. +struct UatInner { m4_adopted: bool, failed: AtomicBool } +impl UatInner { fn lock_m4_upper(&self, _: bool) -> Result<()> { Ok(()) } } +struct Dev; +impl Dev { fn as_ref(&self) -> &Dev { self } } +type Prot = u64; +struct KernelMappingInner { mapped_size: usize } +mod mm { + pub struct Node { pub start: u64, pub inner: T, pub a: std::marker::PhantomData } + impl Node { pub fn start(&self) -> u64 { self.start } } + impl std::ops::Deref for Node { type Target = T; fn deref(&self) -> &T { &self.inner } } +} +struct VmInner { page_table: UatPageTable, uat_inner: Arc, is_kernel: bool, dev: Dev } +impl VmInner { + fn mapping_mutation(&self) {} + fn finish_failed_map(&mut self, _: u64, _: usize) {} + fn tlbi_contexts_naming_root(&self, _: u64, _: usize) {} + /// Stores the leaves; the tables must already exist. + fn map_node_prepared(&mut self, node: &mm::Node<(), KernelMappingInner>, _: Prot) -> Result { + let mut stored = 0; + let range = node.start()..node.start() + node.mapped_size as u64; + self.page_table.walk(range, SKIP, false, true, |_, ptes| { + for pte in ptes { pte.store(0x403, Ordering::Relaxed); } + stored += ptes.len() * UAT_PGSZ; + Ok(()) + })?; + assert_eq!(stored, node.mapped_size, "a leaf had no table"); + Ok(()) + } +''' + +MAIN = r''' +} +const PG: u64 = UAT_PGSZ as u64; +const LEAF_SPAN: u64 = PG << UAT_LVBIT; +fn vm(ledger: &'static Ledger, client: &Arc) -> VmInner { + ROOM.set(usize::MAX); + let ttb = Page::alloc_page(GFP_KERNEL | __GFP_ZERO).unwrap().into_phys(); + let mut page_table = UatPageTable { + ttb, ttb_owned: true, retained: false, reserved: None, native_gpu: false, driver_tables: None, + va_range: 0..1u64 << 42, ias_mask: (1u64 << 42) - 1, oas_mask: (1u64 << 42) - 1, + clean_poc: false, tables: 0, charge: None, + }; + page_table.charge_to(Usage::new(ledger, client.clone())); + VmInner { page_table, uat_inner: Arc::new(UatInner { m4_adopted: false, failed: AtomicBool::new(false) }), + is_kernel: false, dev: Dev } +} +fn node(start: u64, size: u64) -> mm::Node<(), KernelMappingInner> { + mm::Node { start, inner: KernelMappingInner { mapped_size: size as usize }, a: std::marker::PhantomData } +} +fn clear(vm: &mut VmInner, range: Range) { + vm.page_table.walk(range, SKIP, false, true, |_, ptes| { + for pte in ptes { pte.store(0, Ordering::Relaxed); } + Ok(()) + }).unwrap(); +} +fn at_limit(name: &str, limits: Limits) { + let ledger: &'static Ledger = Box::leak(Box::new(Ledger::new())); + ledger.set_limits(limits); + let client = Client::new(); + let mut vm = vm(ledger, &client); + assert_eq!(client.committed(), PG, "{name}: root"); + let (a, b) = (64 * LEAF_SPAN, 65 * LEAF_SPAN); + // Two leaf tables below one level-1 table, all past the limit. + assert_eq!(vm.map_node(&node(a, 2 * LEAF_SPAN), 0), Ok(()), "{name}: a driver mapping is refused at the limit"); + assert_eq!((client.committed(), client.resident()), (4 * PG, 4 * PG), "{name}: charged"); + assert_eq!(ledger.user_committed.load(Ordering::Relaxed), 4 * PG); + assert_eq!(ledger.refused.load(Ordering::Relaxed), 0, "{name}: refusals"); + assert_eq!((vm.page_table.tables, live()), (3, 4)); + // The next mapping needs no table. + clear(&mut vm, a..b); + assert_eq!(vm.map_node(&node(a, PG), 0), Ok(())); + assert_eq!(client.committed(), 4 * PG); + // Binds stay bounded, also past the limit. + let free = 70 * LEAF_SPAN; + assert_eq!(vm.page_table.alloc_pages(free..free + PG), Err(ENOMEM), "{name}: a bind is admitted past the limit"); + assert_eq!(vm.page_table.prepare_map(free..free + PG), Err(ENOMEM), "{name}: a prepared bind is admitted past the limit"); + assert_eq!(ledger.refused.load(Ordering::Relaxed), 2); + assert_eq!((client.committed(), vm.page_table.tables, live()), (4 * PG, 3, 4)); + clear(&mut vm, a..a + 2 * LEAF_SPAN); + drop(vm); + assert_eq!((client.committed(), client.resident(), live()), (0, 0, 0), "{name}: left behind"); + assert_eq!(ledger.user_committed.load(Ordering::Relaxed), 0); + assert_eq!(ledger.user_resident.load(Ordering::Relaxed), 0); +} +fn below_the_limits() { + let ledger: &'static Ledger = Box::leak(Box::new(Ledger::new())); + ledger.set_limits(Limits { device: 100 * PG, client: 50 * PG }); + let client = Client::new(); + let mut vm = vm(ledger, &client); + vm.map_node(&node(64 * LEAF_SPAN, PG), 0).unwrap(); + assert_eq!(client.committed(), 3 * PG); + vm.page_table.alloc_pages(65 * LEAF_SPAN..65 * LEAF_SPAN + PG).unwrap(); + assert_eq!(client.committed(), 4 * PG); + vm.page_table.prepare_map(66 * LEAF_SPAN..66 * LEAF_SPAN + PG).unwrap(); + assert_eq!((client.committed(), client.resident()), (5 * PG, 5 * PG)); + clear(&mut vm, 64 * LEAF_SPAN..67 * LEAF_SPAN); + drop(vm); + assert_eq!((client.committed(), live()), (0, 0)); +} +fn other_errors() { + let ledger: &'static Ledger = Box::leak(Box::new(Ledger::new())); + ledger.set_limits(Limits { device: PG, client: PG }); + let client = Client::new(); + let mut vm = vm(ledger, &client); + let at = 64 * LEAF_SPAN; + assert_eq!(vm.map_node(&node(at + 1, PG), 0), Err(EINVAL)); + vm.map_node(&node(at + PG, PG), 0).unwrap(); + let before = (client.committed(), vm.page_table.tables, live()); + assert_eq!(vm.map_node(&node(at, 2 * LEAF_SPAN), 0), Err(EBUSY)); + assert_eq!((client.committed(), vm.page_table.tables, live()), before); + // The page allocator fails after one more table: that one stays, and only it is charged. + ROOM.set(1); + assert_eq!(vm.map_node(&node(at + LEAF_SPAN, 2 * LEAF_SPAN), 0), Err(ENOMEM)); + assert_eq!((client.committed(), vm.page_table.tables, live()), (before.0 + PG, before.1 + 1, before.2 + 1)); + assert_eq!(ledger.refused.load(Ordering::Relaxed), 0); + ROOM.set(usize::MAX); + vm.map_node(&node(at + LEAF_SPAN, 2 * LEAF_SPAN), 0).unwrap(); + clear(&mut vm, at..at + 4 * LEAF_SPAN); + drop(vm); + assert_eq!((client.committed(), client.resident(), live()), (0, 0, 0)); +} +fn main() { + at_limit("client limit", Limits { device: 0, client: PG }); + at_limit("device limit", Limits { device: PG, client: 0 }); + at_limit("both limits", Limits { device: PG, client: PG }); + below_the_limits(); + other_errors(); + println!("ok: driver mappings are charged and not refused at the limits, binds are refused"); +} +''' + + +def sources(mutation): + text = {name: (ROOT / name).read_text() for name in ('pgtable.rs', 'memacct.rs', 'mmu.rs')} + if mutation: + name, old, new = MUTATIONS[mutation] + assert text[name].count(old) == 1, f'{mutation}: {text[name].count(old)} matches' + text[name] = text[name].replace(old, new) + return text + + +def source_checks(mmu): + for signature in ("pub(crate) fn bind_object<'drm>(", 'fn sm_step_map'): + assert 'prepare_driver_map' not in item(mmu, signature), f'{signature} uses the driver path' + + +def harness(text): + pt, acct, mmu = text['pgtable.rs'], text['memacct.rs'], text['mmu.rs'] + consts = '\n'.join(re.search(rf'^(?:pub\(crate\) )?const {name}: [^;]*;', pt, re.M).group(0) for name in ( + 'UAT_PGBIT', 'UAT_PGSZ', 'UAT_PGMSK', 'PTE_BIT', 'PTE_SIZE', 'UAT_NPTE', 'UAT_LVBIT', 'UAT_LVSZ', + 'UAT_LVMSK', 'UAT_LEVELS', 'PTE_TYPE_BITS', 'PTE_TYPE_LEAF_TABLE')) + # A tree without the driver path walks with a bool. + missing = optional(pt, 'enum Missing {') + if missing: + missing = '#[derive(Clone, Copy, PartialEq, Eq)]\n' + missing + '\nconst SKIP: Missing = Missing::Skip;\n' + else: + missing = 'const SKIP: bool = false;\n' + table = item(pt, 'pub(crate) struct UatPageTable {').replace('crate::memacct::', '') + methods = [item(pt, 'pub(crate) fn charge_to('), item(pt, 'fn with_pages('), item(pt, 'fn walk('), + item(pt, 'fn walk_inner('), item(pt, 'fn cleans_poc('), item(pt, 'fn free_table('), + item(pt, 'pub(crate) fn alloc_pages('), item(pt, 'pub(crate) fn prepare_map('), + item(pt, 'pub(crate) fn ensure_unmapped('), item(pt, 'pub(crate) fn discard_partial_map('), + optional(pt, 'pub(crate) fn prepare_driver_map('), optional(pt, 'fn prepare_tables(')] + methods = '\n'.join(methods).replace('crate::memacct::', '').replace('crate::mem::sync()', 'mem::sync()') + ledger = item(acct, 'pub(crate) struct Ledger {') + '\nimpl Ledger {\n' + '\n'.join( + item(acct, s) for s in ('pub(crate) const fn new() -> Self {', 'pub(crate) fn set_limits(', + 'fn reserve(&self')) + '\n}\n' + ledger += '\n'.join(item(acct, s) for s in ('pub(crate) struct Limits {', 'fn try_add_within(', 'fn sub(')) + usage = '\n'.join(item(acct, s) for s in ('pub(crate) struct Usage {', 'impl Usage {', 'impl Drop for Usage {')) + return '\n'.join([ + PRELUDE, consts, 'type Pte = AtomicU64;', missing, ledger, usage, table, + 'impl UatPageTable {', methods, '}', item(pt, 'impl Drop for UatPageTable {'), + MODEL, item(mmu, 'fn map_node('), MAIN, + ]) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--out', type=Path, required=True) + parser.add_argument('--mutation', choices=MUTATIONS) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + text = sources(args.mutation) + source_checks(text['mmu.rs']) + source, binary = args.out / 'driver_map_charge.rs', args.out / 'driver_map_charge' + source.write_text(harness(text)) + built = subprocess.run(['rustc', '--edition=2021', '-Cdebug-assertions=on', str(source), '-o', str(binary)], + capture_output=True, text=True) + if built.returncode: + print(built.stderr[-6000:]) + raise SystemExit('BUILD FAILED') + ran = subprocess.run([str(binary)], capture_output=True, text=True, timeout=60) + print(ran.stdout, ran.stderr, end='') + print(json.dumps({'mutation': args.mutation, 'exit': ran.returncode})) + raise SystemExit(0 if ran.returncode == 0 else 1) + + +if __name__ == '__main__': + main() diff --git a/tools/asahi/g14-v27-2-fw-window-gc-tests.py b/tools/asahi/g14-v27-2-fw-window-gc-tests.py index ee358b3a468ed..10376ab8dfecd 100644 --- a/tools/asahi/g14-v27-2-fw-window-gc-tests.py +++ b/tools/asahi/g14-v27-2-fw-window-gc-tests.py @@ -559,7 +559,7 @@ def build_source(mutation: str | None) -> str: l2 }} - fn prepare_map(&mut self, range: Range) -> Result {{ + fn prepare_driver_map(&mut self, range: Range) -> Result {{ if range.is_empty() {{ return Ok(()); }} diff --git a/tools/asahi/run-host-tests.py b/tools/asahi/run-host-tests.py index a805fbfd76ff0..c35c3a7504b08 100644 --- a/tools/asahi/run-host-tests.py +++ b/tools/asahi/run-host-tests.py @@ -202,6 +202,9 @@ def mutations(flag, names, base, expect=KILL): # The old revision returns the buffers of a failed job before stopping the engine. 'apple-scaler-recovery-tests.py': [([], PASS), (['--ref', '40e5e29cc915a421fb2676f895ff7dcc3f47a224'], KILL)], + 'asahi-driver-map-charge-tests.py': [(out(), PASS)] + + mutations('--mutation', ('admit-driver-map', 'map-node-admits', 'commit-prepared-bind', + 'commit-bind', 'uncharged-driver-map'), out()), 'asahi-stats-raw-tests.py': [([], PASS)], 'agx-stats-busy-tests.py': [([], PASS), (['--negative-control'], PASS)], 'atc-cio-sleep-tests.py': [(out('--output'), PASS)], diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py index 8b39a4ce54783..12f800398c116 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-mmu-retention.py @@ -65,10 +65,10 @@ def body(source,marker): ''' map_drop=body(mm,'impl Drop for KernelMapping {') # The actual PageTable Drop chooses whether to visit/free physical pages; the mock records those effects. -pages=r''' +pages='#[derive(Clone,Copy)]\n'+body(pt,'enum Missing {')+r''' struct Page;impl Page{unsafe fn from_phys(_p:u64){ROOT_FREES.fetch_add(1,Ordering::Relaxed);}} struct UatPageTable{retained:bool,ttb_owned:bool,ttb:u64,va_range:Range} -impl UatPageTable{fn new()->Self{Self{retained:false,ttb_owned:true,ttb:0x804000000,va_range:0..0x4000}}fn with_pages(&mut self,_r:Range,_a:bool,_f:bool,mut f:F)->Result where F:FnMut(u64,&[AtomicU64])->Result{TREE_FREES.fetch_add(1,Ordering::Relaxed);f(0,&[AtomicU64::new(0)])} +impl UatPageTable{fn new()->Self{Self{retained:false,ttb_owned:true,ttb:0x804000000,va_range:0..0x4000}}fn with_pages(&mut self,_r:Range,_a:Missing,_f:bool,mut f:F)->Result where F:FnMut(u64,&[AtomicU64])->Result{TREE_FREES.fetch_add(1,Ordering::Relaxed);f(0,&[AtomicU64::new(0)])} '''+body(pt,'pub(crate) fn retain(')+'}\n'+body(pt,'impl Drop for UatPageTable {') bindings=r''' #[derive(Clone,Copy)]struct Token(u32);impl Token{fn last_slot(&self)->u32{self.0}} diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-words.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-words.py index 901b1264553ea..5678850d9d8be 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-words.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-vm-words.py @@ -97,7 +97,7 @@ def body(source,marker): } struct Table{uat:Rc,rolled_back:Cell,busy:bool} impl Table{ - fn prepare_map(&mut self,_r:Range)->Result{assert!(!self.uat.held.get(),"allocation under PPL");Ok(())} + fn prepare_driver_map(&mut self,_r:Range)->Result{assert!(!self.uat.held.get(),"allocation under PPL");Ok(())} fn discard_partial_map(&mut self,_r:Range)->Result{assert!(self.uat.held.get(),"rollback outside PPL");self.rolled_back.set(true);Ok(())} // Another mapping's live leaves in the range refuse the map before any store. fn ensure_unmapped(&mut self,_r:Range)->Result{assert!(self.uat.held.get(),"live-leaf check outside PPL");if self.busy{Err(EBUSY)}else{Ok(())}}