Skip to content
Open
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
70 changes: 51 additions & 19 deletions crates/xcl/src/gpu/recomp/runner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1315,22 +1315,39 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
let dev = &gpu.dev;
let dev3: ID3D12Device3 = dev.cast().map_err(e)?;
let mut bufs: Vec<ID3D12Resource> = Vec::new();
// a D3D12 without heaps over process memory (D3DMetal: E_NOTIMPL): each window is a
// buffer in video memory, filled from the window before the dispatch and copied back
// after it -- (upload, readback) per window
let mut copies: Vec<(ID3D12Resource, ID3D12Resource)> = Vec::new();
for &(base, size) in &arena.windows {
let heap: ID3D12Heap = dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void).map_err(|x| format!("OpenExistingHeapFromAddress: {x}"))?;
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size as u64,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER,
..Default::default()
};
let mut mem_buf: Option<ID3D12Resource> = None;
dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?;
bufs.push(mem_buf.ok_or("arena")?);
let heap: ID3D12Heap = match dev3.OpenExistingHeapFromAddress(base as *const std::ffi::c_void) {
Ok(h) => h,
Err(x) if x.code() == windows::Win32::Foundation::E_NOTIMPL => {
let up = buffer(dev, size as u64, D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ, false)?;
let mut p = std::ptr::null_mut();
up.Map(0, None, Some(&mut p)).map_err(e)?;
std::ptr::copy_nonoverlapping(base, p as *mut u8, size);
up.Unmap(0, None);
bufs.push(buffer(dev, size as u64, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COMMON, true)?);
copies.push((up, buffer(dev, size as u64, D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST, false)?));
continue;
}
Err(x) => return Err(format!("OpenExistingHeapFromAddress: {x}")),
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size as u64,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER,
..Default::default()
};
let mut mem_buf: Option<ID3D12Resource> = None;
dev.CreatePlacedResource(&heap, 0, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut mem_buf).map_err(|x| format!("CreatePlacedResource: {x}"))?;
bufs.push(mem_buf.ok_or("arena")?);
}
let mem_buf = bufs[0].clone();
let pso: ID3D12PipelineState = dev
Expand All @@ -1353,13 +1370,18 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(e)?;
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, &pso).map_err(e)?;
list.CopyBufferRegion(&io_buf, 0, &upload, 0, io_bytes);
// (a buffer in COMMON takes the copy as it is)
for (b, (up, _)) in bufs.iter().zip(&copies) {
list.CopyBufferRegion(b, 0, up, 0, b.GetDesc().Width);
}
let filled = if copies.is_empty() { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_COPY_DEST };
list.ResourceBarrier(&[
transition(&io_buf, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
transition(&res_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
transition(&mem_buf, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
transition(&mem_buf, filled, D3D12_RESOURCE_STATE_UNORDERED_ACCESS),
]);
for b in &bufs[1..] {
list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]);
list.ResourceBarrier(&[transition(b, filled, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]);
}
// the windows as raw UAVs at MEM_HEAP_BASE.. of a shader-visible heap
// (`Options::heap_windows`; programs with the root-UAV switch ignore it)
Expand All @@ -1386,18 +1408,28 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result<Kern
list.SetComputeRootUnorderedAccessView(2 + k as u32, bufs.get(k).unwrap_or(&mem_buf).GetGPUVirtualAddress());
}
list.Dispatch(1, 1, 1);
let after = if copies.is_empty() { D3D12_RESOURCE_STATE_COMMON } else { D3D12_RESOURCE_STATE_COPY_SOURCE };
list.ResourceBarrier(&[
transition(&res_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE),
transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON),
transition(&mem_buf, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, after),
]);
for b in &bufs[1..] {
list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON)]);
list.ResourceBarrier(&[transition(b, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, after)]);
}
list.CopyBufferRegion(&readback, 0, &res_buf, 0, res_bytes);
for (b, (_, back)) in bufs.iter().zip(&copies) {
list.CopyBufferRegion(back, 0, b, 0, b.GetDesc().Width);
}
list.Close().map_err(e)?;
gpu.queue.ExecuteCommandLists(&[Some(list.cast().map_err(e)?)]);
gpu.value += 1;
wait_for_submission(dev, &gpu.queue, &gpu.fence, gpu.value, "arena dispatch")?;
for (&(base, size), (_, back)) in arena.windows.iter().zip(&copies) {
let mut q = std::ptr::null_mut();
back.Map(0, None, Some(&mut q)).map_err(e)?;
std::ptr::copy_nonoverlapping(q as *const u8, base, size);
back.Unmap(0, None);
}
let mut q = std::ptr::null_mut();
readback.Map(0, None, Some(&mut q)).map_err(e)?;
let raw = std::slice::from_raw_parts(q as *const u32, KERNEL_RES_DWORDS).to_vec();
Expand Down
22 changes: 21 additions & 1 deletion crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3449,7 +3449,10 @@ fn gpu_uma_import_check_at_init() {
}
crate::hle::d3d12x::real::init().expect("real D3D12.X backend");
let s = crate::hle::d3d12x::real::stats().uma_import_check;
assert!(s.starts_with("ok") || s.starts_with("off"), "{s}");
// a committed window the GPU only has a copy of (no host-memory heaps): there is no import
// to check, and only that window may say so
let shadowed = crate::gpu::uma::get().is_some_and(|u| u.shadowed());
assert!(s.starts_with("ok") || s.starts_with("off") || (shadowed && s.starts_with("not run: the coherent window has a copy in video memory")), "{s}");
}

/// End-to-end GPU test of the sparse-window VRAM runtime layout:
Expand Down Expand Up @@ -3577,8 +3580,16 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() {
}
};

// a window the GPU has a copy of: what the shader stored comes back on request
let gpu_wrote = || {
if u.shadowed() {
crate::hle::d3d12x::sparse::readback_now(out_buf, 256);
}
};

// Submit 1: reads slot 0 -> in_a (sparse VRAM) + arg_table constant 77 (Window 3)
record_and_run(1, true);
gpu_wrote();
for l in 0..64usize {
let got = *((out_buf + 4 * l) as *const u32);
assert_eq!(got, 1000 + l as u32 + 77, "submit 1 lane {l} mismatch");
Expand All @@ -3589,12 +3600,21 @@ fn gpu_sparse_vram_descriptors_buffers_and_xmem() {
*((in_b + 4 * 3) as *mut u32) = 9999;
crate::hle::d3d12x::console_heap::write(&slot0, &vsharp(in_b));
record_and_run(2, false);
gpu_wrote();
for l in 0..64usize {
let expected = if l == 3 { 9999 + 13 } else { 5000 + 2 * l as u32 + 13 };
let got = *((out_buf + 4 * l) as *const u32);
assert_eq!(got, expected, "submit 2 (mutated sparse descriptor + XMem buffer) lane {l} mismatch");
}

// Submits 3..: a constant the CPU rewrites before every submit reaches the shader each time
for n in 0..40u32 {
*(arg_table as *mut u32) = 100 + n;
record_and_run(3 + n as u64, false);
gpu_wrote();
assert_eq!(*(out_buf as *const u32), 5000 + 100 + n, "submit {} (constant rewritten in window 3)", 3 + n);
}

// Clean up
crate::hle::d3d12x::console_heap::unregister(heap_obj);
crate::hle::kernelx::XMemFreeDefault(in_a as *mut _, gfx_attrs);
Expand Down
22 changes: 22 additions & 0 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
//! 4095 MiB works (exactly 4 GiB is rejected), opening 4 GiB takes ~0.5 s.

use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};

use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE};
Expand Down Expand Up @@ -48,6 +49,8 @@ pub struct Uma {
inner: Mutex<Inner>,
/// free ranges of the sparse windows (address → length) and the reservations in them
sparse_free: Mutex<(BTreeMap<usize, usize>, BTreeMap<usize, usize>)>,
/// the committed windows are not the GPU's memory: it has copies of them (`set_shadowed`)
shadowed: AtomicBool,
/// XCL's own pool in window 0 for `Arena` blocks: (start, end, free blocks). The title
/// cannot take it – a title that commits all of unified memory at start (Unicorn
/// Overlord: 2046 of 2048 MB) left no room for draw arguments, and draws were skipped.
Expand Down Expand Up @@ -197,6 +200,7 @@ impl Uma {
win_allocs: vec![base, c_base],
inner: Mutex::new(inner),
sparse_free: Mutex::new(sparse_free),
shadowed: AtomicBool::new(false),
pool: Mutex::new((0, 0, Vec::new())),
};
u.reserve_pool(POOL);
Expand Down Expand Up @@ -277,6 +281,23 @@ impl Uma {
len > 0 && self.is_committed(p) && p.checked_add(len - 1).is_some_and(|e| self.window_of(e) == self.window_of(p))
}

/// The GPU could not open the committed windows as heaps (`OpenExistingHeapFromAddress`
/// not implemented: D3DMetal): each has a buffer in video memory instead, a copy that
/// `d3d12x::sparse` keeps in step like a sparse window's tiles.
pub fn set_shadowed(&self) {
self.shadowed.store(true, Ordering::Release);
}

pub fn shadowed(&self) -> bool {
self.shadowed.load(Ordering::Acquire)
}

/// Whether the GPU works on a copy of the memory at `p` (a sparse window, or a committed
/// one that is shadowed): what the GPU writes there the CPU sees only after a readback.
pub fn is_gpu_copy(&self, p: usize) -> bool {
self.is_sparse(p) || (self.shadowed() && self.is_committed(p))
}

/// Address space for a title reservation of `size` bytes in the sparse windows (64 KiB
/// aligned, first fit; not committed). Prefers windows 1+ so window 0 stays uncluttered for
/// small allocations, falling back to all of the title's sparse space (never `desc_range`).
Expand Down Expand Up @@ -403,6 +424,7 @@ impl Uma {
win_allocs,
inner: Mutex::new(inner),
sparse_free: Mutex::new(Default::default()),
shadowed: AtomicBool::new(false),
pool: Mutex::new((0, 0, Vec::new())),
});
}
Expand Down
5 changes: 5 additions & 0 deletions crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,11 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi
let u = crate::gpu::uma::get().ok_or("no unified memory")?;
let windows = super::real::uma_window_vas();
let first = *windows.first().ok_or("unified memory is not open on the GPU")?;
// shadowed unified memory whose sparse windows could not be made (no reserved resources
// either): descriptor tables are read from window 0, and a null root descriptor is not bound
if first == 0 && u.shadowed() {
return Err("window 0 of unified memory has no buffer on the GPU".into());
}
let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) });
// 32-bit console addresses: window 0; pieces of the list's arena (not a 64 KiB grain each)
let copy = |bytes: &[u8]| -> Result<usize, String> {
Expand Down
23 changes: 22 additions & 1 deletion crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ impl ListState {
last.0 = last.0.min(va);
last.1 = last.1.max(end);
}
if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) {
if crate::gpu::uma::get().is_some_and(|u| u.is_gpu_copy(va as usize)) {
if self.sparse_writes.is_empty() {
SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel);
}
Expand Down Expand Up @@ -953,6 +953,17 @@ fn note_write(list: usize, va: u64, size: u64) {
LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size);
}

