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
89 changes: 88 additions & 1 deletion crates/xcl/src/hle/d3d12x/bind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,8 @@ fn signature_dispatches(sig: usize) -> bool {
pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: usize, max: u32, args: usize, args_off: u64, count_buf: usize, count_off: u64) {
type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64);
let pc: F = std::mem::transmute(super::real::orig_fn(this, 59));
super::real::use_buffer(args);
super::real::use_buffer(count_buf);
let raw_pso = with(this, |s| s.pso);
let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso);
if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) {
Expand Down Expand Up @@ -1011,6 +1013,57 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis
super::real::dispatch_chain::dispatch(list, pso, with(this, |s| s.allocator), [x, y, z])
}

/// The bound tables' addresses: a table argument is its 32-bit console address in window 0.
fn table_addresses(layout: &Layout, args: &[u8], base: usize) -> Vec<usize> {
let word = |at: usize| args.get(at..at + 4).map_or(0, |b| u32::from_le_bytes(b.try_into().unwrap()));
layout
.params
.iter()
.filter_map(|p| match *p {
Param::Table { at } => Some(word(at as usize)),
_ => None,
})
.filter(|&t| t != 0)
.map(|t| base + t as usize)
.collect()
}

/// A root address in a buffer the title placed outside the memory windows names where that
/// buffer lives (`real::place_outside_buffer`), and the buffers waiting for their video memory
/// that a root address or a buffer V# of the bound tables' first 64 slots names get it now
/// (`sparse::use_range`).
unsafe fn outside_buffers_in_use(layout: &Layout, args: &mut [u8], base: usize, in_windows: impl Fn(usize) -> bool) {
for p in layout.params.iter() {
let Param::Descriptor { at } = *p else { continue };
let at = at as usize;
let Some(b) = args.get_mut(at..at + 8) else { continue };
let va = u64::from_le_bytes((&*b).try_into().unwrap()) as usize;
if va == 0 || in_windows(va) {
continue;
}
if let Some(q) = super::real::outside_buffer_address(va) {
b.copy_from_slice(&(q as u64).to_le_bytes());
super::sparse::use_range(q, 1);
}
}
if !super::sparse::lazy_pending() {
return;
}
for table in table_addresses(layout, args, base) {
let slot = super::console_heap::SLOT as usize;
if !crate::gpu::shader::readable(table, slot * 64) {
continue;
}
for k in 0..64 {
let d = ((table + slot * k) as *const [u32; 4]).read_unaligned();
// a V# (an image's T# has its type in the top bits of word 3)
if d[3] >> 30 == 0 && (d[0] | d[1]) != 0 {
super::sparse::use_range(((d[1] as usize & 0xFFFF) << 32) | d[0] as usize, 1);
}
}
}
}

