Skip to content
Open
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
111 changes: 109 additions & 2 deletions d3d12/crates/leonida-hle/src/modules/xmem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,28 @@ fn address_range(flags: u64) -> (usize, usize) {
(1 << 32, (1 << bits) - 1)
}

/// Exclusive end of the GPU's mappable 64 KiB-page directory (`MEMORY_PAGES - 1`
/// pages = 128 GiB - 64 KiB = `0x1F_FFFF_0000`). Page `MEMORY_PAGES - 1`
/// (`[0x1F_FFFF_0000, 0x20_0000_0000)`) is permanently reserved as the empty
/// out-of-range sentinel (`leonida-gpu/src/memory.rs` and `leonida-shader`).
const GPU_DIRECTORY_END: usize = (1usize << 37) - (64 * 1024);

/// Prefer the GPU's mappable 64 KiB-page directory (`[4 GiB, GPU_DIRECTORY_END)`).
/// Expanding it would change every shader's bounds and invalidate translations.
/// Keep the console range for CPU-only memory and as an allocation fallback.
fn graphics_address_range(flags: u64) -> (usize, usize) {
let (lowest, highest) = address_range(flags);
(lowest, if flags & 2 != 0 { highest.min(GPU_DIRECTORY_END - 1) } else { highest })
}

pub extern "system" fn XMemVirtualAlloc(
base: *mut c_void,
size: usize,
kind: u32,
flags: u64,
protect: u32,
) -> *mut c_void {
let (lowest, highest) = address_range(flags);
let (lowest, highest) = graphics_address_range(flags);
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
LowestStartingAddress: lowest as *mut c_void,
HighestEndingAddress: highest as *mut c_void,
Expand Down Expand Up @@ -158,7 +172,7 @@ pub extern "system" fn XMemVirtualAlloc(
}
// SAFETY: the title's own arguments, cleaned of console bits; the
// parameter points at `requirements`, which outlives the call.
let at = unsafe {
let mut at = unsafe {
VirtualAlloc2(
GetCurrentProcess(),
base,
Expand All @@ -173,6 +187,33 @@ pub extern "system" fn XMemVirtualAlloc(
constrained.into(),
)
};
let (_, fallback_highest) = address_range(flags);
if at.is_null() && constrained && highest < fallback_highest {
// A crowded low VA range must not turn a legal console allocation into
// an OOM. Preserve the original limit (normally 40 bits), and make the
// loss of raw-address GPU coverage visible instead of hiding it.
let error = std::io::Error::last_os_error();
tracing::warn!(
size,
%error,
"XMemVirtualAlloc: 37-bit reservation refused; retrying console range (outside GPU directory)"
);
requirements.HighestEndingAddress = fallback_highest as *mut c_void;
parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
// SAFETY: identical reservation and live address-requirements parameter,
// with only its upper bound restored to the console's allowed range.
at = unsafe {
VirtualAlloc2(GetCurrentProcess(), base, size, kind, protect, &mut parameter, 1)
};
}
if !at.is_null() && constrained && flags & 2 != 0 {
tracing::debug!(
at = format_args!("{at:p}"),
size,
directory_covered = (at as usize).checked_add(size).is_some_and(|end| end <= GPU_DIRECTORY_END),
"XMem graphics reservation"
);
}
if at.is_null() {
let error = std::io::Error::last_os_error();
if kind & MEM_COMMIT != 0 {
Expand Down Expand Up @@ -2398,6 +2439,72 @@ pub(crate) fn module() -> HleModule {
mod tests {
use super::*;

/// Graphics reservations prefer the mappable GPU page directory (`[4 GiB, 128 GiB - 64 KiB)`,
/// leaving page `MEMORY_PAGES - 1` at `0x1F_FFFF_0000` free as the empty sentinel),
/// while 32-bit and CPU-only reservations keep their full console address ranges.
#[test]
fn graphics_reservations_prefer_the_gpu_directory() {
const MEM_TOP_DOWN: u32 = 0x0010_0000;
const SENTINEL_PAGE: usize = (1usize << 37) - (64 * 1024);
let size = 64 * 1024;
for field in 0..=7 {
let flags = GRAPHICS | (field << 12);
let p = XMemVirtualAlloc(std::ptr::null_mut(), size, MEM_RESERVE | MEM_TOP_DOWN, flags, PAGE_NOACCESS);
assert!(!p.is_null(), "field {field}: graphics reservation failed");
let addr = p as usize;
leonida_gpu::title_memory_freed(addr, 0);
// SAFETY: the uncommitted reservation returned above belongs to us.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
assert!(addr >= 1usize << 32, "field {field}: addr {addr:#x} below 4 GiB");
assert!(
addr.checked_add(size).is_some_and(|end| end <= SENTINEL_PAGE),
"field {field}: graphics reservation {addr:#x} reached or exceeded GPU directory sentinel page {SENTINEL_PAGE:#x}"
);

let p32 = XMemVirtualAlloc(
std::ptr::null_mut(),
size,
MEM_RESERVE | MEM_TOP_DOWN,
flags | ADDRESS_32BIT,
PAGE_NOACCESS,
);
assert!(!p32.is_null(), "field {field}: 32-bit graphics reservation failed");
let addr32 = p32 as usize;
leonida_gpu::title_memory_freed(addr32, 0);
// SAFETY: as above.
assert_ne!(unsafe { VirtualFree(p32, 0, MEM_RELEASE) }, 0);
assert!(addr32.checked_add(size).is_some_and(|end| end <= 1usize << 32));
}
// CPU-only reservations retain the full 40-bit console range above 128 GiB.
let cpu = XMemVirtualAlloc(std::ptr::null_mut(), size, MEM_RESERVE | MEM_TOP_DOWN, 1, PAGE_NOACCESS);
assert!(!cpu.is_null(), "CPU-only reservation failed");
let cpu_addr = cpu as usize;
leonida_gpu::title_memory_freed(cpu_addr, 0);
// SAFETY: as above.
assert_ne!(unsafe { VirtualFree(cpu, 0, MEM_RELEASE) }, 0);
assert!(
cpu_addr >= 1usize << 37 && cpu_addr.checked_add(size).is_some_and(|end| end <= 1usize << 40),
"CPU-only top-down reservation {cpu_addr:#x} did not retain the 40-bit console range"
);
}

/// A graphics reservation that cannot fit in `[4 GiB, 128 GiB - 64 KiB)` transparently
/// falls back to the console's wider address range instead of failing.
#[test]
fn graphics_reservation_falls_back_when_the_directory_range_is_too_small() {
// [4 GiB, 128 GiB - 64 KiB) cannot fit 128 GiB, so the first reservation must
// fail. Reserve VA only: this test commits no physical memory.
let size = 1usize << 37;
let p = XMemVirtualAlloc(std::ptr::null_mut(), size, MEM_RESERVE, GRAPHICS, PAGE_NOACCESS);
assert!(!p.is_null(), "console-range fallback failed");
let addr = p as usize;
leonida_gpu::title_memory_freed(addr, 0);
// SAFETY: the uncommitted reservation returned above belongs to us.
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
assert!(addr >= 1usize << 32);
assert!(addr.checked_add(size).is_some_and(|end| end <= 1usize << 40));
}

/// The console protections the title asks for, by whether the GPU only reads them.
#[test]
fn gpu_read_only_protections() {
Expand Down