diff --git a/drivers/gpu/drm/asahi/g16/gate.rs b/drivers/gpu/drm/asahi/g16/gate.rs index 5010ab46dc97c..e7e5234d1f537 100644 --- a/drivers/gpu/drm/asahi/g16/gate.rs +++ b/drivers/gpu/drm/asahi/g16/gate.rs @@ -130,34 +130,28 @@ fn program( /// VDM admission for a batch of root streams under an already-held VM read lock. /// Each root stream opens with the G16 barrier, with or without the USC cache invalidate. -/// Reads only the 4-byte root word for a single pass to minimize PoC cache maintenance, -/// and caches up to 256 intra-page bytes across multi-pass batches. Each normal root stream -/// opens with the G16 barrier, with or without the USC cache invalidate. +/// Batches 4-byte root reads through [`mmu::VmReadGuard::read_user_u32_batch`] so multi-pass +/// submits clean/invalidate only the minimal cache line(s) covering each 4-byte root word +/// with a single `poc_barrier()` across the batch. pub(crate) fn vdm_batch_locked(guard: &mut mmu::VmReadGuard<'_>, vas: &[u64]) -> Result { if vas.is_empty() || !params::stream_gate() { return Ok(()); } - let mut win_va = 0u64; - let mut win_len = 0usize; - let mut buf = [0u8; 256]; - let max_read = if vas.len() == 1 { 4 } else { buf.len() }; for &va in vas { - let end = va.checked_add(4).ok_or(EINVAL)?; - let cached = win_len != 0 && va >= win_va && end <= win_va + win_len as u64; - if !cached { - let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); - let len = max_read.min(in_page); - if len < 4 { - return Err(EINVAL); - } - guard.read_user(va, &mut buf[..len]).map_err(|_| EFAULT)?; - win_va = va; - win_len = len; + let _ = va.checked_add(4).ok_or(EINVAL)?; + let in_page = mmu::UAT_PGSZ - (va as usize & mmu::UAT_PGMSK); + if in_page < 4 { + return Err(EINVAL); } - let off = (va - win_va) as usize; - let word = u32::from_le_bytes([buf[off], buf[off + 1], buf[off + 2], buf[off + 3]]); - if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { - return Err(reject("VDM root", va, &[word])); + } + let mut words = [0u32; 64]; + for chunk in vas.chunks(words.len()) { + let out = &mut words[..chunk.len()]; + guard.read_user_u32_batch(chunk, out).map_err(|_| EFAULT)?; + for (&va, &word) in chunk.iter().zip(out.iter()) { + if word & !VDM_ROOT_USC_INVAL != VDM_ROOT { + return Err(reject("VDM root", va, &[word])); + } } } Ok(()) diff --git a/drivers/gpu/drm/asahi/mmu.rs b/drivers/gpu/drm/asahi/mmu.rs index dab93b16914ab..16ca68c059c58 100644 --- a/drivers/gpu/drm/asahi/mmu.rs +++ b/drivers/gpu/drm/asahi/mmu.rs @@ -100,6 +100,11 @@ use crate::{ // KernelMapping protection types pub(crate) use crate::pgtable::Prot; pub(crate) use pgtable::prot::*; + +#[cfg(any(CONFIG_DRM_ASAHI_UAT_ADOPTION, CONFIG_DRM_ASAHI_G16))] +extern "C" { + fn asahi_copy_gpu_read_once(dst: *mut u8, src: *const u8, len: usize); +} pub(crate) use pgtable::{ UatPageTable, UAT_PGBIT, @@ -536,6 +541,11 @@ impl VmReadGuard<'_> { pub(crate) fn read_user(&mut self, va: u64, buf: &mut [u8]) -> Result { Vm::read_user_locked(&mut self.0, va, buf) } + + #[cfg(CONFIG_DRM_ASAHI_G16)] + pub(crate) fn read_user_u32_batch(&mut self, vas: &[u64], out: &mut [u32]) -> Result { + Vm::read_user_u32_batch_locked(&mut self.0, vas, out) + } } /// Slot binding-related inner data for a Vm instance. @@ -2788,7 +2798,7 @@ impl Vm { if !Prot::from_pte(leaf).allows_gpu(true, false) { return Err(EFAULT); } - let phys = inner.page_table.translate_iova(page).map_err(|_| EFAULT)?; + let phys = inner.page_table.leaf_phys(leaf); // SAFETY: `phys` is checked to be a RAM page; it stays mapped (and its backing pinned) // while the VM reservation lock is held, and is only read here. let ram = unsafe { kernel::page::Page::borrow_phys(&phys) }.ok_or(EFAULT)?; @@ -2796,9 +2806,9 @@ impl Vm { ram.with_pointer_into_page(within, count, |p| { pgtable::clean_invalidate_poc(p, count); pgtable::poc_barrier(); - // SAFETY: with_pointer_into_page() checked that `count` bytes at `p` are inside the - // page, and `target` holds exactly `count` bytes. - unsafe { core::ptr::copy_nonoverlapping(p, target.as_mut_ptr(), count) }; + // SAFETY: The source is in the mapped page, and the private destination holds + // `count` bytes. The helper permits concurrent writes to the source. + unsafe { asahi_copy_gpu_read_once(target.as_mut_ptr(), p, count) }; Ok(()) })?; done += count; @@ -2806,6 +2816,98 @@ impl Vm { Ok(()) } + /// Reads one 4-byte little-endian word from each GPU VA in `vas` under the held VM + /// reservation lock, cleaning and invalidating only the minimal cache line(s) covering each + /// 4-byte word and coalescing to a single `poc_barrier()` per chunk of up to 64 words. + #[cfg(CONFIG_DRM_ASAHI_G16)] + fn read_user_u32_batch_locked(inner: &mut VmInner, vas: &[u64], out: &mut [u32]) -> Result { + const MAX_BATCH: usize = 64; + if vas.len() != out.len() { + return Err(EINVAL); + } + if vas.is_empty() { + return Ok(()); + } + let line_mask = (pgtable::dcache_line_size() as u64).saturating_sub(1); + let page_mask = UAT_PGMSK as u64; + for (va_chunk, out_chunk) in vas.chunks(MAX_BATCH).zip(out.chunks_mut(MAX_BATCH)) { + let mut phys_addrs = [0u64; MAX_BATCH]; + let mut cached_page: Option<(u64, PhysicalAddr)> = None; + // A later walk can fail. Complete any issued maintenance while the VM + // reservation is still held, including on those error paths. + let mut need_barrier = kernel::types::ScopeGuard::new_with_data(false, |issued| { + if issued { + pgtable::poc_barrier(); + } + }); + for (i, &va) in va_chunk.iter().enumerate() { + let _ = va.checked_add(4).ok_or(EFAULT)?; + let page = va & !page_mask; + let within = (va - page) as usize; + if within + 4 > UAT_PGSZ { + phys_addrs[i] = u64::MAX; + continue; + } + let phys = match cached_page { + Some((cached_va, cached_phys)) if cached_va == page => cached_phys, + _ => { + if page < inner.va_range.start || page >= inner.va_range.end { + return Err(EFAULT); + } + let leaf = inner.page_table.leaf_entry(page).map_err(|_| EFAULT)?; + if !Prot::from_pte(leaf).allows_gpu(true, false) { + return Err(EFAULT); + } + let phys = inner.page_table.leaf_phys(leaf); + // SAFETY: The VM reservation pins the backing through both passes. + unsafe { kernel::page::Page::borrow_phys(&phys) }.ok_or(EFAULT)?; + cached_page = Some((page, phys)); + phys + } + }; + let phys_byte = phys | (within as u64); + let line0 = phys_byte & !line_mask; + let line1 = (phys_byte + 3) & !line_mask; + let already_cleaned = line0 == line1 + && phys_addrs[..i].iter().any(|&prev| { + prev != u64::MAX + && ((prev & !line_mask) == line0 || ((prev + 3) & !line_mask) == line0) + }); + if !already_cleaned { + // SAFETY: Both the cache hit and miss yield a checked, pinned RAM page. + let ram = unsafe { kernel::page::Page::borrow_phys_unchecked(&phys) }; + ram.with_pointer_into_page(within, 4, |p| { + pgtable::clean_invalidate_poc(p, 4); + Ok(()) + })?; + *need_barrier = true; + } + phys_addrs[i] = phys_byte; + } + drop(need_barrier); + for (i, &phys_byte) in phys_addrs[..va_chunk.len()].iter().enumerate() { + let mut bytes = [0u8; 4]; + if phys_byte == u64::MAX { + Self::read_user_locked(inner, va_chunk[i], &mut bytes)?; + } else { + let phys = phys_byte & !page_mask; + let within = (phys_byte & page_mask) as usize; + // SAFETY: Each non-sentinel entry records a checked RAM page and offset. + // The VM reservation still pins that page. + let ram = unsafe { kernel::page::Page::borrow_phys_unchecked(&phys) }; + ram.with_pointer_into_page(within, 4, |p| { + // SAFETY: Both pointers cover four bytes and the destination is private. + // The helper permits concurrent writes to the mapped source. + unsafe { asahi_copy_gpu_read_once(bytes.as_mut_ptr(), p, 4) }; + Ok(()) + })?; + } + out_chunk[i] = u32::from_le_bytes(bytes); + } + } + Ok(()) + } + /// Status shared by every queue using this VM, if enabled by its GPU. /// Charges kernel memory sized by this VM's client to `client` ([`Self::memory_client`]), /// starting with the VM's page tables. diff --git a/drivers/gpu/drm/asahi/pgtable.rs b/drivers/gpu/drm/asahi/pgtable.rs index 381ad1acc7164..546131a6257c7 100644 --- a/drivers/gpu/drm/asahi/pgtable.rs +++ b/drivers/gpu/drm/asahi/pgtable.rs @@ -62,7 +62,7 @@ static DCACHE_LINE_SIZE: AtomicUsize = AtomicUsize::new(0); /// The system-wide minimum CPU line size, including heterogeneous CPUs. A local /// CTR_EL0 read can select too large a stride if the task migrates during the loop. #[inline(always)] -fn dcache_line_size() -> usize { +pub(crate) fn dcache_line_size() -> usize { let cached = DCACHE_LINE_SIZE.load(Ordering::Relaxed); if cached != 0 { return cached; @@ -966,10 +966,15 @@ impl UatPageTable { Ok(expected == visited && permitted) } + /// Physical page base from a resolved leaf, excluding attributes outside the output width. + pub(crate) fn leaf_phys(&self, entry: u64) -> PhysicalAddr { + entry & self.oas_mask & !(UAT_PGMSK as u64) + } + /// Resolves an existing leaf without creating page tables. pub(crate) fn translate_iova(&mut self, iova: u64) -> Result { let entry = self.leaf_entry(iova & !(UAT_PGMSK as u64))?; - Ok((entry & self.oas_mask & !(UAT_PGMSK as u64)) | (iova & UAT_PGMSK as u64)) + Ok(self.leaf_phys(entry) | (iova & UAT_PGMSK as u64)) } /// The page frame of every page of the page-aligned `iova_range`, in one walk: what diff --git a/drivers/gpu/drm/asahi/user_pages.c b/drivers/gpu/drm/asahi/user_pages.c index b0c9c4dbe8879..7a24754ac73c9 100644 --- a/drivers/gpu/drm/asahi/user_pages.c +++ b/drivers/gpu/drm/asahi/user_pages.c @@ -14,9 +14,30 @@ #include #include #include +#include #include "user_pages.h" +/* + * Snapshot a GPU mapping that userspace or the GPU can write concurrently. + * Only individual aligned loads are atomic; the buffer is not a transaction. + */ +void asahi_copy_gpu_read_once(u8 *dst, const u8 *src, size_t len) +{ + while (len && !IS_ALIGNED((unsigned long)src, sizeof(u32))) { + *dst++ = READ_ONCE(*src++); + len--; + } + while (len >= sizeof(u32)) { + put_unaligned(READ_ONCE(*(const u32 *)src), (u32 *)dst); + src += sizeof(u32); + dst += sizeof(u32); + len -= sizeof(u32); + } + while (len--) + *dst++ = READ_ONCE(*src++); +} + #ifdef CONFIG_MM_SUBPAGE /* Pinned fragments of a range; released only through asahi_unpin_user_fragments(). */ struct asahi_user_fragments { diff --git a/drivers/gpu/drm/asahi/user_pages.h b/drivers/gpu/drm/asahi/user_pages.h index d856192fdedfe..430fd7e4135c4 100644 --- a/drivers/gpu/drm/asahi/user_pages.h +++ b/drivers/gpu/drm/asahi/user_pages.h @@ -7,6 +7,9 @@ struct asahi_user_fragments; struct page; +/* Called from mmu.rs with a locally mapped source and a private destination. */ +void asahi_copy_gpu_read_once(u8 *dst, const u8 *src, size_t len); + /* Called from gem.rs. */ bool asahi_user_mm_is_subpage(void); long asahi_pin_user_fragments(unsigned long start, unsigned long nr_pages, diff --git a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py index eb48e6ce3ee65..93b285f31d194 100755 --- a/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py +++ b/tools/testing/selftests/drivers/gpu/asahi-m4/test-stream-gate.py @@ -5,13 +5,38 @@ import hashlib import json +import os import pathlib +import shlex import subprocess import tempfile ROOT = kernel_root() SOURCE = ROOT / 'drivers/gpu/drm/asahi/g16/gate.rs' +MMU_SOURCE = ROOT / 'drivers/gpu/drm/asahi/mmu.rs' OUT = output_dir() + +def extract_fn(text, marker): + start = text.index(marker) + line_start = text.rfind('\n', 0, start) + 1 + at = text.index('{', start) + depth = 1 + end = at + 1 + while depth: + depth += (text[end] == '{') - (text[end] == '}') + end += 1 + return text[line_start:end] + +pgtable = (MMU_SOURCE.parent / 'pgtable.rs').read_text() +mmu = MMU_SOURCE.read_text() +MMU_BATCH_FN = extract_fn(mmu, 'fn read_user_u32_batch_locked(') +MMU_SINGLE_FN = extract_fn(mmu, 'fn read_user_locked(') +READ_ONCE_FN = extract_fn( + (MMU_SOURCE.parent / 'user_pages.c').read_text(), 'void asahi_copy_gpu_read_once(' +) +SCOPE_GUARD = (ROOT / 'rust/kernel/types.rs').read_text() +SCOPE_GUARD = SCOPE_GUARD[SCOPE_GUARD.index('pub struct ScopeGuard'): + SCOPE_GUARD.index('/// Stores an opaque value')] harness = r''' #![allow(dead_code, unused_variables)] extern crate core; @@ -51,6 +76,9 @@ pub epoch: std::cell::Cell>, pub lock_calls: std::cell::Cell, pub read_calls: std::cell::Cell, + pub batch_read_calls: std::cell::Cell, + pub poc_barriers: std::cell::Cell, + pub poc_flushed_lines: std::cell::Cell, pub last_read_len: std::cell::Cell, } pub struct VmReadGuard<'a>(&'a Vm); @@ -66,6 +94,9 @@ pub fn read_user(&mut self, va: u64, out: &mut [u8]) -> Result { self.0.read_user(va, out) } + pub fn read_user_u32_batch(&mut self, vas: &[u64], out: &mut [u32]) -> Result { + self.0.read_user_u32_batch(vas, out) + } } impl Vm { pub fn region(&mut self, base: u64, bytes: Vec) { @@ -82,6 +113,7 @@ pub fn read_user(&self, va: u64, out: &mut [u8]) -> Result { self.read_calls.set(self.read_calls.get() + 1); self.last_read_len.set(out.len()); + self.poc_barriers.set(self.poc_barriers.get() + 1); let end = va.checked_add(out.len() as u64).ok_or(EFAULT)?; for r in &self.regions { if r.readable && va >= r.base && end <= r.base + r.bytes.len() as u64 { @@ -92,6 +124,61 @@ } Err(EFAULT) } + pub fn read_user_u32_batch(&self, vas: &[u64], out: &mut [u32]) -> Result { + if vas.len() != out.len() { + return Err(EINVAL); + } + if vas.is_empty() { + return Ok(()); + } + self.batch_read_calls.set(self.batch_read_calls.get() + 1); + self.last_read_len.set(4); + // Mirror production 64-byte cache-line dedup and single PoC barrier per 64-entry chunk. + let line_mask = 63u64; + for (va_chunk, out_chunk) in vas.chunks(64).zip(out.chunks_mut(64)) { + let mut seen: Vec = Vec::with_capacity(va_chunk.len()); + let mut need_barrier = false; + for &va in va_chunk { + let end = va.checked_add(4).ok_or(EFAULT)?; + if !self.contains(va, end) { + return Err(EFAULT); + } + let line0 = va & !line_mask; + let line1 = (va + 3) & !line_mask; + let already = line0 == line1 + && seen.iter().any(|&p| { + (p & !line_mask) == line0 || ((p + 3) & !line_mask) == line0 + }); + if !already { + let lines = if line0 == line1 { 1 } else { 2 }; + self.poc_flushed_lines.set(self.poc_flushed_lines.get() + lines); + need_barrier = true; + } + seen.push(va); + } + if need_barrier { + self.poc_barriers.set(self.poc_barriers.get() + 1); + } + for (i, &va) in va_chunk.iter().enumerate() { + let end = va + 4; + let mut raw = [0u8; 4]; + let mut found = false; + for r in &self.regions { + if r.readable && va >= r.base && end <= r.base + r.bytes.len() as u64 { + let at = (va - r.base) as usize; + raw.copy_from_slice(&r.bytes[at..at + 4]); + found = true; + break; + } + } + if !found { + return Err(EFAULT); + } + out_chunk[i] = u32::from_le_bytes(raw); + } + } + Ok(()) + } } } mod g16 { @@ -358,29 +445,33 @@ } } #[test] -fn vdm_batch_shares_lock_caches_window_and_rejects_bad_root() { +fn vdm_batch_shares_lock_coalesces_poc_and_rejects_bad_root() { let mut vm = mmu::Vm::default(); let mut page0 = vec![0u8; 0x4000]; let mut page1 = vec![0u8; 0x4000]; let root = 0x21000960u32.to_le_bytes(); - for off in [0usize, 0x20, 0x40, 0x80, 0x3ffc] { + for off in [0usize, 0x20, 0x40, 0x80, 0x400, 0x800, 0x3ffc] { page0[off..off + 4].copy_from_slice(&root); } page1[0x10..0x14].copy_from_slice(&root); vm.region(BASE, page0); vm.region(BASE + 0x4000, page1); - // Empty batch performs no reads. + // Empty batch performs no reads or PoC barriers. assert!(vdm_check(&vm, &[]).is_ok()); - assert_eq!(vm.read_calls.get(), 0); + assert_eq!(vm.batch_read_calls.get(), 0); + assert_eq!(vm.poc_barriers.get(), 0); - // Four adjacent VDM roots within 256 bytes share one lock and one read_user. + // Four VDM roots share one lock, one batch read, one PoC barrier, and deduplicate + // roots in the same 64-byte cache line (BASE and BASE + 0x20 share line 0). vm.lock_calls.set(0); assert!(vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x40, BASE + 0x80]).is_ok()); assert_eq!(vm.lock_calls.get(), 1); - assert_eq!(vm.read_calls.get(), 1); + assert_eq!(vm.batch_read_calls.get(), 1); + assert_eq!(vm.poc_barriers.get(), 1); + assert_eq!(vm.poc_flushed_lines.get(), 3); - // A bad root inside the same cached 256-byte window is still rejected. + // A bad root inside the batch is still rejected. vm.regions[0].bytes[0x80..0x84].copy_from_slice(&0xdeadbeefu32.to_le_bytes()); assert_eq!( vdm_check(&vm, &[BASE, BASE + 0x20, BASE + 0x80]), @@ -388,12 +479,31 @@ ); vm.regions[0].bytes[0x80..0x84].copy_from_slice(&root); - // Cross-page and end-of-page roots share one lock and never over-read past UAT_PGSZ. + // Streams >256 B apart, cross-page, and end-of-page share one lock and one PoC barrier, + // flushing only 1 line per distinct 4-byte root and never over-reading past UAT_PGSZ. vm.lock_calls.set(0); - vm.read_calls.set(0); - assert!(vdm_check(&vm, &[BASE, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); + vm.batch_read_calls.set(0); + vm.poc_barriers.set(0); + vm.poc_flushed_lines.set(0); + assert!(vdm_check(&vm, &[BASE, BASE + 0x400, BASE + 0x800, BASE + 0x3ffc, BASE + 0x4010]).is_ok()); assert_eq!(vm.lock_calls.get(), 1); - assert_eq!(vm.read_calls.get(), 3); + assert_eq!(vm.batch_read_calls.get(), 1); + assert_eq!(vm.poc_barriers.get(), 1); + assert_eq!(vm.poc_flushed_lines.get(), 5); + + // Page-crossing unaligned or wrapping VAs are rejected before reading. + assert_eq!(vdm_check(&vm, &[BASE + 0x3ffd]), Err(kernel::prelude::EINVAL)); + assert_eq!(vdm_check(&vm, &[BASE + 0x3ffe]), Err(kernel::prelude::EINVAL)); + assert_eq!(vdm_check(&vm, &[u64::MAX - 2]), Err(kernel::prelude::EINVAL)); + + // Unmapped VA fails with EFAULT. + assert_eq!(vdm_check(&vm, &[BASE, BASE + 0x8000]), Err(kernel::prelude::EFAULT)); + + // Batches larger than 64 entries chunk cleanly and still reject a bad root in chunk 2. + let mut big = vec![BASE; 70]; + assert!(vdm_check(&vm, &big).is_ok()); + big[68] = BASE + 0x100; // zeroed -> invalid VDM root + assert_eq!(vdm_check(&vm, &big), Err(kernel::prelude::EINVAL)); } #[test] fn cdm_batches_vm_read_lock_and_releases_on_resched() { @@ -430,7 +540,9 @@ let vm = vm_for(&[0x21000960]); assert!(vdm_check(&vm, &[BASE]).is_ok()); assert_eq!(vm.lock_calls.get(), 1); - assert_eq!(vm.read_calls.get(), 1); + assert_eq!(vm.batch_read_calls.get(), 1); + assert_eq!(vm.poc_barriers.get(), 1); + assert_eq!(vm.poc_flushed_lines.get(), 1); assert_eq!(vm.last_read_len.get(), 4); let mut words = launch(0, USC, 0); @@ -441,6 +553,297 @@ assert_eq!(cdm_vm.read_calls.get(), 1); assert_eq!(cdm_vm.last_read_len.get(), words.len() * 4); } +mod mmu_batch_poc_tests { + use core::cell::Cell; + use core::ops::Range; + use crate::kernel::prelude::*; + + type PhysicalAddr = u64; + const UAT_PGSZ: usize = 0x4000; + const UAT_PGMSK: usize = UAT_PGSZ - 1; + const PHYS_BASE: u64 = 0x1_0000_0000; + + std::thread_local! { + static CLEAN_CALLS: Cell = const { Cell::new(0) }; + static CLEAN_LINES: Cell = const { Cell::new(0) }; + static BARRIERS: Cell = const { Cell::new(0) }; + static OUTSTANDING: Cell = const { Cell::new(0) }; + static COPIES: Cell = const { Cell::new(0) }; + static RAM_CHECKS: Cell = const { Cell::new(0) }; + static WALK_CALLS: Cell = const { Cell::new(0) }; + static MEM_PTR: Cell = const { Cell::new(0) }; + static MEM_PAGES: Cell = const { Cell::new(0) }; + } + + mod pgtable { + use super::*; + pub(super) fn dcache_line_size() -> usize { 64 } + pub(super) fn clean_invalidate_poc(ptr: *const u8, len: usize) { + CLEAN_CALLS.with(|c| c.set(c.get() + 1)); + OUTSTANDING.with(|c| c.set(c.get() + 1)); + let line = dcache_line_size(); + let start = ptr as usize & !(line - 1); + let end = ptr as usize + len; + let count = (end - start + line - 1) / line; + CLEAN_LINES.with(|c| c.set(c.get() + count)); + } + pub(super) fn poc_barrier() { + BARRIERS.with(|c| c.set(c.get() + 1)); + OUTSTANDING.with(|c| c.set(0)); + } + } + + mod kernel { + pub mod types { + use core::ops::{Deref, DerefMut}; + SCOPE_GUARD_PRODUCTION + } + + pub mod page { + use super::super::*; + pub struct Page(usize); + static PAGES: [Page; 4] = [Page(0), Page(1), Page(2), Page(3)]; + impl Page { + pub unsafe fn borrow_phys(phys: &PhysicalAddr) -> Option<&'static Self> { + RAM_CHECKS.with(|c| c.set(c.get() + 1)); + let off = phys.checked_sub(PHYS_BASE)?; + if off & (UAT_PGMSK as u64) != 0 { + return None; + } + let idx = (off / UAT_PGSZ as u64) as usize; + if idx < MEM_PAGES.with(Cell::get) { + PAGES.get(idx) + } else { + None + } + } + pub unsafe fn borrow_phys_unchecked(phys: &PhysicalAddr) -> &Self { + let idx = ((phys - PHYS_BASE) / UAT_PGSZ as u64) as usize; + assert!(idx < MEM_PAGES.with(Cell::get)); + &PAGES[idx] + } + pub fn with_pointer_into_page(&self, within: usize, count: usize, f: F) -> Result + where + F: FnOnce(*const u8) -> Result, + { + if within + count > UAT_PGSZ { + return Err(EINVAL); + } + let base = MEM_PTR.with(Cell::get) as *const u8; + let ptr = unsafe { base.add(self.0 * UAT_PGSZ + within) }; + f(ptr) + } + } + } + } + + struct Prot(u64); + impl Prot { + fn from_pte(pte: u64) -> Self { Self(pte) } + fn allows_gpu(&self, read: bool, _write: bool) -> bool { !read || (self.0 & 1) != 0 } + } + + struct PageTable { + oas_mask: u64, + pages: Vec<(u64, Option, u64)>, + } + impl PageTable { + fn leaf_entry(&self, page: u64) -> Result { + WALK_CALLS.with(|c| c.set(c.get() + 1)); + self.pages.iter().find(|&&(va, _, _)| va == page) + .and_then(|&(_, phys, flags)| phys.map(|pa| pa | flags | (1 << 55))).ok_or(EFAULT) + } + LEAF_PHYS_PRODUCTION + TRANSLATE_IOVA_PRODUCTION + } + + #[repr(C, align(64))] + struct AlignedRam([u8; 2 * UAT_PGSZ]); + + struct VmInner { + va_range: Range, + page_table: PageTable, + backing: Box, + } + + struct Vm; + impl Vm { + MMU_SINGLE_PRODUCTION_FN + MMU_BATCH_PRODUCTION_FN + } + + unsafe fn asahi_copy_gpu_read_once(dst: *mut u8, src: *const u8, len: usize) { + extern "C" { + fn asahi_copy_gpu_read_once(dst: *mut u8, src: *const u8, len: usize); + } + assert_eq!(OUTSTANDING.with(Cell::get), 0); + COPIES.with(|c| c.set(c.get() + 1)); + unsafe { asahi_copy_gpu_read_once(dst, src, len) }; + } + + fn reset_counters() { + CLEAN_CALLS.with(|c| c.set(0)); + CLEAN_LINES.with(|c| c.set(0)); + BARRIERS.with(|c| c.set(0)); + COPIES.with(|c| c.set(0)); + assert_eq!(OUTSTANDING.with(Cell::get), 0); + WALK_CALLS.with(|c| c.set(0)); + RAM_CHECKS.with(|c| c.set(0)); + } + + #[test] + fn production_mmu_batch_coalesces_barrier_dedups_lines_and_handles_boundaries() { + let mut backing = Box::new(AlignedRam([0u8; 2 * UAT_PGSZ])); + // Page 0: aligned words across >256 B gaps, shared-line words, unaligned cache-line + // crossing word at 0x3e..0x42, and end-of-page word at 0x3ffc..0x4000. + backing.0[0x00..0x04].copy_from_slice(&0x21000960u32.to_le_bytes()); + backing.0[0x20..0x24].copy_from_slice(&0x21000968u32.to_le_bytes()); + backing.0[0x300..0x304].copy_from_slice(&0x11223344u32.to_le_bytes()); + backing.0[0x700..0x704].copy_from_slice(&0x55667788u32.to_le_bytes()); + backing.0[0x3e..0x42].copy_from_slice(&0x99aabbccu32.to_le_bytes()); + backing.0[0x3ffc..0x4000].copy_from_slice(&0x21000960u32.to_le_bytes()); + // Page 1: cross-page word. + backing.0[UAT_PGSZ + 0x100..UAT_PGSZ + 0x104].copy_from_slice(&0x21000968u32.to_le_bytes()); + + MEM_PTR.with(|p| p.set(backing.0.as_ptr() as usize)); + MEM_PAGES.with(|n| n.set(2)); + let base = 0x200000000u64; + let mut inner = VmInner { + va_range: base..(base + 2 * UAT_PGSZ as u64), + page_table: PageTable { oas_mask: (1 << 42) - 1, + pages: vec![ + (base, Some(PHYS_BASE), 1), + (base + UAT_PGSZ as u64, Some(PHYS_BASE + UAT_PGSZ as u64), 1), + ], + }, + backing, + }; + + // 11-pass style multi-page batch: 1 single poc_barrier(), same-line dedup (0x00 and 0x20), + // minimal 64B line per distinct 4B root, and 1 page-table walk per distinct page. + reset_counters(); + let vas = [ + base, + base + 0x20, + base + 0x300, + base + 0x700, + base + 0x3ffc, + base + UAT_PGSZ as u64 + 0x100, + ]; + let mut out = [0u32; 6]; + assert_eq!(Vm::read_user_u32_batch_locked(&mut inner, &vas, &mut out), Ok(())); + assert_eq!(out, [0x21000960, 0x21000968, 0x11223344, 0x55667788, 0x21000960, 0x21000968]); + assert_eq!(BARRIERS.with(Cell::get), 1); + assert_eq!(CLEAN_CALLS.with(Cell::get), 5); // 0x20 deduped with 0x00 + assert_eq!(CLEAN_LINES.with(Cell::get), 5); // 1 cache line (64B) each, not 256B + assert_eq!(WALK_CALLS.with(Cell::get), 2); // 1 walk for page 0 + 1 walk for page 1 + assert_eq!(RAM_CHECKS.with(Cell::get), 2); + assert_eq!(COPIES.with(Cell::get), vas.len()); + + // A second VA for the same physical page shares maintenance, never the VA permission. + let alias = base + UAT_PGSZ as u64; + inner.page_table.pages[1].1 = Some(PHYS_BASE); + reset_counters(); + let mut aliases = [0; 2]; + Vm::read_user_u32_batch_locked(&mut inner, &[base, alias + 0x20], &mut aliases).unwrap(); + assert_eq!(aliases, [0x21000960, 0x21000968]); + assert_eq!(CLEAN_CALLS.with(Cell::get), 1); + assert_eq!(WALK_CALLS.with(Cell::get), 2); + inner.page_table.pages[1].2 = 0; + assert_eq!(Vm::read_user_u32_batch_locked(&mut inner, &[base, alias], &mut aliases), + Err(EFAULT)); + inner.page_table.pages[1] = (alias, Some(PHYS_BASE + UAT_PGSZ as u64), 1); + + // Unaligned intra-page word straddling a 64-byte cache-line boundary (0x3e..0x42): + // cleans both lines with 1 barrier and returns the exact word. + reset_counters(); + let mut out1 = [0u32; 1]; + assert_eq!(Vm::read_user_u32_batch_locked(&mut inner, &[base + 0x3e], &mut out1), Ok(())); + assert_eq!(out1, [0x99aabbcc]); + assert_eq!(BARRIERS.with(Cell::get), 1); + assert_eq!(CLEAN_CALLS.with(Cell::get), 1); + assert_eq!(CLEAN_LINES.with(Cell::get), 2); + assert_eq!(COPIES.with(Cell::get), 1); + + // Unaligned cross-page word at 0x3ffe..0x4002 falls back cleanly without failing. + inner.backing.0[0x3ffe..0x4002].copy_from_slice(&0xdeadcafeu32.to_le_bytes()); + reset_counters(); + let mut out_cross = [0u32; 1]; + assert_eq!( + Vm::read_user_u32_batch_locked(&mut inner, &[base + 0x3ffe], &mut out_cross), + Ok(()) + ); + assert_eq!(out_cross, [0xdeadcafe]); + assert_eq!(COPIES.with(Cell::get), 2); + assert_eq!(BARRIERS.with(Cell::get), 2); + + // Length mismatch returns EINVAL; unmapped/non-readable returns EFAULT. + assert_eq!(Vm::read_user_u32_batch_locked(&mut inner, &[base], &mut []), Err(EINVAL)); + assert_eq!( + Vm::read_user_u32_batch_locked(&mut inner, &[base + 2 * UAT_PGSZ as u64], &mut out1), + Err(EFAULT) + ); + inner.page_table.pages[0].2 = 0; + assert_eq!(Vm::read_user_u32_batch_locked(&mut inner, &[base], &mut out1), Err(EFAULT)); + } + + #[test] + fn production_mmu_completes_maintenance_when_a_later_root_fails() { + let backing = Box::new(AlignedRam([0u8; 2 * UAT_PGSZ])); + MEM_PTR.with(|p| p.set(backing.0.as_ptr() as usize)); + MEM_PAGES.with(|n| n.set(1)); + let base = 0x200000000u64; + let bad = base + UAT_PGSZ as u64; + let mut inner = VmInner { + va_range: base..(bad + UAT_PGSZ as u64), + page_table: PageTable { oas_mask: (1 << 42) - 1, pages: vec![(base, Some(PHYS_BASE), 1)] }, + backing, + }; + + // Fail the leaf lookup, GPU permission, translation and RAM-page checks in turn. + for entry in [None, Some((bad, None, 0)), Some((bad, None, 1)), + Some((bad, Some(PHYS_BASE + UAT_PGSZ as u64), 1))] { + inner.page_table.pages.truncate(1); + inner.page_table.pages.extend(entry); + reset_counters(); + let mut out = [u32::MAX; 2]; + assert_eq!(Vm::read_user_u32_batch_locked(&mut inner, &[base, bad], &mut out), Err(EFAULT)); + assert_eq!(CLEAN_CALLS.with(Cell::get), 1); + assert_eq!(BARRIERS.with(Cell::get), 1); + assert_eq!(OUTSTANDING.with(Cell::get), 0); + assert_eq!(COPIES.with(Cell::get), 0); + } + } + + #[test] + fn production_mmu_reads_aligned_words_and_unaligned_edges_once() { + extern "C" { + fn test_read_counts() -> u32; + } + let mut backing = Box::new(AlignedRam([0u8; 2 * UAT_PGSZ])); + backing.0[..8].copy_from_slice(&[0x10, 0x21, 0x32, 0x43, 0x54, 0x65, 0x76, 0x87]); + MEM_PTR.with(|p| p.set(backing.0.as_ptr() as usize)); + MEM_PAGES.with(|n| n.set(1)); + let base = 0x200000000u64; + let mut inner = VmInner { + va_range: base..(base + UAT_PGSZ as u64), + page_table: PageTable { oas_mask: (1 << 42) - 1, pages: vec![(base, Some(PHYS_BASE), 1)] }, + backing, + }; + + let mut bytes = [0u8; 8]; + reset_counters(); + assert_eq!(Vm::read_user_locked(&mut inner, base + 1, &mut bytes[..7]), Ok(())); + assert_eq!(WALK_CALLS.with(Cell::get), 1); + assert_eq!(bytes, [0x21, 0x32, 0x43, 0x54, 0x65, 0x76, 0x87, 0]); + assert_eq!(unsafe { test_read_counts() }, (1 << 16) | 3); + + let mut out = [0u32; 2]; + assert_eq!(Vm::read_user_u32_batch_locked(&mut inner, &[base, base + 1], &mut out), Ok(())); + assert_eq!(out, [0x43322110, 0x54433221]); + assert_eq!(unsafe { test_read_counts() }, (1 << 16) | 4); + } +} #[test] fn cdm_locked_shares_held_guard_and_hits_span_proof() { let mut words = launch(1, USC + 0x80, 0x400000000); @@ -503,15 +906,53 @@ with tempfile.TemporaryDirectory(prefix='m4-rust-gate-') as directory: directory = pathlib.Path(directory) test = directory / 'test.rs' - test.write_text(harness.replace('PRODUCTION_SOURCE', str(SOURCE))) + test.write_text( + harness.replace('PRODUCTION_SOURCE', str(SOURCE)) + .replace('LEAF_PHYS_PRODUCTION', extract_fn(pgtable, 'fn leaf_phys(')) + .replace('TRANSLATE_IOVA_PRODUCTION', extract_fn(pgtable, 'fn translate_iova(')) + .replace('MMU_BATCH_PRODUCTION_FN', MMU_BATCH_FN) + .replace('MMU_SINGLE_PRODUCTION_FN', MMU_SINGLE_FN) + .replace('SCOPE_GUARD_PRODUCTION', SCOPE_GUARD) + ) + c_test = directory / 'read-once.c' + c_test.write_text(r''' +#include +#include +#include + +typedef uint8_t u8; +typedef uint32_t u32; +static _Thread_local u32 reads; + +u32 test_read_counts(void) +{ + u32 result = reads; + reads = 0; + return result; +} + +#define IS_ALIGNED(value, size) (!((value) & ((size) - 1))) +#define READ_ONCE(value) ({ \ + reads += sizeof(value) == sizeof(u32) ? (1U << 16) : 1; \ + *(const volatile typeof(value) *)&(value); \ +}) +#define put_unaligned(value, dst) do { \ + u32 copy = (value); \ + memcpy(dst, ©, sizeof(copy)); \ +} while (0) +''' + READ_ONCE_FN) + obj = directory / 'read-once.o' + subprocess.run(shlex.split(os.environ.get('CC', 'cc')) + + ['-std=gnu11', '-Wall', '-Werror', '-c', str(c_test), '-o', str(obj)], check=True) binary = directory / 'test' - subprocess.run(rustc() + [ '--edition=2021', '--test', str(test), '-o', str(binary)], check=True) + subprocess.run(rustc() + ['--edition=2021', '--test', str(test), + '-C', f'link-arg={obj}', '-o', str(binary)], check=True) result = subprocess.run([str(binary), '--nocapture'], check=True, text=True, capture_output=True, timeout=60) print(result.stdout, end='') (OUT / 'stream-gate-host.log').write_text(result.stdout + result.stderr) (OUT / 'stream-gate-host.json').write_text(json.dumps({ 'source': str(SOURCE), 'sha256': hashlib.sha256(SOURCE.read_bytes()).hexdigest(), - 'result': 'pass', 'test_groups': 12, + 'result': 'pass', 'test_groups': 18, 'mesa_sources': ['src/asahi/genxml/agx3_cmdstream.h', 'src/asahi/lib/agx3_cdm_decode_core.c', 'src/asahi/lib/agx_vdm_barrier_core.c'], 'limitations': 'Host VM model validates parser, addresses, cycles and interruption; hardware and kernel cache behavior require target tests.'