/// XCL's ABI for a translated pipeline: its root signature, the user SGPRs (`io`, the kept
/// arguments the console's way – compute or graphics) and the argument table in unified
/// memory, u1 res, u2… the memory windows; then the pipeline.
Expand All @@ -1019,7 +1072,10 @@ 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")?;
let (layout, args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) });
let (layout, mut args) = with(this, |s| if gfx { (s.layout_gfx.clone(), s.args_gfx.clone()) } else { (s.layout.clone(), s.args.clone()) });
if let Some(l) = layout.as_deref() {
outside_buffers_in_use(l, &mut args, u.base(), |va| u.contains(va));
}
// 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> {
let p = with(this, |s| s.arena.take(u, bytes.len().max(16), 256, &mut s.uma)).ok_or("unified memory is full")?;
Expand Down Expand Up @@ -1089,6 +1145,37 @@ mod tests {
use super::*;
use std::sync::atomic::AtomicUsize;

#[test]
fn table_addresses_follow_the_table_arguments() {
let layout = Layout { params: vec![Param::Table { at: 0 }, Param::Constants { at: 4, count: 2 }, Param::Descriptor { at: 12 }, Param::Table { at: 20 }, Param::Table { at: 24 }], size: 28, inline: 0, inline_gfx: 0 };
let mut args = vec![0u8; 28];
args[0..4].copy_from_slice(&0x4dbc_9a80u32.to_le_bytes());
args[4..12].copy_from_slice(&[7; 8]);
args[12..20].copy_from_slice(&0x1234_5678_9abcu64.to_le_bytes());
args[24..28].copy_from_slice(&0x0004_0000u32.to_le_bytes());
let base = 0x7_0000_0000usize;
assert_eq!(table_addresses(&layout, &args, base), vec![base + 0x4dbc_9a80, base + 0x4_0000], "a table not set yet is skipped");
assert!(table_addresses(&layout, &args[..2], base).is_empty(), "arguments not set yet");
}

/// A root address in a buffer the title placed outside the memory windows names where the
/// buffer lives; an address in the windows, in no such buffer, or 0 stays as it is.
#[test]
fn root_addresses_in_outside_buffers_name_their_address_in_the_windows() {
let (title, lives) = (0x15_7e57_0000usize, 0x4_7e57_0000usize);
real::note_outside_buffer(title, 0x2_0000, lives);
let layout = Layout { params: vec![Param::Descriptor { at: 0 }, Param::Constants { at: 8, count: 1 }, Param::Descriptor { at: 12 }, Param::Descriptor { at: 20 }, Param::Descriptor { at: 28 }], size: 36, inline: 0, inline_gfx: 0 };
let mut args = vec![0u8; 36];
args[0..8].copy_from_slice(&(title as u64 + 0x1240).to_le_bytes());
args[8..12].copy_from_slice(&0x15_u32.to_le_bytes());
args[12..20].copy_from_slice(&(title as u64 + 0x2_0000).to_le_bytes());
args[20..28].copy_from_slice(&0x4_0000_1000u64.to_le_bytes());
let before = args.clone();
unsafe { outside_buffers_in_use(&layout, &mut args, 0, |va| va < 0x10_0000_0000) };
assert_eq!(u64::from_le_bytes(args[0..8].try_into().unwrap()), lives as u64 + 0x1240);
assert_eq!(args[8..], before[8..], "constants, an address past the buffer, one in the windows and 0 are kept");
}

/// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone.
#[test]
fn rect_lists_with_the_rect_list_gs_are_not_expanded_on_the_cpu() {
Expand Down
3 changes: 3 additions & 0 deletions crates/xcl/src/hle/d3d12x/device_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1107,6 +1107,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
if let Some(hr) = real::place_at_title_address(this, va as usize, &d, state, clear, riid, ppv) {
return hr;
}
if let Some(hr) = real::place_outside_buffer(this, va as usize, &d, state, riid, ppv) {
return hr;
}
}
let state = if !buffer {
pc_initial_state_for_desc(
Expand Down
2 changes: 2 additions & 0 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4250,6 +4250,8 @@ fn note_gpu_write(what: &str, va: usize, n: u64) {
}

pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) {
real::use_buffer(dst);
real::use_buffer(src);
if super::present::trace_frame() {
if let Some(a) = real::title_address(dst) {
note_gpu_write("CopyBufferRegion", a + dst_off as usize, n);
Expand Down
113 changes: 113 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1505,6 +1505,79 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc:
Some(hr)
}

/// Buffers the title placed outside the memory windows that live in the sparse windows
/// (`place_outside_buffer`): (title address, bytes, address in the windows)
static OUTSIDE_BUFFERS: Mutex<Vec<(usize, usize, usize)>> = Mutex::new(Vec::new());

/// A buffer the title places outside every memory window, at an address with no CPU pages (a
/// retail title puts its compute buffers – light, ray and tile lists, BVH data – in plain
/// reservations above its GPU views): only the GPU uses it. As a committed resource of its own
/// its views had an empty V#, so shaders read zeros and their writes were dropped. It gets an
/// address in the sparse windows instead, with video memory from its first use
/// (`sparse::use_range`); its views and root addresses name that address.
pub(super) unsafe fn place_outside_buffer(this: *mut c_void, va: usize, desc: &[u8; 0x38], state: u32, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> {
let u = crate::gpu::uma::get()?;
let d: D3D12_RESOURCE_DESC = std::ptr::read_unaligned(desc.as_ptr() as *const D3D12_RESOURCE_DESC);
let bytes = d.Width as usize;
if !u.has_sparse() || bytes == 0 || u.contains(va) || has_cpu_pages(va, bytes) {
return None;
}
let (p, _) = u.sparse_alloc(bytes, 0x1_0000)?;
let Some((hr, _)) = super::sparse::place_buffer_when(this, p, &d, state, riid, ppv, true) else {
u.sparse_release(p);
return None;
};
UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (p, bytes, true));
note_outside_buffer(va, bytes, p);
Some(hr)
}

/// Whether any page of `[va, va + bytes)` is committed (the title may write the buffer there
/// with the CPU, which nothing would carry to an address in the sparse windows).
fn has_cpu_pages(va: usize, bytes: usize) -> bool {
use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT};
let end = va.saturating_add(bytes);
let mut at = va;
while at < end {
// SAFETY: VirtualQuery only reads the description of the process's address space
let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 {
return false;
}
if m.State == MEM_COMMIT {
return true;
}
let next = (m.BaseAddress as usize).saturating_add(m.RegionSize);
if next <= at {
return false;
}
at = next;
}
false
}

pub(super) fn note_outside_buffer(va: usize, bytes: usize, p: usize) {
let mut g = OUTSIDE_BUFFERS.lock().unwrap();
g.retain(|&(a, n, _)| a + n <= va || va + bytes <= a);
g.push((va, bytes, p));
}

/// Where title address `va` lives when it is in a buffer of `place_outside_buffer`.
pub fn outside_buffer_address(va: usize) -> Option<usize> {
OUTSIDE_BUFFERS.lock().unwrap().iter().find(|&&(a, n, _)| va >= a && va < a + n).map(|&(a, _, p)| p + (va - a))
}

/// Resource `res` is used by a call of the title (a copy, indirect arguments): a buffer still
/// waiting for its video memory gets it (`sparse::use_range`).
pub unsafe fn use_buffer(res: usize) {
if !super::sparse::lazy_pending() {
return;
}
if let Some((p, n)) = console_buffer(res) {
super::sparse::use_range(p, n);
}
}

/// buffers placed below their console address: resource → bytes before it
static BUFFER_DELTA: Mutex<Option<HashMap<usize, u64>>> = Mutex::new(None);

Expand Down Expand Up @@ -1694,6 +1767,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 {
super::title_textures::forget(this as usize);
let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize)));
if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) {
OUTSIDE_BUFFERS.lock().unwrap().retain(|b| b.2 != p);
if u.is_sparse(p) {
super::sparse::free(p);
} else {
Expand Down Expand Up @@ -6458,6 +6532,45 @@ fn pc_topology_type(g: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC) {
}
}

#[cfg(test)]
mod outside_buffer_tests {
use super::*;
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE};

/// Only an address range with no committed page is taken for a GPU-only buffer.
#[test]
fn cpu_pages_are_found_anywhere_in_the_range() {
const PAGE: usize = 0x1000;
unsafe {
let base = VirtualAlloc(std::ptr::null(), 8 * PAGE, MEM_RESERVE, PAGE_NOACCESS) as usize;
assert_ne!(base, 0);
assert!(!has_cpu_pages(base, 8 * PAGE), "reserved only");
assert!(!VirtualAlloc((base + 5 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null());
assert!(has_cpu_pages(base, 8 * PAGE), "one committed page in the middle");
assert!(has_cpu_pages(base + 5 * PAGE + 16, 4), "inside the committed page");
assert!(!has_cpu_pages(base, 5 * PAGE), "the range before it");
assert!(!has_cpu_pages(base + 6 * PAGE, 2 * PAGE), "the range after it");
assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
}
}

/// Addresses in an outside buffer map to the same offset in its copy; a buffer placed again
/// over part of an older one replaces it.
#[test]
fn outside_buffer_addresses_keep_their_offset() {
let (title, lives) = (0x16_0000_0000usize, 0x4_8000_0000usize);
note_outside_buffer(title, 0x1_0000, lives);
assert_eq!(outside_buffer_address(title), Some(lives));
assert_eq!(outside_buffer_address(title + 0xfff8), Some(lives + 0xfff8));
assert_eq!(outside_buffer_address(title + 0x1_0000), None);
assert_eq!(outside_buffer_address(title - 1), None);
note_outside_buffer(title + 0x8000, 0x1_0000, lives + 0x10_0000);
assert_eq!(outside_buffer_address(title), None, "the older buffer overlapped by the new one is gone");
assert_eq!(outside_buffer_address(title + 0x8000), Some(lives + 0x10_0000));
OUTSIDE_BUFFERS.lock().unwrap().retain(|b| b.0 < title || b.0 >= title + 0x2_0000);
}
}

#[cfg(test)]
mod pso_blend_and_tsharp_tests {
use super::*;
Expand Down
Loading
Loading