Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 16 additions & 22 deletions drivers/gpu/drm/asahi/g16/gate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand Down
110 changes: 106 additions & 4 deletions drivers/gpu/drm/asahi/mmu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -2788,24 +2798,116 @@ 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)?;
let target = &mut buf[done..done + count];
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;
}
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.
Expand Down
9 changes: 7 additions & 2 deletions drivers/gpu/drm/asahi/pgtable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<u64> {
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
Expand Down
21 changes: 21 additions & 0 deletions drivers/gpu/drm/asahi/user_pages.c
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,30 @@
#include <linux/mm_subpage.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/unaligned.h>

#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 {
Expand Down
3 changes: 3 additions & 0 deletions drivers/gpu/drm/asahi/user_pages.h
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading