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
15 changes: 15 additions & 0 deletions runtime/d3d12/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ mod enhanced;
mod descriptors;
mod graphics;
mod copy_memory;
pub(crate) mod list_memory;
mod media;
mod memory_wait;
pub(crate) mod page_mapping;
Expand Down Expand Up @@ -1236,6 +1237,17 @@ fn write_dword(list: &List, state: &mut Recording, address: u64, value: u32) ->
state.prefix.push(&list.native, memory_wait::Packet::Marker(write))
}

// XboxBvhBuilder emits this when its inline packet space is exhausted, with
// the same words it otherwise writes as a 0x4003cc00 packet: group counts X,
// Y, Z and a flags word (0x20 or 0x8020 in the rehydrate path). The flags have
// no desktop equivalent, so the dispatch is recorded as an ordinary one.
unsafe extern "system" fn dispatch_flagged(list: &List, x: u32, y: u32, z: u32, flags: u32) {
static FIRST: std::sync::Once = std::sync::Once::new();
crate::diagnostics::log_once(&FIRST, || format!(
"slot 80 dispatch groups=({x},{y},{z}) flags={flags:#x}"));
unsafe { compute::dispatch(list, x, y, z) }
}

static LIST_SLOTS: Slots<149> = {
let mut slots = child_slots::<ID3D12GraphicsCommandList, ListData, 149>();
slots[8] = crate::slot!(get_type);
Expand Down Expand Up @@ -1301,6 +1313,7 @@ static LIST_SLOTS: Slots<149> = {
slots[71] = crate::slot!(write_marker);
slots[72] = crate::slot!(write_value64);
slots[74] = crate::slot!(memory_wait::wait_value64);
slots[80] = crate::slot!(dispatch_flagged);
slots[83] = crate::slot!(copy_texture);
slots[84] = crate::slot!(copy_resource);
// GTA's texture uploader uses this entry for a placed footprint to a
Expand All @@ -1317,6 +1330,8 @@ static LIST_SLOTS: Slots<149> = {
slots[131] = crate::slot!(build_raytracing::batch);
slots[139] = crate::slot!(reset_extended);
slots[146] = crate::slot!(enhanced::barrier);
// XboxBvhBuilder's batched builds take descriptor memory from the list.
slots[148] = crate::slot!(list_memory::allocate_slot);
slots
};

Expand Down
117 changes: 117 additions & 0 deletions runtime/d3d12/src/commands/list_memory.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
//! Slot 148 hands out memory that lives as long as the command allocator.
//!
//! The console's XboxBvhBuilder calls slot 148 with (byte count, alignment)
//! and writes build descriptors and post-build records into the returned
//! pointer before recording commands that read it by GPU virtual address. On
//! the console that memory comes from the allocator's command buffer and stays
//! valid until the allocator is reset. A null result is checked by only one of
//! the four call sites, so it is not an acceptable fallback.
//!
//! Here each allocator owns a bump arena of committed host pages. Guest GPU
//! addresses equal CPU addresses, so commands that read the memory resolve it
//! through the usual guest-memory import. Pages are never released: a reset
//! returns them to a shared pool, so the same addresses come back and any GPU
//! import of them stays valid.
use std::collections::HashMap;
use std::sync::{LazyLock, Mutex};

use windows::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE};

use super::{recording, List};

const CHUNK: usize = 1 << 20;

struct Chunk {
base: usize,
size: usize,
}

#[derive(Default)]
struct Arena {
chunks: Vec<Chunk>,
used: usize,
}

#[derive(Default)]
struct Pool {
arenas: HashMap<usize, Arena>,
free: Vec<Chunk>,
}

static POOL: LazyLock<Mutex<Pool>> = LazyLock::new(Default::default);

fn take_chunk(free: &mut Vec<Chunk>, bytes: usize) -> Option<Chunk> {
if let Some(index) = free.iter().position(|chunk| chunk.size >= bytes) {
return Some(free.swap_remove(index));
}
let size = bytes.max(CHUNK).checked_next_multiple_of(0x10000)?;
let base = unsafe { VirtualAlloc(None, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) };
(!base.is_null()).then(|| Chunk { base: base as usize, size })
}

/// Bump-allocate `bytes` aligned to `alignment` from the allocator's arena.
fn allocate(allocator: usize, bytes: usize, alignment: usize) -> Option<usize> {
if bytes == 0 || !alignment.is_power_of_two() || alignment > 0x10000 {
return None;
}
let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
let Pool { arenas, free } = &mut *pool;
let arena = arenas.entry(allocator).or_default();
if let Some(chunk) = arena.chunks.last() {
let start = (chunk.base + arena.used).checked_next_multiple_of(alignment)?;
if start.checked_add(bytes)? <= chunk.base + chunk.size {
arena.used = start + bytes - chunk.base;
return Some(start);
}
}
let chunk = take_chunk(free, bytes)?;
let start = chunk.base;
arena.used = bytes;
arena.chunks.push(chunk);
Some(start)
}

/// Return an allocator's pages to the pool once its native reset succeeded.
pub(crate) fn release(allocator: usize) {
let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
if let Some(arena) = pool.arenas.remove(&allocator) {
pool.free.extend(arena.chunks);
}
}

pub(super) unsafe extern "system" fn allocate_slot(list: &List, bytes: u32, alignment: u32) -> *mut core::ffi::c_void {
let state = recording(list);
let allocator = std::sync::Arc::as_ptr(&state.resources) as usize;
drop(state);
let result = allocate(allocator, bytes as usize, (alignment as usize).max(1));
static FIRST: std::sync::Once = std::sync::Once::new();
crate::diagnostics::log_once(&FIRST, || format!(
"slot 148 list memory bytes={bytes} alignment={alignment} -> {:#x}", result.unwrap_or(0)));
result.map_or(core::ptr::null_mut(), |address| address as *mut _)
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn bump_alignment_and_reuse() {
let key = 0x5151_0000;
let a = allocate(key, 40, 8).unwrap();
let b = allocate(key, 56, 16).unwrap();
assert_eq!(b % 16, 0);
assert!(b >= a + 40);
let big = allocate(key, 3 << 20, 16).unwrap();
assert_eq!(big % 16, 0);
release(key);
let again = allocate(key, 40, 8).unwrap();
// A reset hands pages back, so a later arena reuses committed memory.
let pool = POOL.lock().unwrap();
assert!(pool.arenas[&key].chunks.iter().any(|c| c.base == again));
drop(pool);
assert!(allocate(key, 8, 3).is_none());
assert!(allocate(key, 0, 8).is_none());
release(key);
}
}
1 change: 1 addition & 0 deletions runtime/d3d12/src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ unsafe extern "system" fn reset_allocator(this: &Allocator) -> HRESULT {
let status = unsafe { (host.vtable().Reset)(host.as_raw()) };
if status.is_ok() {
sources.clear();
crate::commands::list_memory::release(std::sync::Arc::as_ptr(&this.state) as usize);
}
status
}
Expand Down
Loading