357 lines
13 KiB
Rust
357 lines
13 KiB
Rust
//! `xmem.dll`: console memory, served from host memory. The GPU side works
|
|||
|
|
//! from CPU addresses (unified memory), so memory types and bandwidth
|
||
|
|
//! classes change nothing here; what constrains addresses (alignment,
|
||
|
|
//! 2 MiB pages, address-bit limits) is honoured.
|
||
|
|
#![allow(non_snake_case)]
|
||
|
|
// Title code calls these through its import table, passing pointers the real
|
||
|
|
// API would trust.
|
||
|
|
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||
|
|
|
||
|
|
use std::alloc::{Layout, alloc, dealloc};
|
||
|
|
use std::ffi::c_void;
|
||
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||
|
|
|
||
|
|
use windows_sys::Win32::Foundation::HANDLE;
|
||
|
|
use windows_sys::Win32::System::Memory::{
|
||
|
|
MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RELEASE, MEM_RESERVE,
|
||
|
|
MEMORY_BASIC_INFORMATION, MemExtendedParameterAddressRequirements, PAGE_NOACCESS,
|
||
|
|
PAGE_READWRITE, VirtualAlloc2, VirtualFree, VirtualQueryEx,
|
||
|
|
};
|
||
|
|
use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
|
||
|
|
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||
|
|
use windows_sys::core::BOOL;
|
||
|
|
|
||
|
|
use crate::{HleModule, hle_export};
|
||
|
|
|
||
|
|
const MIB: usize = 1 << 20;
|
||
|
|
const GIB: usize = 1 << 30;
|
||
|
|
/// Title memory of an Xbox Series X in the advanced mode: 10 GiB of
|
||
|
|
/// GPU-optimal and 3.5 GiB of standard memory.
|
||
|
|
const GPU_OPTIMAL_LIMIT: usize = 10 * GIB;
|
||
|
|
const STANDARD_LIMIT: usize = 7 * GIB / 2;
|
||
|
|
|
||
|
|
/// Standard memory the title has handed to the system.
|
||
|
|
static TRANSFERRED: AtomicUsize = AtomicUsize::new(0);
|
||
|
|
|
||
|
|
// Console additions to the host's flags.
|
||
|
|
/// 2 MiB pages; the host reads this bit as large pages, which need a
|
||
|
|
/// privilege.
|
||
|
|
const PAGES_2M: u32 = 0x2000_0000;
|
||
|
|
/// With `PAGES_2M`: 64 KiB pages; the host reads it as AWE memory.
|
||
|
|
const PAGES_64K_BIT: u32 = 0x40_0000;
|
||
|
|
/// The host's protection constants and `PAGE_GUARD`. Above them the console
|
||
|
|
/// adds GPU access bits (0x800-0x40000). Write-combining and uncached are
|
||
|
|
/// dropped too: our GPU side reads this memory through the CPU.
|
||
|
|
const HOST_PROTECTION: u32 = 0x1ff;
|
||
|
|
/// XMem flags of memory both processors reach: all of ours.
|
||
|
|
const GRAPHICS: u64 = 3;
|
||
|
|
/// XMem flag bit of 32-bit graphics memory.
|
||
|
|
const ADDRESS_32BIT: u64 = 4;
|
||
|
|
|
||
|
|
/// The highest address XMem `flags` allow, 0 for no limit: 32 bits, or
|
||
|
|
/// 46 down to 40 bits from the field at bit 12.
|
||
|
|
fn highest_address(flags: u64) -> usize {
|
||
|
|
let bits = match (flags & ADDRESS_32BIT, flags >> 12 & 7) {
|
||
|
|
(0, 0) => return 0,
|
||
|
|
(0, field) => 47 - field,
|
||
|
|
_ => 32,
|
||
|
|
};
|
||
|
|
(1 << bits) - 1
|
||
|
|
}
|
||
|
|
|
||
|
|
pub extern "system" fn XMemVirtualAlloc(
|
||
|
|
base: *mut c_void,
|
||
|
|
size: usize,
|
||
|
|
kind: u32,
|
||
|
|
flags: u64,
|
||
|
|
protect: u32,
|
||
|
|
) -> *mut c_void {
|
||
|
|
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
|
||
|
|
HighestEndingAddress: highest_address(flags) as *mut c_void,
|
||
|
|
Alignment: if kind & (PAGES_2M | PAGES_64K_BIT) == PAGES_2M {
|
||
|
|
2 * MIB
|
||
|
|
} else {
|
||
|
|
0
|
||
|
|
},
|
||
|
|
..Default::default()
|
||
|
|
};
|
||
|
|
let mut kind = kind & !(PAGES_2M | PAGES_64K_BIT);
|
||
|
|
let protect = match protect & HOST_PROTECTION {
|
||
|
|
0 => PAGE_NOACCESS,
|
||
|
|
p => p,
|
||
|
|
};
|
||
|
|
let mut parameter = MEM_EXTENDED_PARAMETER::default();
|
||
|
|
parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
|
||
|
|
parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
|
||
|
|
// Address requirements apply to reservations at an address of our choice.
|
||
|
|
let constrained = base.is_null()
|
||
|
|
&& (!requirements.HighestEndingAddress.is_null() || requirements.Alignment != 0);
|
||
|
|
if constrained {
|
||
|
|
kind |= MEM_RESERVE;
|
||
|
|
}
|
||
|
|
// SAFETY: the title's own arguments, cleaned of console bits; the
|
||
|
|
// parameter points at `requirements`, which outlives the call.
|
||
|
|
unsafe {
|
||
|
|
VirtualAlloc2(
|
||
|
|
GetCurrentProcess(),
|
||
|
|
base,
|
||
|
|
size,
|
||
|
|
kind,
|
||
|
|
protect,
|
||
|
|
if constrained { &mut parameter } else { std::ptr::null_mut() },
|
||
|
|
constrained.into(),
|
||
|
|
)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
|
||
|
|
/// same), then the XMem flags and tag.
|
||
|
|
#[repr(C)]
|
||
|
|
pub struct BasicInformation {
|
||
|
|
host: MEMORY_BASIC_INFORMATION,
|
||
|
|
flags: u64,
|
||
|
|
tag_code: u32,
|
||
|
|
tag: [u8; 4],
|
||
|
|
}
|
||
|
|
|
||
|
|
// shortcut: every committed page reports graphics memory and no tag, since
|
||
|
|
// all of it is GPU-reachable here; remember the flags of `XMemVirtualAlloc`
|
||
|
|
// regions if a title tells CPU-only memory apart.
|
||
|
|
pub extern "system" fn XMemVirtualQuery(
|
||
|
|
process: HANDLE,
|
||
|
|
address: *const c_void,
|
||
|
|
out: *mut BasicInformation,
|
||
|
|
) -> BOOL {
|
||
|
|
let size = size_of::<MEMORY_BASIC_INFORMATION>();
|
||
|
|
// SAFETY: the title passes room for the whole structure; the host
|
||
|
|
// fails on a null one.
|
||
|
|
unsafe {
|
||
|
|
if VirtualQueryEx(process, address, out.cast(), size) == 0 {
|
||
|
|
return 0;
|
||
|
|
}
|
||
|
|
let info = &mut *out;
|
||
|
|
info.flags = if info.host.State == MEM_COMMIT { GRAPHICS } else { 0 };
|
||
|
|
info.tag_code = 0;
|
||
|
|
info.tag = [0; 4];
|
||
|
|
}
|
||
|
|
1
|
||
|
|
}
|
||
|
|
|
||
|
|
// `XMemAlloc` attributes: alignment as log2 (5 bits at 24, 4 bytes and up
|
||
|
|
// from 2), then the memory type, then bit 33: a 32-bit address.
|
||
|
|
const ALIGNMENT_SHIFT: u64 = 24;
|
||
|
|
const ALLOC_32BIT: u64 = 1 << 33;
|
||
|
|
/// Our block header: the block's size and alignment, just below the
|
||
|
|
/// pointer handed out.
|
||
|
|
const HEADER: usize = 2 * size_of::<usize>();
|
||
|
|
|
||
|
|
fn layout(size: usize, attributes: u64) -> Option<Layout> {
|
||
|
|
// An alignment of at least 16 leaves room for the header.
|
||
|
|
let align = 1usize << (attributes >> ALIGNMENT_SHIFT & 0x1f).max(4);
|
||
|
|
Layout::from_size_align(size.checked_add(align)?, align).ok()
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The title's general allocator, for middleware too.
|
||
|
|
// shortcut: allocation hooks (`XMemSetAllocationHooks`, or hooks the title
|
||
|
|
// exports) are not called; no title we have sets them.
|
||
|
|
pub extern "system" fn XMemAlloc(size: usize, attributes: u64) -> *mut c_void {
|
||
|
|
if attributes & ALLOC_32BIT != 0 {
|
||
|
|
return XMemVirtualAlloc(
|
||
|
|
std::ptr::null_mut(),
|
||
|
|
size,
|
||
|
|
MEM_RESERVE | MEM_COMMIT,
|
||
|
|
GRAPHICS | ADDRESS_32BIT,
|
||
|
|
PAGE_READWRITE,
|
||
|
|
);
|
||
|
|
}
|
||
|
|
let Some(layout) = layout(size, attributes) else {
|
||
|
|
return std::ptr::null_mut();
|
||
|
|
};
|
||
|
|
// SAFETY: the layout has a non-zero size.
|
||
|
|
let block = unsafe { alloc(layout) };
|
||
|
|
if block.is_null() {
|
||
|
|
return block.cast();
|
||
|
|
}
|
||
|
|
// SAFETY: the block holds the alignment (at least the header) and then
|
||
|
|
// `size` bytes.
|
||
|
|
unsafe {
|
||
|
|
let user = block.add(layout.align());
|
||
|
|
user.sub(HEADER)
|
||
|
|
.cast::<[usize; 2]>()
|
||
|
|
.write([layout.size(), layout.align()]);
|
||
|
|
user.cast()
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Frees what [`XMemAlloc`] returned, given the same attributes.
|
||
|
|
pub extern "system" fn XMemFree(address: *mut c_void, attributes: u64) {
|
||
|
|
if address.is_null() {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
// SAFETY: the address came from `XMemAlloc` with these attributes: a
|
||
|
|
// whole reservation, or a header-prefixed block.
|
||
|
|
unsafe {
|
||
|
|
if attributes & ALLOC_32BIT != 0 {
|
||
|
|
VirtualFree(address, 0, MEM_RELEASE);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
let user = address.cast::<u8>();
|
||
|
|
let [size, align] = user.sub(HEADER).cast::<[usize; 2]>().read();
|
||
|
|
dealloc(
|
||
|
|
user.sub(align),
|
||
|
|
Layout::from_size_align_unchecked(size, align),
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The oldest layout we know; newer titles pass other flag values (Minecraft
|
||
|
|
/// 0x20000001) and read the same leading fields.
|
||
|
|
#[repr(C)]
|
||
|
|
#[derive(Debug, Default)]
|
||
|
|
pub struct WorkingSet {
|
||
|
|
pub title_limit: usize,
|
||
|
|
pub title_used: usize,
|
||
|
|
pub tools_limit: usize,
|
||
|
|
pub tools_used: usize,
|
||
|
|
pub stack_used: u32,
|
||
|
|
pub physical_pages: u32,
|
||
|
|
pub gpu_optimal_limit: usize,
|
||
|
|
pub gpu_optimal_used: usize,
|
||
|
|
pub tools_gpu_optimal_limit: usize,
|
||
|
|
pub tools_gpu_optimal_used: usize,
|
||
|
|
pub kernel_pool_used: u32,
|
||
|
|
pub kernel_pool_limit: u32,
|
||
|
|
}
|
||
|
|
|
||
|
|
/// The title's budget and our process's commit as what it uses. No tools
|
||
|
|
/// memory: a retail console.
|
||
|
|
// shortcut: all fields are filled whatever the flags ask for, and use is
|
||
|
|
// not split by bandwidth class (GPU-optimal use reads 0); track
|
||
|
|
// allocations per class if a title budgets from that field.
|
||
|
|
pub extern "system" fn XMemGetWorkingSetStatistics(_which: u32, out: *mut WorkingSet) -> BOOL {
|
||
|
|
if out.is_null() {
|
||
|
|
return 0;
|
||
|
|
}
|
||
|
|
let mut counters = PROCESS_MEMORY_COUNTERS {
|
||
|
|
cb: size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
|
||
|
|
..Default::default()
|
||
|
|
};
|
||
|
|
// SAFETY: our own process and a sized structure.
|
||
|
|
unsafe { K32GetProcessMemoryInfo(GetCurrentProcess(), &mut counters, counters.cb) };
|
||
|
|
let stats = WorkingSet {
|
||
|
|
title_limit: GPU_OPTIMAL_LIMIT + STANDARD_LIMIT - TRANSFERRED.load(Ordering::Relaxed),
|
||
|
|
title_used: counters.PagefileUsage,
|
||
|
|
gpu_optimal_limit: GPU_OPTIMAL_LIMIT,
|
||
|
|
..Default::default()
|
||
|
|
};
|
||
|
|
// SAFETY: checked non-null; the title passes room for the structure.
|
||
|
|
unsafe { out.write(stats) };
|
||
|
|
1
|
||
|
|
}
|
||
|
|
|
||
|
|
/// Hands title memory (standard, in 2 MiB pages) to the system. The other
|
||
|
|
/// transfers involve tools memory, which a retail console has none of.
|
||
|
|
pub extern "system" fn XMemTransferMemory(kind: u32, size: usize) -> BOOL {
|
||
|
|
const TITLE_TO_SYSTEM: u32 = 0;
|
||
|
|
tracing::info!(kind, size, "XMemTransferMemory");
|
||
|
|
if size == 0 {
|
||
|
|
return 1;
|
||
|
|
}
|
||
|
|
let Some(size) = size.checked_next_multiple_of(2 * MIB) else {
|
||
|
|
return 0;
|
||
|
|
};
|
||
|
|
let moved = kind == TITLE_TO_SYSTEM
|
||
|
|
&& TRANSFERRED
|
||
|
|
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |t| {
|
||
|
|
t.checked_add(size).filter(|&t| t <= STANDARD_LIMIT)
|
||
|
|
})
|
||
|
|
.is_ok();
|
||
|
|
moved.into()
|
||
|
|
}
|
||
|
|
|
||
|
|
pub(crate) fn module() -> HleModule {
|
||
|
|
HleModule {
|
||
|
|
name: "xmem",
|
||
|
|
dlls: &["xmem.dll"],
|
||
|
|
exports: vec![
|
||
|
|
hle_export!(XMemAlloc),
|
||
|
|
hle_export!(XMemFree),
|
||
|
|
hle_export!(XMemVirtualAlloc),
|
||
|
|
hle_export!(XMemVirtualQuery),
|
||
|
|
hle_export!(XMemGetWorkingSetStatistics),
|
||
|
|
hle_export!(XMemTransferMemory),
|
||
|
|
],
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
#[cfg(test)]
|
||
|
|
mod tests {
|
||
|
|
use super::*;
|
||
|
|
|
||
|
|
fn query(address: *const c_void) -> BasicInformation {
|
||
|
|
// SAFETY: plain data; zero is a valid value.
|
||
|
|
let mut info: BasicInformation = unsafe { std::mem::zeroed() };
|
||
|
|
// SAFETY: a pseudo handle needs no closing.
|
||
|
|
let process = unsafe { GetCurrentProcess() };
|
||
|
|
assert_eq!(XMemVirtualQuery(process, address, &mut info), 1);
|
||
|
|
info
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn alloc_honours_alignment_and_frees() {
|
||
|
|
for (field, align) in [(0, 16), (4, 16), (0xc, 4096), (0x10, 64 * 1024)] {
|
||
|
|
let attributes = field << ALIGNMENT_SHIFT | 1 << 29; // a graphics type
|
||
|
|
let p = XMemAlloc(100, attributes);
|
||
|
|
assert!(!p.is_null());
|
||
|
|
assert_eq!(p as usize % align, 0, "field {field:#x}");
|
||
|
|
// SAFETY: 100 bytes were allocated.
|
||
|
|
unsafe { p.cast::<u8>().write_bytes(0xab, 100) };
|
||
|
|
XMemFree(p, attributes);
|
||
|
|
}
|
||
|
|
let p = XMemAlloc(4096, ALLOC_32BIT);
|
||
|
|
assert!(!p.is_null() && (p as usize) < 1 << 32);
|
||
|
|
XMemFree(p, ALLOC_32BIT);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn virtual_alloc_meets_console_constraints() {
|
||
|
|
const GPU_READ_WRITE: u32 = 0x2000;
|
||
|
|
let p = XMemVirtualAlloc(
|
||
|
|
std::ptr::null_mut(),
|
||
|
|
4 * MIB,
|
||
|
|
PAGES_2M | MEM_RESERVE | MEM_COMMIT,
|
||
|
|
GRAPHICS | 7 << 12, // 40-bit addresses
|
||
|
|
PAGE_READWRITE | GPU_READ_WRITE,
|
||
|
|
);
|
||
|
|
assert!(!p.is_null());
|
||
|
|
assert_eq!(p as usize % (2 * MIB), 0);
|
||
|
|
assert!((p as usize) < 1 << 40);
|
||
|
|
let info = query(p);
|
||
|
|
assert_eq!(info.host.State, MEM_COMMIT);
|
||
|
|
assert_eq!(info.host.Protect, PAGE_READWRITE);
|
||
|
|
assert_eq!(info.flags & GRAPHICS, GRAPHICS);
|
||
|
|
// SAFETY: our own reservation.
|
||
|
|
assert_ne!(unsafe { VirtualFree(p, 0, MEM_RELEASE) }, 0);
|
||
|
|
assert_eq!(query(p).flags, 0);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn transfers_shrink_the_title_budget() {
|
||
|
|
let mut before = WorkingSet::default();
|
||
|
|
assert_eq!(XMemGetWorkingSetStatistics(0x2000_0001, &mut before), 1);
|
||
|
|
assert!(before.title_used > 0);
|
||
|
|
assert_eq!(XMemTransferMemory(0, 128 * MIB - 1), 1);
|
||
|
|
assert_eq!(XMemTransferMemory(2, MIB), 0, "no tools memory");
|
||
|
|
assert_eq!(XMemTransferMemory(0, STANDARD_LIMIT), 0, "over budget");
|
||
|
|
let mut after = WorkingSet::default();
|
||
|
|
XMemGetWorkingSetStatistics(0x2000_0001, &mut after);
|
||
|
|
assert_eq!(before.title_limit - after.title_limit, 128 * MIB);
|
||
|
|
}
|
||
|
|
|
||
|
|
#[test]
|
||
|
|
fn statistics_have_the_console_layout() {
|
||
|
|
assert_eq!(size_of::<WorkingSet>(), 0x50);
|
||
|
|
assert_eq!(size_of::<BasicInformation>(), 0x40);
|
||
|
|
assert_eq!(std::mem::offset_of!(WorkingSet, gpu_optimal_limit), 0x28);
|
||
|
|
}
|
||
|
|
}
|