/// A PC copy into `[offset, offset + n)` of console buffer `dst` whose memory the GPU only has
/// a copy of in a committed window (`Uma::shadowed`: readback buffers live there, and titles
/// read them through a pointer they keep mapped, without another Map): the bytes come back to
/// the CPU's view after the submit, like the lists' own memory writes.
fn note_copy_into(list: usize, dst: usize, offset: u64, n: u64) {
let Some(u) = crate::gpu::uma::get().filter(|u| u.shadowed()) else { return };
let Some((p, bytes)) = real::console_buffer(dst).filter(|&(p, _)| u.is_committed(p)) else { return };
let offset = offset.min(bytes as u64);
note_write(list, p as u64 + offset, n.min(bytes as u64 - offset));
}

// ---------------------------------------------------------------------------------------
// per-address GPU fence bridge for monotonic 64-bit Write64BitValue* -> Wait64BitValueX
// ---------------------------------------------------------------------------------------
Expand Down Expand Up @@ -3796,6 +3807,7 @@ pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst
note_gpu_write("CopyBufferRegion", a + dst_off as usize, n);
}
}
note_copy_into(this as usize, dst, dst_off, n);
pc::<unsafe extern "system" fn(*mut c_void, usize, u64, usize, u64, u64)>(this, PC_COPY_BUFFER_REGION)(this, dst, dst_off + real::buffer_delta(dst), src, src_off + real::buffer_delta(src), n)
}

Expand Down Expand Up @@ -3895,6 +3907,12 @@ pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, ds
}
}
}
if let Some(l) = dst.as_ref().filter(|l| l.Type == D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT) {
// (the rows of the footprint: at most what the copy writes)
let f = &l.Anonymous.PlacedFootprint;
let n = f.Footprint.RowPitch as u64 * f.Footprint.Height.max(1) as u64 * f.Footprint.Depth.max(1) as u64;
note_copy_into(this as usize, transmute_copy::<_, usize>(&l.pResource), f.Offset, n);
}
let (Some(d), Some(s)) = (pc_location(dst), pc_location(src)) else { return };
pc::<unsafe extern "system" fn(*mut c_void, *const D3D12_TEXTURE_COPY_LOCATION, u32, u32, u32, *const D3D12_TEXTURE_COPY_LOCATION, *const D3D12_BOX)>(this, PC_COPY_TEXTURE_REGION)(this, &d, x, y, z, &s, bx);
std::mem::forget((d, s)); // borrowed resource pointers
Expand Down Expand Up @@ -3981,6 +3999,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi
}
let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src));
if dd == 0 && sd == 0 {
note_copy_into(this as usize, dst, 0, u64::MAX);
return pc::<unsafe extern "system" fn(*mut c_void, usize, usize)>(this, PC_COPY_RESOURCE)(this, dst, src);
}
let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64);
Expand Down Expand Up @@ -4037,6 +4056,8 @@ pub(super) unsafe extern "system" fn end_query_x(this: *mut c_void, heap: usize,
/// ResolveQueryData wants the destination). Buffers placed below their console address add
/// `buffer_delta(dest)` to the destination offset.
pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, heap: usize, ty: D3D12_QUERY_TYPE, first: u32, count: u32, dest: usize, offset: u64) {
// (8 bytes a query; pipeline statistics, the largest, are 11 values)
note_copy_into(this as usize, dest, offset, count as u64 * if ty == D3D12_QUERY_TYPE_PIPELINE_STATISTICS { 88 } else { 8 });
let pc_offset = offset.saturating_add(real::buffer_delta(dest));
type F = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64);
pc::<F>(this, PC_RESOLVE_QUERY_DATA)(this, heap, ty, first, count, dest, pc_offset);
Expand Down
Loading
Loading