XDefiant: title memory on the GPU (sparse windows), graphics root arguments, vertex buffers

- Sparse windows: the title's own 64 KiB-page reservations get addresses in
  UMA windows 1-3; on the GPU each is a 4 GiB reserved buffer whose tiles map
  onto video memory as pages are committed. CPU writes go to the tiles before
  each submit, only the 64-byte chunks that changed (GPU-written data on the
  same page is kept). Placed buffers there get reserved resources over the
  same tiles.
- Graphics root arguments of console code passed the console way on draws
  (user SGPRs from s8, measured with the console compiler; end-to-end test).
- Console #48 IASetVertexBuffers translates the title's addresses (the
  untranslated ones caused NaN render targets and GPU hangs); #83
  CopyTextureRegionX; #59 ExecuteIndirect on XCL's ABI; console-only
  GraphicsCommandList5/6 IIDs answered by the list object; Map of resources
  at title addresses; aliasing barriers; window functions made Unicode.
- Safety: XCL_RUN_SECONDS ends the title itself (fences released, queues
  drained) instead of an outside kill that left the process stuck in the
  driver; translated loops capped at 65 536 iterations; at most 6 shader
  compiles at once, waiting while commit is low; the title is stopped when
  the device is removed.
- Diagnostics: XCL_TRACE_FRAME, XCL_FRAME_DUMP raw histograms and render
  target dumps, XCL_TRACE_ADDRESSES, XCL_DRED, XCL_TRACE_MEM.

XDefiant now runs 90 s without a GPU hang; its frames are still black.
This commit is contained in:
ivall
2026-11-22 01:01:09 +01:00
parent d82829c163
commit 660f6dc2f0
23 changed files with 1379 additions and 37 deletions
+38 -4
View File
@@ -1109,10 +1109,44 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76
`note_alias`). GPU-owned textures (render target / depth / UAV flags) now go to *arenas*: default heaps standing for
ranges of title addresses (from the 32 MiB below, at least 128 MiB), placed at their address's offset, so resources
at one address share memory. ~16 arenas in XDefiant's first 25 s. Other textures stay committed and mirrored.
- **XDefiant now**: frames 20 and 140 dumped (`XCL_FRAME_DUMP`) – the presented 3840x2160 R10G10B10A2 buffer is
entirely black; at ~25 s four engine threads read a null command-context member (+0x1358 of the object with vtable
+0x34dd7e0) at `+0x6859a1` – not out of video memory (the same with smaller arenas); cause open. Next: find which
pass first writes non-black (dump intermediate render targets / log clear colours), check the final composite.
- **XDefiant now (2026-11-22)**: runs 90 s without a GPU hang and ends itself (`XCL_RUN_SECONDS`); ~1 500 console
shaders translated, thousands of draws and dispatches, nothing skipped. The presented 3840x2160 buffer is still
black: it is written by a compute pass through a UAV (never a render target); the scene / UI render targets are
(almost) black too – the title may be at its online-login gate (another implementer: it retries RTA / Ubisoft
services), or something in the frame is still wrong. ~2.3 frames per second: the sparse-window uploads cost ~30 ms
a submit (126 s in 4 096 submits) – next to optimise (no wait for idle per upload, cheaper dirty scan).
- **What made the GPU hang** (four PC reboots – the AMD driver did not always recover from the TDR): vertex buffers.
Console #48 IASetVertexBuffers gave the title's addresses to the PC as GPU addresses – the index buffer was
translated, the vertex buffers were not (NaN in every render target, then device hangs). `ia_set_vertex_buffers_x`.
- **Console-only list interfaces**: the title queries its lists for the console headers' ID3D12GraphicsCommandList5 /
6 – 55050859-4024-474c-98cf-645b51dc4874 / c3827890-4024-474c-98cf-645b51dc4874 (PC GCL5 / 6 end 87f5-6472eaee44ea /
e548-4cfa-96cf-5689a9370f80) – and copies the answer into its command context unchecked (null → crash after ~25 s).
The console list object answers them with itself (`title_list::CONSOLE_LIST_IIDS`).
- **Console list #83 = CopyTextureRegionX**(dst, x, y, z, src, box, flags) – the title calls it where the DMA list
gets #12; it was a stub (texture uploads through the graphics list were lost). **#59 ExecuteIndirect** with a
translated pipeline binds XCL's ABI first (`bind::execute_indirect`; signatures that change root arguments skipped).
- **Sparse windows** (`d3d12x::sparse`, `gpu::uma`): the title's own reservations of 64 KiB pages (VirtualAlloc
MEM_RESERVE | MEM_64K_PAGES, XDefiant's 8 GB pool) get addresses in UMA windows 1–3 (reserved only); on the GPU each
window is a 4 GiB reserved buffer whose 64 KiB tiles are mapped onto video-memory pool heaps as pages are committed.
The CPU view stays the title's memory; before each ExecuteCommandLists the CPU's writes (write-watch) go to the tiles
– only the 64-byte chunks that changed (`changed_chunks`: hashes of what was sent), so what the GPU wrote on the same
page is not overwritten – and the title's queue waits for that copy. Buffers placed there get reserved resources over
the same tiles. GPU writes are not copied back to the CPU view. Measured first (`tests/heap_probe.rs`): tiles of a
reserved buffer on default heaps work for a whole 4 GiB window; tiles mapped onto heaps opened from file mappings
removed the device (do not try again).
- **Graphics root arguments** measured with the console compiler (`print_graphics_root_argument_placement` /
`_capacity`): VS / PS get them in user SGPRs s8…s31 (24), the rest in the table at s[0:1]; `bind` keeps the graphics
ones and binds them on draws; checked end to end by `console_compiled_graphics_reads_its_root_arguments`.
- **Ending a run without a stuck process**: a host killed from outside with GPU work in flight stayed in the driver
holding 12–16 GB. `XCL_RUN_SECONDS=n` ends the title itself: every fence the title created is signalled to the
maximum (GPU waits on future values complete), the queues drain, then TerminateProcess (`real::end_title`). Shader
compiles: at most 6 at once and they wait while the system has < 6 GB of commit left (`dxc::wait_for_memory`).
- **Window**: titles create their window with CreateWindowExA / RegisterClassExA but DefWindowProcW (its title showed
as CJK characters); `hle::user` makes them Unicode calls. The window stays white (console titles never paint it).
- Diagnostics: `XCL_TRACE_FRAME=1` (what console code does with each presented resource; render-target binds, UAV
views of large render targets, clear colours; with `XCL_FRAME_DUMP` also the busiest render target and raw texel
histograms), `XCL_TRACE_ADDRESSES=1` (root descriptor addresses in / outside unified memory), `XCL_DRED=1` (DRED
page fault + breadcrumbs on a device removal – opt-in: twice the title stalled with it), `XCL_LIST_TRACE=1`.
- **Notes from another implementer** (user-provided): XDefiant also calls XGCreateTextureComputerFromDescriptor, then
libHttpClient / XCurl (XUserGetTokenAndSignature*, XNetworking) and retries wss://rta.xboxlive.com/connect every
10–25 s; a 3D 120x68x64 RGBA16F resource / view returning E_INVALIDARG is not null-checked by the title.
+1
View File
@@ -61,6 +61,7 @@ pub fn set_title_filter(f: usize) -> usize {
}
unsafe extern "system" fn unhandled_filter(info: *const EXCEPTION_POINTERS) -> i32 {
crate::hle::d3d12x::real::log_device_removed();
if !info.is_null() && !(*info).ExceptionRecord.is_null() {
let rec = &*(*info).ExceptionRecord;
let addr = rec.ExceptionAddress as usize;
+23 -3
View File
@@ -115,20 +115,40 @@ struct Job {
reply: std::sync::mpsc::Sender<Result<Vec<u8>, String>>,
}
/// DXC workers (one per core, each with its own compiler and a `DXC_STACK` stack), started
/// on first use; callers wait for their job.
/// Compile threads at most: big translated programs take gigabytes each in DXC and the driver,
/// and a title compiles hundreds at once – the machine must not run out of memory.
pub const MAX_COMPILE_THREADS: usize = 6;
/// Wait (up to a minute) while the system has less than 6 GB of commit left: a compile that
/// would push it to the limit waits for the others to finish.
pub fn wait_for_memory() {
use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX};
let start = std::time::Instant::now();
loop {
let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
if unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= 6 << 30 || start.elapsed().as_secs() >= 60 {
return;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
}
/// DXC workers (one per core, at most `MAX_COMPILE_THREADS`, each with its own compiler and a
/// `DXC_STACK` stack), started on first use; callers wait for their job.
fn pool() -> &'static std::sync::Mutex<std::sync::mpsc::Sender<Job>> {
static POOL: OnceLock<std::sync::Mutex<std::sync::mpsc::Sender<Job>>> = OnceLock::new();
POOL.get_or_init(|| {
let (tx, rx) = std::sync::mpsc::channel::<Job>();
let rx = std::sync::Arc::new(std::sync::Mutex::new(rx));
for k in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) {
for k in 0..std::thread::available_parallelism().map_or(4, |n| n.get()).min(MAX_COMPILE_THREADS) {
let rx = rx.clone();
let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop {
let job = match rx.lock().unwrap().recv() {
Ok(j) => j,
Err(_) => return,
};
wait_for_memory();
let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect();
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra)))
.unwrap_or_else(|_| Err("DXC: panic in the compile thread".into()));
+1 -1
View File
@@ -4360,7 +4360,7 @@ uint dst_sel(uint4 c, uint sel, bool isint) { return select(sel == 0u, 0u, selec
const PRELUDE: &str = r#"
static uint lane_id;
// loop iterations a lane may run (`LOOP_GUARD`): far above what a working program needs
static uint xcl_budget = 1u << 22;
static uint xcl_budget = 1u << 16;
// the high half of a 32 x 32-bit product, from 16-bit parts: DXC turns
// `(uint)(((uint64_t)a * b) >> 32) != 0` (the console's integer division code) into
// umul.with.overflow, which DXIL does not allow (validation fails)
+3 -2
View File
@@ -401,8 +401,9 @@ fn why(_at: u64, msg: &str) {
type MemoKey = (u64, u64, Option<u64>, usize, Option<u64>, Vec<u64>);
/// At the top of every emitted loop: a lane's loop iterations are capped (`xcl_budget`, in
/// the prelude) – console code that loops on what XCL passed it wrong (an address, a count)
/// must not run on the PC GPU until the driver resets it. Once the budget is spent every loop
/// the prelude: 65 536) – console code that loops on what XCL passed it wrong (an address, a
/// count) must not keep the PC GPU busy for minutes (a process with such work in flight cannot
/// even be terminated). Once the budget is spent every loop
/// leaves at its next iteration and the program runs to its end.
const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;";
+1 -1
View File
@@ -25,7 +25,7 @@ pub fn is_console(blob: &[u8]) -> bool {
/// Memory windows of the title's unified memory (1 without it).
pub fn mem_windows() -> u32 {
crate::gpu::uma::get().map_or(1, |u| u.windows() as u32)
crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)
}
/// A static sampler of a translated program: (S#, comparison) – see `Translation`.
+87 -4
View File
@@ -34,6 +34,12 @@ pub struct Uma {
/// bytes of each window
size: usize,
inner: Mutex<Inner>,
/// windows `windows`..4 reserved (not committed) as *sparse* windows: the title's own
/// reservations get their addresses, the GPU sees them through tiled window buffers
/// (`d3d12x::sparse`)
sparse: bool,
/// free ranges of the sparse windows (address → length) and the reservations in them
sparse_free: Mutex<(BTreeMap<usize, usize>, BTreeMap<usize, usize>)>,
}
#[derive(Default)]
@@ -50,7 +56,83 @@ impl Uma {
pub fn new(size: usize) -> Option<Uma> {
let size = ((size + GRAIN - 1) & !(GRAIN - 1)).max(GRAIN);
let n = size.div_ceil(MAX_SIZE).clamp(1, MAX_WINDOWS);
Uma::with_windows(n, (size.div_ceil(n) + GRAIN - 1) & !(GRAIN - 1))
let mut u = Uma::with_windows(n, (size.div_ceil(n) + GRAIN - 1) & !(GRAIN - 1))?;
u.reserve_sparse_windows();
Some(u)
}
/// The windows after the committed ones as one write-watched reservation (sparse windows).
fn reserve_sparse_windows(&mut self) {
if self.windows >= MAX_WINDOWS {
return;
}
let start = self.base + self.windows * WINDOW;
let len = (MAX_WINDOWS - self.windows) * WINDOW;
let p = unsafe { VirtualAlloc(start as *const std::ffi::c_void, len, MEM_RESERVE | MEM_WRITE_WATCH, PAGE_READWRITE) };
if p as usize == start {
self.sparse = true;
self.sparse_free.lock().unwrap().0.insert(start, len);
} else if !p.is_null() {
unsafe { VirtualFree(p, 0, MEM_RELEASE) };
}
}
/// Windows translated shaders address (`mem`, `mem1` …): the committed and the sparse ones.
pub fn shader_windows(&self) -> usize {
if self.sparse {
MAX_WINDOWS
} else {
self.windows
}
}
/// Whether `p` is in a sparse window (the title's reservations).
pub fn is_sparse(&self, p: usize) -> bool {
self.sparse && p >= self.base + self.windows * WINDOW && p < self.base + MAX_WINDOWS * WINDOW
}
/// Whether `p` is in a committed window (XCL's allocations).
pub fn is_committed(&self, p: usize) -> bool {
p.checked_sub(self.base).is_some_and(|o| o / WINDOW < self.windows && o % WINDOW < self.size)
}
/// Address space for a title reservation of `size` bytes in the sparse windows (64 KiB
/// aligned, first fit; not committed).
pub fn sparse_reserve(&self, size: usize) -> Option<usize> {
let size = (size.max(1) + GRAIN - 1) & !(GRAIN - 1);
let mut g = self.sparse_free.lock().unwrap();
let (&at, &len) = g.0.iter().find(|(_, &l)| l >= size)?;
g.0.remove(&at);
if len > size {
g.0.insert(at + size, len - size);
}
g.1.insert(at, size);
Some(at)
}
/// The bytes of the sparse reservation starting at `p` (it is gone after this).
pub fn sparse_release(&self, p: usize) -> Option<usize> {
let mut g = self.sparse_free.lock().unwrap();
let size = g.1.remove(&p)?;
let (mut start, mut len) = (p, size);
if let Some((&o, &l)) = g.0.range(..p).next_back() {
if o + l == p {
g.0.remove(&o);
start = o;
len += l;
}
}
if let Some(l) = g.0.remove(&(p + size)) {
len += l;
}
g.0.insert(start, len);
Some(size)
}
/// The sparse reservation holding `p`: (start, bytes).
pub fn sparse_reservation(&self, p: usize) -> Option<(usize, usize)> {
let g = self.sparse_free.lock().unwrap();
g.1.range(..=p).next_back().map(|(&a, &l)| (a, l)).filter(|&(a, l)| p < a + l)
}
/// `windows` windows of `size` bytes each.
@@ -74,7 +156,7 @@ impl Uma {
for k in 0..windows {
inner.free.insert(k * WINDOW, size);
}
return Some(Uma { base, windows, size, inner: Mutex::new(inner) });
return Some(Uma { base, windows, size, inner: Mutex::new(inner), sparse: false, sparse_free: Mutex::new(Default::default()) });
}
for p in got {
unsafe { VirtualFree(p, 0, MEM_RELEASE) };
@@ -97,13 +179,14 @@ impl Uma {
}
/// (address, bytes) of window `k`
/// (address, bytes) of window `k` (a sparse window: all 4 GiB)
pub fn window(&self, k: usize) -> (usize, usize) {
(self.base + k * WINDOW, self.size)
(self.base + k * WINDOW, if k < self.windows { self.size } else { WINDOW })
}
pub fn window_of(&self, p: usize) -> Option<usize> {
let k = p.checked_sub(self.base)? / WINDOW;
(k < self.windows && p - self.window(k).0 < self.size).then_some(k)
(k < self.shader_windows() && p - self.window(k).0 < self.window(k).1).then_some(k)
}
pub fn contains(&self, p: usize) -> bool {
+60
View File
@@ -123,9 +123,68 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo
/// #42 / #44 / #46 SetGraphicsRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #38 /
/// #40 / #42)
pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) {
note_address(va);
put_in(this, true, i, 0, &va.to_le_bytes());
}
/// `XCL_TRACE_ADDRESSES=1`: root descriptor addresses of console code – in unified memory
/// (translated shaders see them) or not – counted and logged
fn note_address(va: u64) {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static IN: AtomicU64 = AtomicU64::new(0);
static OUT: AtomicU64 = AtomicU64::new(0);
if !*ON.get_or_init(|| std::env::var_os("XCL_TRACE_ADDRESSES").is_some()) {
return;
}
let inside = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize));
let (i, o) = if inside { (IN.fetch_add(1, Ordering::Relaxed) + 1, OUT.load(Ordering::Relaxed)) } else { (IN.load(Ordering::Relaxed), OUT.fetch_add(1, Ordering::Relaxed) + 1) };
if (i + o).is_power_of_two() {
crate::xlog_info!("D3D12.X: root descriptor addresses: {i} in unified memory, {o} outside (latest {va:#x})");
}
}
/// command signatures that change root arguments (they need the title's root signature)
static ROOT_SIGNATURES: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
pub(super) fn note_root_changing_signature(sig: usize) {
ROOT_SIGNATURES.lock().unwrap().get_or_insert_with(Default::default).insert(sig);
}
/// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a
/// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root
/// arguments themselves cannot be – skipped, logged)
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));
let pso = super::pso_async::resolve_wait(with(this, |s| s.pso));
let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso));
let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf));
if !gfx && !compute {
return pc(this, sig, max, args, args_off, count_buf, count_off);
}
if ROOT_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) {
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if N.fetch_add(1, Ordering::Relaxed) < 4 {
crate::xlog_warn!("D3D12.X: ExecuteIndirect that changes root arguments with a translated pipeline skipped");
}
return;
}
let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return };
match bind_abi(this, list, pso, gfx) {
Ok(()) => {
count(if gfx { DRAWS } else { DISPATCHES });
pc(this, sig, max, args, args_off, count_buf, count_off)
}
Err(e) => {
count(if gfx { DRAWS_SKIPPED } else { DISPATCHES_SKIPPED });
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if N.fetch_add(1, Ordering::Relaxed) < 4 {
crate::xlog_warn!("D3D12.X: ExecuteIndirect with a translated pipeline skipped: {e}");
}
}
}
}
/// #12 DrawInstanced
pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) {
if let Some(list) = graphics_bound(this) {
@@ -197,6 +256,7 @@ pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_voi
/// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 /
/// #39 / #41): the 64-bit GPU address
pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) {
note_address(va);
put(this, i, 0, &va.to_le_bytes());
}
+8 -1
View File
@@ -483,6 +483,9 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
Err(_) => {}
}
}
if hr >= 0 && !(*ppv).is_null() {
real::note_title_address(*ppv as usize, va as usize);
}
if hr < 0 || once(&N, 4) {
let w = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap());
crate::xlog_info!(
@@ -546,7 +549,11 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi
}
let needs_root = list.iter().any(|a| (5..=8).contains(&a[0]));
pc[8..16].copy_from_slice(&(if list.is_empty() { 0 } else { list.as_ptr() as u64 }).to_le_bytes());
real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv)
let hr = real::dev_create_command_signature(this, pc.as_ptr() as usize, if needs_root { root } else { 0 }, riid, ppv);
if hr >= 0 && !ppv.is_null() && needs_root {
super::bind::note_root_changing_signature(*ppv as usize);
}
hr
}
#[cfg(test)]
+29
View File
@@ -344,6 +344,25 @@ unsafe fn set_index_buffer(list: *mut c_void, view: Option<&D3D12_INDEX_BUFFER_V
f(list, view.map_or(std::ptr::null(), |v| v as *const _));
}
const PC_IA_SET_VERTEX_BUFFERS: usize = 44;
/// command list #48 IASetVertexBuffers(start slot, count, views) (PC #44): the addresses are
/// the title's (its memory: the GPU address of that memory for the PC)
pub(super) unsafe extern "system" fn ia_set_vertex_buffers_x(this: *mut c_void, start: u32, n: u32, views: *const D3D12_VERTEX_BUFFER_VIEW) {
let f = pc::<unsafe extern "system" fn(*mut c_void, u32, u32, *const D3D12_VERTEX_BUFFER_VIEW)>(this, PC_IA_SET_VERTEX_BUFFERS);
if views.is_null() || n == 0 {
return f(this, start, n, views);
}
let v: Vec<D3D12_VERTEX_BUFFER_VIEW> = (0..n as usize)
.map(|k| {
let mut v = views.add(k).read_unaligned();
v.BufferLocation = pc_va(v.BufferLocation);
v
})
.collect();
f(this, start, n, v.as_ptr())
}
/// command list #47 IASetIndexBuffer(view) (PC #43): the address is the title's
pub(super) unsafe extern "system" fn ia_set_index_buffer_x(this: *mut c_void, view: *const D3D12_INDEX_BUFFER_VIEW) {
let mut m = INDEX_BUFFERS.lock().unwrap();
@@ -512,14 +531,24 @@ pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst
/// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12)
pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) {
if let Some(d) = dst.as_ref() {
super::present::note_use(transmute_copy::<_, usize>(&d.pResource), super::present::USE_COPY);
}
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
}
/// command list #83 CopyTextureRegionX(dst, x, y, z, src, box, flags): CopyTextureRegion with
/// console copy flags (the title's texture streaming calls it where the DMA list gets #12)
pub(super) unsafe extern "system" fn copy_texture_region_flags_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX, _flags: u32) {
copy_texture_region_x(this, dst, x, y, z, src, bx)
}
/// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address
/// are copied as their own bytes (the PC resources also hold what lies before them)
pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) {
super::present::note_use(dst, super::present::USE_COPY);
let (dd, sd) = (real::buffer_delta(dst), real::buffer_delta(src));
if dd == 0 && sd == 0 {
return pc::<unsafe extern "system" fn(*mut c_void, usize, usize)>(this, PC_COPY_RESOURCE)(this, dst, src);
+1
View File
@@ -22,6 +22,7 @@ pub mod null;
pub mod present;
pub mod pso_async;
pub mod real;
pub mod sparse;
pub mod title_list;
pub mod title_textures;
pub mod vram;
+101 -5
View File
@@ -63,6 +63,21 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl
if res == 0 {
return 0;
}
if trace_frame() {
static N: AtomicU64 = AtomicU64::new(0);
let n = N.fetch_add(1, Ordering::Relaxed);
if n < 3 || n % 50 == 0 {
let u = USES.lock().unwrap().as_ref().and_then(|m| m.get(&res).copied()).unwrap_or_default();
let d = ID3D12Resource::from_raw_borrowed(&(res as *mut c_void)).map(|r| r.GetDesc()).map(|d| (d.Width, d.Height, d.Format.0, d.Flags.0));
let busiest: Vec<String> = {
let g = USES.lock().unwrap();
let mut v: Vec<(usize, [u64; 4])> = g.as_ref().map(|m| m.iter().map(|(&k, &u)| (k, u)).collect()).unwrap_or_default();
v.sort_by_key(|(_, u)| std::cmp::Reverse(u[0] + u[1] + u[2]));
v.iter().take(6).map(|(k, u)| format!("{k:#x}: rt {} uav {} copy {} clear {}", u[0], u[1], u[2], u[3])).collect()
};
crate::xlog_info!("frame trace: PresentX #{n} of {res:#x} {:?} – rt binds {}, UAV views {}, copy destination {}, clears {}; most used: {}", d, u[0], u[1], u[2], u[3], busiest.join("; "));
}
}
{
let mut c = CANDIDATE.lock().unwrap();
if c.map(|(_, r)| r) != Some(res) {
@@ -120,6 +135,31 @@ pub unsafe fn note_rtv(handle: usize, res: *mut c_void) {
}
}
/// `XCL_TRACE_FRAME=1`: what console code does with each resource it later presents –
/// render-target binds, UAV views, copy destinations, clears (logged at the first presents)
static USES: Mutex<Option<HashMap<usize, [u64; 4]>>> = Mutex::new(None);
pub const USE_RT: usize = 0;
pub const USE_UAV: usize = 1;
pub const USE_COPY: usize = 2;
pub const USE_CLEAR: usize = 3;
pub fn trace_frame() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("XCL_TRACE_FRAME").is_some())
}
/// `res` was used as `what` (USE_*)
pub fn note_use(res: usize, what: usize) {
if trace_frame() && res != 0 {
USES.lock().unwrap().get_or_insert_with(HashMap::new).entry(res).or_default()[what] += 1;
}
}
/// the resource an RTV handle names (render-target binds)
pub fn rtv_resource(handle: usize) -> Option<usize> {
RTVS.lock().unwrap().as_ref()?.get(&handle).copied()
}
pub fn note_rt0(list: usize, handle: usize) {
if !enabled() {
return;
@@ -151,7 +191,22 @@ unsafe fn backbuffer_like(res: usize) -> Option<D3D12_RESOURCE_DESC> {
ok.then_some(d)
}
/// queues the title submitted work to (AddRef'd: they stay valid for `drain`)
static QUEUES: Mutex<Vec<usize>> = Mutex::new(Vec::new());
/// The queues the title submitted work to.
pub fn known_queues() -> Vec<usize> {
QUEUES.lock().unwrap().clone()
}
pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) {
{
let mut q = QUEUES.lock().unwrap();
if !q.contains(&(queue as usize)) {
add_ref(queue as usize);
q.push(queue as usize);
}
}
if !enabled() || IN_PRESENT.with(|c| c.get()) || PRESENTX.load(Ordering::Relaxed) {
return;
}
@@ -408,7 +463,19 @@ unsafe fn present_now(min_interval: Duration) {
let b1 = [transition(&bb, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST)];
p.list.ResourceBarrier(&b1);
p.list.CopyResource(&bb, src);
let dump = frame_dump_due().then(|| readback_copy(&p.list, src, &desc)).flatten();
let due = frame_dump_due();
let dump = due.then(|| readback_copy(&p.list, src, &desc)).flatten();
// with `XCL_TRACE_FRAME`: also the render target the title binds most (its scene / UI)
let rt_dump = if due && trace_frame() {
busiest_rt().and_then(|r| {
let rr = r as *mut c_void;
let res = ID3D12Resource::from_raw_borrowed(&rr)?.clone();
let d = res.GetDesc();
readback_copy(&p.list, &res, &d).map(|x| (x, d.Format))
})
} else {
None
};
let b2 = [transition(&bb, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT)];
p.list.ResourceBarrier(&b2);
if p.list.Close().is_err() {
@@ -427,7 +494,10 @@ unsafe fn present_now(min_interval: Duration) {
let _ = p.fence.SetEventOnCompletion(p.value, p.event);
WaitForSingleObject(p.event, 2000);
}
write_frame(&rb, &fp, desc.Format);
write_frame(&rb, &fp, desc.Format, "frame");
}
if let Some(((rb, fp), f)) = rt_dump {
write_frame(&rb, &fp, f, "rt");
}
let n = PRESENTS.fetch_add(1, Ordering::Relaxed);
if n == 0 {
@@ -484,11 +554,32 @@ fn rgb(format: DXGI_FORMAT, t: u32) -> Option<[u8; 3]> {
DXGI_FORMAT_R10G10B10A2_UNORM => [(t >> 2 & 0xFF) as u8, (t >> 12 & 0xFF) as u8, (t >> 22 & 0xFF) as u8],
DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_R8G8B8A8_UNORM_SRGB => [t as u8, (t >> 8) as u8, (t >> 16) as u8],
DXGI_FORMAT_B8G8R8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM_SRGB => [(t >> 16) as u8, (t >> 8) as u8, t as u8],
// HDR: tone-mapped for viewing
DXGI_FORMAT_R11G11B10_FLOAT => {
let tm = |v: f32| ((v / (1.0 + v)).sqrt() * 255.0) as u8;
[tm(small_float(t & 0x7FF, 6)), tm(small_float(t >> 11 & 0x7FF, 6)), tm(small_float(t >> 22, 5))]
}
_ => return None,
})
}
unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, format: DXGI_FORMAT) {
/// the resource bound as a render target most often (`XCL_TRACE_FRAME`)
fn busiest_rt() -> Option<usize> {
USES.lock().unwrap().as_ref()?.iter().filter(|(_, u)| u[USE_RT] > 0).max_by_key(|(_, u)| u[USE_RT]).map(|(&r, _)| r)
}
/// an 11- / 10-bit unsigned float (5-bit exponent) -> f32
fn small_float(v: u32, mantissa_bits: u32) -> f32 {
let (e, m) = (v >> mantissa_bits, v & ((1 << mantissa_bits) - 1));
let m = m as f32 / (1u32 << mantissa_bits) as f32;
match e {
0 => m * 2f32.powi(-14),
31 => 65504.0,
_ => (1.0 + m) * 2f32.powi(e as i32 - 15),
}
}
unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT, format: DXGI_FORMAT, tag: &str) {
let mut p: *mut c_void = std::ptr::null_mut();
if rb.Map(0, None, Some(&mut p)).is_err() || p.is_null() {
return;
@@ -508,10 +599,12 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI
bmp.extend_from_slice(&0u32.to_le_bytes());
}
let (mut lit, mut decoded) = (0usize, true);
let mut raw: HashMap<u32, usize> = HashMap::new();
for y in (0..oh).rev() {
let start = bmp.len();
for x in 0..ow {
let t = ((p as *const u8).add(fp.Offset as usize + 4 * y * pitch + 16 * x) as *const u32).read_unaligned();
*raw.entry(t).or_default() += 1;
let c = rgb(format, t).unwrap_or_else(|| {
decoded = false;
[0; 3]
@@ -526,15 +619,18 @@ unsafe fn write_frame(rb: &ID3D12Resource, fp: &D3D12_PLACED_SUBRESOURCE_FOOTPRI
rb.Unmap(0, None);
let n = PRESENTS.load(Ordering::Relaxed);
let Some(boot) = crate::state::boot() else { return };
let path = boot.logs_dir().join(format!("frame_{n}.bmp"));
let path = boot.logs_dir().join(format!("{tag}_{n}.bmp"));
let _ = std::fs::write(&path, &bmp);
crate::xlog_info!(
"present: frame {n} ({w}x{h}, format {}) written to {} – {lit} of {} samples not black{}",
"present: {tag} {n} ({w}x{h}, format {}) written to {} – {lit} of {} samples not black{}",
format.0,
path.display(),
ow * oh,
if decoded { "" } else { " (format not decoded)" }
);
let mut top: Vec<(u32, usize)> = raw.into_iter().collect();
top.sort_by_key(|x| std::cmp::Reverse(x.1));
crate::xlog_info!("present: {tag} {n} raw texels (most common): {}", top.iter().take(6).map(|(v, c)| format!("{v:#010x}×{c}")).collect::<Vec<_>>().join(" "));
}
impl Drop for Presenter {
+1 -1
View File
@@ -39,7 +39,7 @@ fn queue() -> &'static Mutex<mpsc::Sender<(Arc<Pending>, Job)>> {
let (tx, rx) = mpsc::channel::<(Arc<Pending>, Job)>();
let rx = Arc::new(Mutex::new(rx));
// translation recurses deeply on big programs; DXC itself runs on its own pool
let n = std::thread::available_parallelism().map_or(4, |n| n.get());
let n = std::thread::available_parallelism().map_or(4, |n| n.get()).min(crate::gpu::recomp::dxc::MAX_COMPILE_THREADS);
for k in 0..n {
let rx = rx.clone();
let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop {
+193 -4
View File
@@ -239,6 +239,9 @@ unsafe fn open_uma(device: &ID3D12Device) {
crate::xlog_info!("D3D12.X: UMA ({} MB, {} window(s)) opened as GPU heaps, window 0 buffer at VA {:#x}", u.size() >> 20, w.len(), w[0].1);
*UMA_HEAPS.lock().unwrap() = w.iter().map(|x| x.2).collect();
*UMA_BUFFER.lock().unwrap() = w.iter().map(|x| (x.0, x.1)).collect();
// the title's own reservations: sparse windows after these
let sparse = super::sparse::init(device);
UMA_BUFFER.lock().unwrap().extend(sparse);
}
Err(e) => {
crate::xlog_warn!("D3D12.X: UMA not available to the GPU: {e}");
@@ -323,6 +326,16 @@ pub fn init() -> Result<String, String> {
}
}
}
// `XCL_DRED=1`: on a device removal the faulting address and the last GPU operations
// (logged by `log_device_removed`); no debug layer needed. Opt-in: with it XDefiant
// stalled in its first seconds twice.
let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
if std::env::var_os("XCL_DRED").is_some() && D3D12GetDebugInterface(&mut dred).is_ok() {
if let Some(d) = dred {
d.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
d.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
}
}
let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?;
let mut device: Option<ID3D12Device> = None;
let mut name = String::new();
@@ -689,6 +702,9 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> {
(17, l::copy_resource_x as usize),
(13, b::draw_indexed_instanced as usize),
(14, b::dispatch as usize),
(48, l::ia_set_vertex_buffers_x as usize),
(59, b::execute_indirect as usize),
(83, l::copy_texture_region_flags_x as usize),
(34, b::set_graphics_root_signature as usize),
(36, b::set_graphics_root_table as usize),
(38, b::set_graphics_root_constant as usize),
@@ -968,6 +984,15 @@ pub(super) unsafe fn place_at_title_address(this: *mut c_void, va: usize, desc:
if bytes == 0 || va - base + bytes > size {
return None;
}
// the title's own memory (a sparse window): a resource over its video-memory tiles
if u.is_sparse(va) {
let (hr, delta) = super::sparse::place_buffer(this, va, &d, state, riid, ppv)?;
UMA_BUFFERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (va, bytes, false));
if delta != 0 {
BUFFER_DELTA.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, delta as u64);
}
return Some(hr);
}
let heap = *UMA_HEAPS.lock().unwrap().get(k)?;
d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
@@ -1011,7 +1036,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v
if hr >= 0 {
return hr;
}
match super::title_textures::address(this as usize) {
match super::title_textures::address(this as usize).or_else(|| TITLE_ADDRESS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied())) {
Some(p) => {
if !data.is_null() {
*data = p as *mut c_void;
@@ -1030,6 +1055,14 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v
}
}
/// resources the title placed at its own address that got a PC resource of their own: on the
/// console Map gives that address (the CPU's view of the resource)
static TITLE_ADDRESS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
pub(super) fn note_title_address(res: usize, va: usize) {
TITLE_ADDRESS.lock().unwrap().get_or_insert_with(HashMap::new).insert(res, va);
}
/// resources whose Map gave their unified-memory address (no PC mapping to undo)
static UNMAPPABLE: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
@@ -1051,6 +1084,10 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 {
if let Some(m) = BUFFER_DELTA.lock().unwrap().as_mut() {
m.remove(&(this as usize));
}
if let Some(m) = TITLE_ADDRESS.lock().unwrap().as_mut() {
m.remove(&(this as usize));
}
super::sparse::forget_buffer(this as usize);
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()) {
@@ -1268,7 +1305,15 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void,
}
unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, counter: *mut c_void, desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64) {
super::present::note_use(res as usize, super::present::USE_UAV);
let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void, *const D3D12_UNORDERED_ACCESS_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 19));
if super::present::trace_frame() {
let d = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc());
if d.is_some_and(|d| d.Width >= 1920 && d.Flags.0 & 1 != 0) {
let s = super::console_heap::slot(cpu);
crate::xlog_info!("frame trace: UAV of render target {res:p} {:?} at {cpu:#x}: console slot {:?}, view {:?}", d.map(|d| (d.Width, d.Height, d.Format.0)), s.as_ref().map(|s| (s.index, s.pc_uav, s.at)), desc.as_ref().map(|v| (v.Format.0, v.ViewDimension.0)));
}
}
let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, counter, desc, cpu) };
f(this, res, counter, desc, slot.pc_uav);
let Some(r) = ID3D12Resource::from_raw_borrowed(&res) else {
@@ -1418,7 +1463,12 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> {
("CreatePlacedResource1", dev_create_placed_resource1 as usize),
("CreateCommandQueue1", dev_create_command_queue1 as usize),
]),
Kind::CommandList => v.extend_from_slice(&[("OMSetRenderTargets", cl_om_set_render_targets as usize), ("SetPipelineState", cl_set_pipeline_state as usize), ("Close", cl_close as usize)]),
Kind::CommandList => v.extend_from_slice(&[
("OMSetRenderTargets", cl_om_set_render_targets as usize),
("SetPipelineState", cl_set_pipeline_state as usize),
("Close", cl_close as usize),
("ClearRenderTargetView", cl_clear_rtv as usize),
]),
Kind::CommandQueue => v.push(("ExecuteCommandLists", q_execute_command_lists as usize)),
Kind::CommandAllocator => v.push(("Reset", alloc_reset as usize)),
Kind::Resource => v.extend_from_slice(&[("Release", res_release as usize), ("Map", res_map as usize), ("Unmap", res_unmap as usize)]),
@@ -1574,7 +1624,39 @@ creator!(dev_create_reserved_resource, "CreateReservedResource", Kind::Resource,
creator!(dev_create_reserved_resource1, "CreateReservedResource1", Kind::Resource, [a1, a2, a3, a4]);
creator!(dev_create_heap, "CreateHeap", Kind::Heap, [a1]);
creator!(dev_create_heap1, "CreateHeap1", Kind::Heap, [a1, a2]);
creator!(dev_create_fence, "CreateFence", Kind::Fence, [a1, a2]);
creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]);
/// fences created through the device (AddRef'd: they are released at the end only)
static FENCES: Mutex<Vec<usize>> = Mutex::new(Vec::new());
/// CreateFence: as on the PC; the fence is remembered for `end_title`
unsafe extern "system" fn dev_create_fence(this: *mut c_void, value: usize, flags: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
let hr = dev_create_fence_pc(this, value, flags, riid, ppv);
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() {
let add: RefFn = std::mem::transmute(*vt(*ppv).add(1));
add(*ppv);
FENCES.lock().unwrap().push(*ppv as usize);
}
hr
}
/// End the title on purpose without leaving the process stuck in the driver: every fence it
/// created is signalled to the largest value (GPU waits on values the title would have signalled
/// later complete), the queues drain, and the process ends without running DLL detach code.
pub fn end_title(code: u32) -> ! {
unsafe {
for &f in FENCES.lock().unwrap().iter() {
let fr = f as *mut c_void;
if let Some(f) = ID3D12Fence::from_raw_borrowed(&fr) {
let _ = f.Signal(u64::MAX);
}
}
drain_gpu();
crate::log::flush();
windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), code);
}
std::process::abort()
}
creator!(dev_create_query_heap, "CreateQueryHeap", Kind::QueryHeap, [a1]);
creator!(dev_create_command_signature, "CreateCommandSignature", Kind::CommandSignature, [a1, a2]);
creator!(dev_create_pipeline_library, "CreatePipelineLibrary", Kind::PipelineLibrary, [a1, a2]);
@@ -2472,14 +2554,52 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView")));
f(this, res, desc, handle);
super::present::note_rtv(handle, res);
if super::present::trace_frame() {
static N: AtomicU64 = AtomicU64::new(0);
if N.fetch_add(1, Ordering::Relaxed) < 12 {
let d = ID3D12Resource::from_raw_borrowed(&res).map(|r| r.GetDesc()).map(|d| (d.Width, d.Height, d.Format.0));
crate::xlog_info!("frame trace: CreateRenderTargetView {handle:#x} → {res:p} {d:?}");
}
}
}
/// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged)
unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) {
type F = unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const c_void);
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearRenderTargetView")));
if super::present::trace_frame() {
static N: AtomicU64 = AtomicU64::new(0);
if N.fetch_add(1, Ordering::Relaxed) < 16 {
crate::xlog_info!("frame trace: ClearRenderTargetView {rtv:#x} → {:?} colour {:?}, {n} rects", super::present::rtv_resource(rtv), color.as_ref());
}
if let Some(r) = super::present::rtv_resource(rtv) {
super::present::note_use(r, super::present::USE_CLEAR);
}
}
f(this, rtv, color, n, rects)
}
unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) {
type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize);
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "OMSetRenderTargets")));
f(this, n, rtvs, single, dsv);
if super::present::trace_frame() {
static N: AtomicU64 = AtomicU64::new(0);
if N.fetch_add(1, Ordering::Relaxed) < 12 {
let first = if n > 0 && !rtvs.is_null() { *rtvs } else { 0 };
crate::xlog_info!("frame trace: OMSetRenderTargets({n}, first {first:#x} → {:?}, single {single}, dsv {:?})", super::present::rtv_resource(first), dsv.as_ref().copied());
}
}
if n > 0 && !rtvs.is_null() {
super::present::note_rt0(this as usize, *rtvs);
if super::present::trace_frame() {
for k in 0..n as usize {
let h = if single != 0 { *rtvs + k * 32 } else { *rtvs.add(k) };
if let Some(r) = super::present::rtv_resource(h) {
super::present::note_use(r, super::present::USE_RT);
}
}
}
}
}
@@ -2510,7 +2630,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis
type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void);
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists")));
// textures in title memory the CPU wrote since: uploaded again first
super::title_textures::refresh();
super::title_textures::refresh(this);
// console-shaped lists run as the PC lists they were translated into
let mapped: Vec<*mut c_void>;
let lists = if n > 0 && !lists.is_null() {
@@ -2526,6 +2646,74 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis
stop_if_device_removed();
}
/// Wait (up to 10 s) until the GPU has finished the work submitted to the queues console code
/// used (before the process ends on purpose).
pub fn drain_gpu() {
let raw = device_raw();
let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return };
unsafe {
// a fence per queue (they finish in any order)
let mut fences = Vec::new();
for q in super::present::known_queues() {
let qr = q as *mut c_void;
let (Some(q), Ok(f)) = (ID3D12CommandQueue::from_raw_borrowed(&qr), dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE)) else { continue };
if q.Signal(&f, 1).is_ok() {
fences.push(f);
}
}
let start = std::time::Instant::now();
while fences.iter().any(|f| f.GetCompletedValue() < 1) && start.elapsed().as_secs() < 10 {
std::thread::sleep(std::time::Duration::from_millis(20));
}
}
}
/// If the device was removed: the reason, DRED's page fault (address, the allocations around
/// it) and the operations each command list got to – into the log, once.
pub fn log_device_removed() {
static DONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
let raw = device_raw();
let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return };
let Err(e) = (unsafe { dev.GetDeviceRemovedReason() }) else { return };
if DONE.swap(true, Ordering::AcqRel) {
return;
}
crate::xlog_error!("D3D12 device removed: {:#x} {}", e.code().0 as u32, e.message());
unsafe {
let Ok(dred) = dev.cast::<ID3D12DeviceRemovedExtendedData>() else { return };
if let Ok(pf) = dred.GetPageFaultAllocationOutput() {
let names = |mut n: *const D3D12_DRED_ALLOCATION_NODE| {
let mut v = Vec::new();
while !n.is_null() && v.len() < 8 {
let a = &*n;
let name = if a.ObjectNameA.is_null() { String::new() } else { std::ffi::CStr::from_ptr(a.ObjectNameA as *const std::ffi::c_char).to_string_lossy().into_owned() };
v.push(format!("type {} {}", a.AllocationType.0, name));
n = a.pNext;
}
v.join(", ")
};
let va = pf.PageFaultVA;
let window = uma_window_vas().iter().position(|&w| va >= w && va < w + 0x1_0000_0000).map(|k| format!(" = window {k} + {:#x}", va - uma_window_vas()[k])).unwrap_or_default();
crate::xlog_error!("DRED page fault at GPU VA {va:#x}{window}; allocations there: [{}]; recently freed: [{}]", names(pf.pHeadExistingAllocationNode), names(pf.pHeadRecentFreedAllocationNode));
}
if let Ok(bc) = dred.GetAutoBreadcrumbsOutput() {
let mut n = bc.pHeadAutoBreadcrumbNode;
let mut k = 0;
while !n.is_null() && k < 64 {
let node = &*n;
let count = node.BreadcrumbCount as usize;
let done = if node.pLastBreadcrumbValue.is_null() { 0 } else { *node.pLastBreadcrumbValue as usize };
if done < count {
let ops: Vec<String> = (done.saturating_sub(3)..(done + 3).min(count)).map(|i| format!("{}{}", if i == done { ">" } else { "" }, (*node.pCommandHistory.add(i)).0)).collect();
crate::xlog_error!("DRED: list {:p} on queue {:p}: {done} of {count} operations done, around: {}", node.pCommandList.as_ref().map_or(std::ptr::null_mut(), |l| l.as_raw()), node.pCommandQueue.as_ref().map_or(std::ptr::null_mut(), |q| q.as_raw()), ops.join(" "));
}
n = node.pNext;
k += 1;
}
}
}
}
/// The GPU hung or the device was removed: the title is stopped at once (a title that goes on
/// submitting work to a hung device can keep the driver from recovering), with the reason in
/// the log and the report.
@@ -2533,6 +2721,7 @@ pub fn stop_if_device_removed() {
let raw = device_raw();
let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return };
if let Err(e) = unsafe { dev.GetDeviceRemovedReason() } {
log_device_removed();
let msg = format!("the D3D12 device was removed ({:#x}: {}) – the title is stopped", e.code().0 as u32, e.message());
crate::xlog_error!("{msg}");
crate::report::write_final(Some(msg));
+524
View File
@@ -0,0 +1,524 @@
//! The title's own memory, seen by the GPU: sparse windows.
//!
//! A console title keeps GPU data in memory it reserves and commits itself (XDefiant: one
//! 8 GB reservation of 64 KiB pages it commits in steps and places buffers in) – on the
//! console all of it is GPU-visible at the same addresses. XCL gives such reservations
//! addresses in the *sparse windows* of the unified-memory block (`gpu::uma`: windows after
//! the committed one, reserved only), so translated shaders reach them through `mem1`…`mem3`
//! like any unified memory. On the GPU each sparse window is a reserved (tiled) buffer of
//! 4 GiB whose 64 KiB tiles are mapped onto video-memory heaps as the title commits pages.
//! The CPU's view stays the title's memory: what the CPU wrote (write-watch) is copied into
//! the tiles before the title's next ExecuteCommandLists, and its queues wait for that copy.
//! Only the bytes the CPU changed go (64-byte chunks against a hash of what was sent last,
//! `changed_chunks`): the rest of a written page may hold what the GPU wrote there (counters,
//! indirect arguments) and must not be overwritten with the CPU's stale view of it.
//! Buffers the title places there get reserved resources over the same tiles, so PC-side
//! copies, views and barriers see the same memory. GPU writes are not copied back to the
//! CPU's view (not needed by rendering so far).
use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::Mutex;
use windows::core::Interface;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;
const TILE: usize = 0x1_0000;
/// tiles of a video-memory pool heap (64 MiB)
const POOL_TILES: u32 = 1024;
/// bytes of the upload staging buffer
const STAGING: usize = 64 << 20;
struct State {
dev: ID3D12Device,
queue: ID3D12CommandQueue,
fence: ID3D12Fence,
value: u64,
/// (window start, reserved buffer) of each sparse window
windows: Vec<(usize, ID3D12Resource)>,
pools: Vec<ID3D12Heap>,
free: Vec<(u32, u32)>,
/// tile address → (pool, tile in it)
mapped: HashMap<usize, (u32, u32)>,
/// pool tiles also used by placed buffers (not freed while they are)
pinned: HashMap<(u32, u32), u32>,
/// placed buffers → the pool tiles they use
buffers: HashMap<usize, Vec<(u32, u32)>>,
/// reused tiles to clear: (address, bytes)
to_zero: Vec<(usize, usize)>,
staging: Option<(ID3D12Resource, *mut u8)>,
alloc: ID3D12CommandAllocator,
list: ID3D12GraphicsCommandList,
/// the fence value each title queue last waited for
waited: HashMap<usize, u64>,
/// 4 KiB page → hash of each 64-byte chunk the GPU got from the CPU (absent: all zero)
sent: HashMap<usize, Box<[u64; CHUNKS]>>,
}
const PAGE: usize = 0x1000;
const CHUNK: usize = 64;
const CHUNKS: usize = PAGE / CHUNK;
/// hash of 64 bytes
fn chunk_hash(c: &[u8]) -> u64 {
let mut h = 0x243F_6A88_85A3_08D3u64;
for w in c.chunks_exact(8) {
h = (h ^ u64::from_le_bytes(w.try_into().unwrap())).wrapping_mul(0x9E37_79B9_7F4A_7C15).rotate_left(29);
}
h
}
fn zero_hashes() -> [u64; CHUNKS] {
[chunk_hash(&[0u8; CHUNK]); CHUNKS]
}
/// The byte ranges (offset, length) of `page` whose 64-byte chunks differ from `sent`
/// (updated to the page's chunks).
pub fn changed_chunks(page: &[u8], sent: &mut [u64; CHUNKS]) -> Vec<(usize, usize)> {
let mut out: Vec<(usize, usize)> = Vec::new();
for (k, c) in page.chunks_exact(CHUNK).enumerate() {
let h = chunk_hash(c);
if h == sent[k] {
continue;
}
sent[k] = h;
match out.last_mut() {
Some(last) if last.0 + last.1 == k * CHUNK => last.1 += CHUNK,
_ => out.push((k * CHUNK, CHUNK)),
}
}
out
}
// D3D12 objects are free-threaded; the staging pointer is only used under the lock
unsafe impl Send for State {}
static STATE: Mutex<Option<State>> = Mutex::new(None);
/// commits before the device existed
static EARLY: Mutex<Vec<(usize, usize)>> = Mutex::new(Vec::new());
fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_DESC {
D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: bytes,
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,
..Default::default()
}
}
/// The sparse windows' buffers on `dev`: (buffer, GPU address) for each window after the
/// committed ones – the shader ABI's `mem1`… (empty: no sparse windows).
pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, u64)> {
let Some(u) = crate::gpu::uma::get() else { return Vec::new() };
let mut out = Vec::new();
let mut windows = Vec::new();
for k in u.windows()..u.shader_windows() {
let (base, size) = u.window(k);
let mut r: Option<ID3D12Resource> = None;
if let Err(e) = dev.CreateReservedResource(&buffer_desc(size as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut r) {
crate::xlog_warn!("sparse window {k}: CreateReservedResource: {e}");
return Vec::new();
}
let Some(r) = r else { return Vec::new() };
out.push((r.clone().into_raw() as usize, r.GetGPUVirtualAddress()));
windows.push((base, r));
}
let made = (|| -> windows::core::Result<State> {
let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?;
let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?;
list.Close()?;
Ok(State {
dev: dev.clone(),
queue,
fence,
value: 0,
windows,
pools: Vec::new(),
free: Vec::new(),
mapped: HashMap::new(),
pinned: HashMap::new(),
buffers: HashMap::new(),
to_zero: Vec::new(),
staging: None,
alloc,
list,
waited: HashMap::new(),
sent: HashMap::new(),
})
})();
match made {
Ok(s) => {
crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len());
*STATE.lock().unwrap() = Some(s);
for (a, n) in std::mem::take(&mut *EARLY.lock().unwrap()) {
committed(a, n);
}
out
}
Err(e) => {
crate::xlog_warn!("sparse windows: {e}");
Vec::new()
}
}
}
impl State {
fn window(&self, a: usize) -> Option<(usize, &ID3D12Resource)> {
self.windows.iter().find(|(b, _)| a >= *b && a < *b + crate::gpu::uma::WINDOW).map(|(b, r)| (*b, r))
}
unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> {
if let Some(t) = self.free.pop() {
return Some((t, true));
}
let desc = D3D12_HEAP_DESC {
SizeInBytes: POOL_TILES as u64 * TILE as u64,
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
Alignment: 0,
Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES,
};
let mut heap: Option<ID3D12Heap> = None;
if let Err(e) = self.dev.CreateHeap(&desc, &mut heap) {
crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})");
return None;
}
let h = self.pools.len() as u32;
self.pools.push(heap?);
self.free.extend((1..POOL_TILES).rev().map(|t| (h, t)));
Some(((h, 0), false))
}
/// map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles
unsafe fn map_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[(usize, (u32, u32))]) {
for &(a, (h, t)) in tiles {
let start = D3D12_TILED_RESOURCE_COORDINATE { X: ((a - res_base) / TILE) as u32, ..Default::default() };
let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() };
let (flags, n) = (D3D12_TILE_RANGE_FLAG_NONE, 1u32);
self.queue.UpdateTileMappings(res, 1, Some(&start), Some(&region), &self.pools[h as usize], 1, Some(&flags), Some(&t), Some(&n), D3D12_TILE_MAPPING_FLAG_NONE);
}
}
unsafe fn unmap_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[usize]) {
for &a in tiles {
let start = D3D12_TILED_RESOURCE_COORDINATE { X: ((a - res_base) / TILE) as u32, ..Default::default() };
let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() };
let flags = D3D12_TILE_RANGE_FLAG_NULL;
self.queue.UpdateTileMappings(res, 1, Some(&start), Some(&region), None, 1, Some(&flags), None, None, D3D12_TILE_MAPPING_FLAG_NONE);
}
}
/// tiles of `[a, a + n)` get video memory (mapped in their window)
unsafe fn ensure_mapped(&mut self, a: usize, n: usize) {
let first = a & !(TILE - 1);
let mut new: Vec<(usize, (u32, u32))> = Vec::new();
let mut t = first;
while t < a + n {
if !self.mapped.contains_key(&t) && self.window(t).is_some() {
let Some((tile, reused)) = self.take_tile() else { break };
self.mapped.insert(t, tile);
if reused {
self.to_zero.push((t, TILE));
}
new.push((t, tile));
}
t += TILE;
}
// per window
let mut by_window: HashMap<usize, Vec<(usize, (u32, u32))>> = HashMap::new();
for x in new {
if let Some((b, _)) = self.window(x.0) {
by_window.entry(b).or_default().push(x);
}
}
for (b, tiles) in by_window {
if let Some((_, r)) = self.window(b) {
let r = r.clone();
self.map_tiles(&r, b, &tiles);
}
}
self.signal();
}
unsafe fn signal(&mut self) {
self.value += 1;
let _ = self.queue.Signal(&self.fence, self.value);
}
unsafe fn wait_idle(&self) {
if self.fence.GetCompletedValue() < self.value {
if let Ok(ev) = windows::Win32::System::Threading::CreateEventW(None, false, false, None) {
let _ = self.fence.SetEventOnCompletion(self.value, ev);
windows::Win32::System::Threading::WaitForSingleObject(ev, 5000);
let _ = windows::Win32::Foundation::CloseHandle(ev);
}
}
}
unsafe fn staging(&mut self) -> Option<(ID3D12Resource, *mut u8)> {
if self.staging.is_none() {
let mut r: Option<ID3D12Resource> = None;
let mut d = buffer_desc(STAGING as u64);
d.Flags = D3D12_RESOURCE_FLAG_NONE;
self.dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut r).ok()?;
let r = r?;
let mut p = std::ptr::null_mut();
r.Map(0, None, Some(&mut p)).ok()?;
self.staging = Some((r, p as *mut u8));
}
self.staging.clone()
}
/// copy `runs` (address, bytes) of the CPU's view into the tiles (`zero`: clear instead)
unsafe fn upload(&mut self, runs: &[(usize, usize, bool)]) {
let Some((staging, p)) = self.staging() else { return };
let mut used = 0usize;
let mut open = false;
for &(a, n, zero) in runs {
let mut done = 0;
while done < n {
if used == STAGING {
self.flush(&mut open);
used = 0;
}
let chunk = (n - done).min(STAGING - used);
let Some((b, r)) = self.window(a + done).map(|(b, r)| (b, r.clone())) else { break };
if !open {
self.wait_idle();
let _ = self.alloc.Reset();
let _ = self.list.Reset(&self.alloc, None);
open = true;
}
if zero {
std::ptr::write_bytes(p.add(used), 0, chunk);
} else {
std::ptr::copy_nonoverlapping((a + done) as *const u8, p.add(used), chunk);
}
self.list.CopyBufferRegion(&r, (a + done - b) as u64, &staging, used as u64, chunk as u64);
used += chunk;
done += chunk;
}
}
if open {
self.flush(&mut open);
}
}
unsafe fn flush(&mut self, open: &mut bool) {
if !*open {
return;
}
*open = false;
if self.list.Close().is_ok() {
if let Ok(l) = self.list.cast::<ID3D12CommandList>() {
self.queue.ExecuteCommandLists(&[Some(l)]);
}
}
self.signal();
// the staging buffer is written again only after this
self.wait_idle();
}
}
/// The title committed `[a, a + n)` in a sparse window.
pub unsafe fn committed(a: usize, n: usize) {
let mut g = STATE.lock().unwrap();
match g.as_mut() {
Some(s) => s.ensure_mapped(a, n),
None => EARLY.lock().unwrap().push((a, n)),
}
}
/// The title decommitted `[a, a + n)`: its whole tiles give their video memory back (unless a
/// placed buffer still uses it).
pub unsafe fn decommitted(a: usize, n: usize) {
let mut g = STATE.lock().unwrap();
let Some(s) = g.as_mut() else {
EARLY.lock().unwrap().retain(|&(x, m)| x + m <= a || x >= a + n);
return;
};
let first = (a + TILE - 1) & !(TILE - 1);
let tiles: Vec<usize> = (first..(a + n) & !(TILE - 1)).step_by(TILE).filter(|t| s.mapped.contains_key(t)).collect();
let mut by_window: HashMap<usize, Vec<usize>> = HashMap::new();
for &t in &tiles {
if let Some((b, _)) = s.window(t) {
by_window.entry(b).or_default().push(t);
}
}
for (b, ts) in by_window {
if let Some((_, r)) = s.window(b) {
let r = r.clone();
s.unmap_tiles(&r, b, &ts);
}
}
for pg in (a & !(PAGE - 1)..a + n).step_by(PAGE) {
s.sent.remove(&pg);
}
for t in tiles {
if let Some(tile) = s.mapped.remove(&t) {
if !s.pinned.contains_key(&tile) {
s.free.push(tile);
}
}
}
s.signal();
}
impl State {
/// a pool tile no window maps and no buffer uses goes back to the free list
fn release_if_unused(&mut self, tile: (u32, u32)) {
if !self.pinned.contains_key(&tile) && !self.mapped.values().any(|&x| x == tile) {
self.free.push(tile);
}
}
}
/// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB
/// pages from the write-watch, sorted) and the reused tiles are copied into video memory, and
/// `queue` waits for that and for new tile mappings.
pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) {
let t0 = std::time::Instant::now();
let mut g = STATE.lock().unwrap();
let Some(s) = g.as_mut() else { return };
let zeroed = std::mem::take(&mut s.to_zero);
for &(a, n) in &zeroed {
for pg in (a..a + n).step_by(PAGE) {
s.sent.remove(&pg);
}
}
let mut runs: Vec<(usize, usize, bool)> = zeroed.into_iter().map(|(a, n)| (a, n, true)).collect();
let mut i = 0;
while i < dirty.len() {
let a = dirty[i];
let mut n = page;
i += 1;
while i < dirty.len() && dirty[i] == a + n {
n += page;
i += 1;
}
// only what has video memory (committed tiles of a sparse window)
if s.window(a).is_some() {
let mut x = a;
while x < a + n {
let t = x & !(TILE - 1);
let end = (t + TILE).min(a + n);
if s.mapped.contains_key(&t) {
// per page: only the chunks the CPU changed since they were sent
let mut pg = x & !(PAGE - 1);
while pg < end {
let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE);
let sent = s.sent.entry(pg).or_insert_with(|| Box::new(zero_hashes()));
for (o, n) in changed_chunks(bytes, sent) {
match runs.last_mut() {
Some(last) if !last.2 && last.0 + last.1 == pg + o => last.1 += n,
_ => runs.push((pg + o, n, false)),
}
}
pg += PAGE;
}
}
x = end;
}
}
}
if !runs.is_empty() {
s.upload(&runs);
}
{
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
static CALLS: AtomicU64 = AtomicU64::new(0);
static BYTES: AtomicU64 = AtomicU64::new(0);
static MICROS: AtomicU64 = AtomicU64::new(0);
let bytes: usize = runs.iter().map(|r| r.1).sum();
let n = CALLS.fetch_add(1, Relaxed) + 1;
let b = BYTES.fetch_add(bytes as u64, Relaxed) + bytes as u64;
let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Relaxed) + t0.elapsed().as_micros() as u64;
if n.is_power_of_two() && n >= 16 {
crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len());
}
}
let q = queue.as_raw() as usize;
if s.value > 0 && s.waited.get(&q).copied().unwrap_or(0) < s.value {
let _ = queue.Wait(&s.fence, s.value);
s.waited.insert(q, s.value);
}
}
/// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC
/// description): a reserved resource over the window's tiles there, starting at the 64 KiB
/// below `va` (returned: its distance from there).
pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> {
let mut g = STATE.lock().unwrap();
let s = g.as_mut()?;
let start = va & !(TILE - 1);
let delta = va - start;
let bytes = desc.Width as usize;
s.window(start)?;
s.window(va + bytes - 1)?;
let mut d = *desc;
d.Width = (delta + bytes) as u64;
d.Alignment = 0;
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
let hr = super::real::dev_create_reserved_resource(this, &d as *const _ as usize, state as usize, 0, riid, ppv);
if hr < 0 || ppv.is_null() || (*ppv).is_null() {
return None;
}
// its tiles: the window's video memory at the same addresses
s.ensure_mapped(start, delta + bytes);
let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|&x| (t, x))).collect();
let raw = *ppv;
let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone();
s.map_tiles(&res, start, &tiles);
for &(_, tile) in &tiles {
*s.pinned.entry(tile).or_default() += 1;
}
s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect());
s.signal();
Some((hr, delta))
}
/// A placed buffer is gone: its tiles are not pinned by it any more.
pub fn forget_buffer(res: usize) {
let mut g = STATE.lock().unwrap();
let Some(s) = g.as_mut() else { return };
let Some(tiles) = s.buffers.remove(&res) else { return };
for tile in tiles {
if let Some(c) = s.pinned.get_mut(&tile) {
*c -= 1;
if *c == 0 {
s.pinned.remove(&tile);
s.release_if_unused(tile);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Only the 64-byte chunks the CPU changed are sent again – the rest of the page may hold
/// what the GPU wrote.
#[test]
fn only_changed_chunks_are_sent() {
let mut page = vec![0u8; PAGE];
let mut sent = zero_hashes();
assert!(changed_chunks(&page, &mut sent).is_empty(), "a zero page is what the GPU has");
page[10] = 1;
page[200] = 2;
page[255] = 3;
page[4000] = 4;
assert_eq!(changed_chunks(&page, &mut sent), vec![(0, 64), (192, 64), (3968, 64)]);
assert!(changed_chunks(&page, &mut sent).is_empty(), "nothing changed since");
page[256] = 5; // next to the chunk at 192: one run
page[200] = 9;
assert_eq!(changed_chunks(&page, &mut sent), vec![(192, 128)]);
}
}
+30 -1
View File
@@ -151,9 +151,27 @@ unsafe fn pc_slot(pc: *mut c_void, slot: usize) -> usize {
}
/// QueryInterface: the PC list answers; where it hands out itself, the console object goes out.
/// Command list interfaces of the console's headers that the PC does not know: the console's
/// ID3D12GraphicsCommandList5 / 6 (the PC's data1–data3, another tail – titles ask for them
/// and use the answer without a check). The console object has the console's whole vtable,
/// so it is the answer.
const CONSOLE_LIST_IIDS: [(u32, u16, u16, [u8; 8]); 2] = [
(0x5505_0859, 0x4024, 0x474c, [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74]),
(0xc382_7890, 0x4024, 0x474c, [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74]),
];
unsafe extern "system" fn qi(this: *mut c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
let pc = *((this as usize + F_BACKING) as *const *mut c_void);
let f: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(pc_slot(pc, 0));
if !riid.is_null() && !ppv.is_null() {
let g = &*riid;
if CONSOLE_LIST_IIDS.contains(&(g.data1, g.data2, g.data3, g.data4)) {
let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 1));
add_ref(pc);
*ppv = this;
return 0;
}
}
let hr = f(pc, riid, ppv);
if hr >= 0 && !ppv.is_null() && *ppv == pc {
*ppv = this;
@@ -189,6 +207,10 @@ mod tests {
*ppv = this;
0
}
unsafe extern "system" fn fake_add_ref(this: *mut c_void) -> u32 {
(*(this as *mut Fake)).refs += 1;
(*(this as *mut Fake)).refs
}
unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 {
(*(this as *mut Fake)).refs -= 1;
(*(this as *mut Fake)).refs
@@ -202,6 +224,7 @@ mod tests {
fn console_list_objects_have_no_room_and_forward_to_the_pc_list() {
let mut vt = vec![0usize; LIST_SLOTS];
vt[0] = fake_qi as usize;
vt[1] = fake_add_ref as usize;
vt[2] = fake_release as usize;
vt[20] = fake_this as usize;
let fake = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 }));
@@ -215,12 +238,18 @@ mod tests {
// a method: the PC list's, with the PC list as `this` and the arguments kept
let m: unsafe extern "system" fn(*mut c_void, u64, u64, u64, u64) -> u64 = std::mem::transmute(slot(20));
assert_eq!(m(o, 1, 2, 3, 4), fake as u64 + 4321);
// QueryInterface hands out the console object
// QueryInterface hands out the console object – also for the console-only list IIDs
let q: unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT = std::mem::transmute(slot(0));
let mut out = std::ptr::null_mut();
assert_eq!(q(o, std::ptr::null(), &mut out), 0);
assert_eq!(out, o);
let (d1, d2, d3, d4) = CONSOLE_LIST_IIDS[0];
let gcl5 = GUID { data1: d1, data2: d2, data3: d3, data4: d4 };
let mut out = std::ptr::null_mut();
assert_eq!(q(o, &gcl5, &mut out), 0);
assert_eq!(out, o);
let r: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2));
assert_eq!(r(o), 2);
assert_eq!(r(o), 1);
assert_eq!(r(o), 0); // the object is freed with it
drop(Box::from_raw(fake));
+13 -7
View File
@@ -84,7 +84,7 @@ pub fn address(res: usize) -> Option<usize> {
/// Before the title's GPU work: textures whose memory the CPU wrote since the last look are
/// uploaded again.
pub(super) unsafe fn refresh() {
pub(super) unsafe fn refresh(queue: *mut c_void) {
thread_local! {
static BUSY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
@@ -92,18 +92,20 @@ pub(super) unsafe fn refresh() {
if BUSY.with(|b| b.replace(true)) {
return;
}
refresh_once();
refresh_once(queue);
BUSY.with(|b| b.set(false));
}
unsafe fn refresh_once() {
if TEXTURES.lock().unwrap().is_empty() {
unsafe fn refresh_once(queue: *mut c_void) {
let Some(u) = crate::gpu::uma::get() else { return };
let sparse = u.shader_windows() > u.windows();
if TEXTURES.lock().unwrap().is_empty() && !sparse {
return;
}
let Some(u) = crate::gpu::uma::get() else { return };
let mut dirty: Vec<usize> = Vec::new();
let mut page = 0x1000u32;
let regions: Vec<(usize, usize)> = (0..u.windows()).map(|k| u.window(k)).chain(crate::hle::kernelx::graphics_reservations()).collect();
// the committed windows, the sparse ones (the title's reservations) and other reservations
let regions: Vec<(usize, usize)> = (0..u.shader_windows()).map(|k| u.window(k)).chain(crate::hle::kernelx::graphics_reservations()).collect();
for (base, size) in regions {
loop {
let mut buf = vec![std::ptr::null_mut::<c_void>(); 16384];
@@ -117,10 +119,14 @@ unsafe fn refresh_once() {
}
}
}
dirty.sort_unstable();
// the title's own memory: what the CPU wrote goes to its video memory first
if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) {
super::sparse::before_execute(q, &dirty, page as usize);
}
if dirty.is_empty() {
return;
}
dirty.sort_unstable();
// textures with a written page; a reference each while they are uploaded
let todo: Vec<(ID3D12Resource, Upload)> = {
let t = TEXTURES.lock().unwrap();
+64 -2
View File
@@ -146,7 +146,36 @@ const MEM_WRITE_WATCH: u32 = 0x20_0000;
/// Graphics memory (MEM_GRAPHICS, committed, no fixed address) comes from the unified
/// memory region the GPU uses directly (`gpu::uma`); a graphics reservation (no commit) is
/// write-watched address space of Windows; everything else from Windows.
/// The console's MEM_64K_PAGES (MEM_LARGE_PAGES | MEM_PHYSICAL): title memory of 64 KiB
/// pages – GPU-visible on the console like all title memory.
const MEM_64K_PAGES: u32 = 0x2040_0000;
/// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video
/// memory (`d3d12x::sparse`).
unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void {
let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p));
if !q.is_null() {
crate::hle::d3d12x::sparse::committed(q as usize, n);
}
q
}
pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void {
let uma = crate::gpu::uma::get();
// committing inside one of the title's reservations in a sparse window
if !addr.is_null() && t & 0x1000 != 0 && uma.is_some_and(|u| u.is_sparse(addr as usize)) {
return commit_sparse(addr as usize, size, p);
}
// the title's own reservations of 64 KiB pages: in a sparse window, so the GPU sees them
if addr.is_null() && t & 0x2000 != 0 && t & MEM_64K_PAGES == MEM_64K_PAGES {
if let Some(q) = uma.and_then(|u| u.sparse_reserve(size)) {
if t & 0x1000 != 0 && commit_sparse(q, size, p).is_null() {
uma.map(|u| u.sparse_release(q));
return std::ptr::null_mut();
}
return q as *mut c_void;
}
}
if addr.is_null() && t & MEM_GRAPHICS != 0 && t & 0x1000 != 0 {
if let Some(q) = crate::gpu::uma::get().and_then(|u| u.alloc(size, 0)) {
return q as *mut c_void;
@@ -159,6 +188,9 @@ pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t:
if let Some(q) = crate::gpu::uma::get().and_then(|u| u.reserve(size, 0x1_0000)) {
return q as *mut c_void;
}
if let Some(q) = uma.and_then(|u| u.sparse_reserve(size)) {
return q as *mut c_void;
}
let q = mem::VirtualAlloc(addr, size, mem::MEM_RESERVE | MEM_WRITE_WATCH, sanitize_protect(p));
if !q.is_null() {
GRAPHICS_RESERVATIONS.lock().unwrap().insert(q as usize, size);
@@ -182,6 +214,30 @@ fn trace_mem(what: &str, addr: usize, size: usize, flags: u64, protect: u32, got
/// Blocks of the unified memory region go back to it (MEM_RELEASE) or stay (MEM_DECOMMIT
/// zeroes them); others to Windows.
pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32) -> BOOL {
// the title's reservations in a sparse window: decommit (and on release give the address
// space back); their video memory goes with it
if let Some(u) = crate::gpu::uma::get().filter(|u| u.is_sparse(addr as usize)) {
let a = addr as usize;
let n = if t & 0x8000 != 0 {
match u.sparse_reservation(a) {
Some((start, len)) if start == a => len,
_ => {
fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER);
return 0;
}
}
} else {
size
};
if n > 0 {
mem::VirtualFree(addr, n, mem::MEM_DECOMMIT);
crate::hle::d3d12x::sparse::decommitted(a, n);
}
if t & 0x8000 != 0 {
u.sparse_release(a);
}
return 1;
}
if let Some(u) = crate::gpu::uma::get().filter(|u| u.contains(addr as usize)) {
if t & 0x8000 != 0 {
return u.free(addr as usize) as BOOL;
@@ -533,7 +589,10 @@ unsafe fn unmap_away(away: &mut Away, at: usize) {
if let Some(home) = page_home(page) {
std::ptr::copy_nonoverlapping(at as *const u8, home as *mut u8, PHYS_PAGE);
}
if !crate::gpu::uma::get().is_some_and(|u| u.contains(at)) {
if !crate::gpu::uma::get().is_some_and(|u| u.is_committed(at)) {
if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) {
crate::hle::d3d12x::sparse::decommitted(at, PHYS_PAGE);
}
mem::VirtualFree(at as *mut c_void, PHYS_PAGE, mem::MEM_DECOMMIT);
}
}
@@ -626,7 +685,7 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _
fnd::SetLastError(fnd::ERROR_INVALID_PARAMETER);
return std::ptr::null_mut();
}
let in_uma = |a: usize| crate::gpu::uma::get().is_some_and(|u| u.contains(a));
let in_uma = |a: usize| crate::gpu::uma::get().is_some_and(|u| u.is_committed(a));
for (i, &p) in pages.iter().enumerate() {
let at = base + i * PHYS_PAGE;
unmap_away(away, at);
@@ -641,6 +700,9 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _
return std::ptr::null_mut();
}
std::ptr::copy_nonoverlapping(page_home(p).unwrap() as *const u8, at as *mut u8, PHYS_PAGE);
if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(at)) {
crate::hle::d3d12x::sparse::committed(at, PHYS_PAGE);
}
away.at.insert(at, p);
away.page.insert(p, at);
}
+4 -1
View File
@@ -17,6 +17,7 @@ pub mod dxcompiler;
pub mod kernelx;
pub mod mfplat;
pub mod opus;
pub mod user;
pub mod xaudio2;
pub mod xma2;
pub mod xg;
@@ -93,7 +94,7 @@ fn build(config: &Config) -> Registry {
HleModule::new(XAUDIO2, xaudio2::exports(), &["xaudio2_9.dll"]),
HleModule::new(MFPLAT, mfplat::exports(), &["mfplat.dll"]),
HleModule::new(DXCOMPILER, dxcompiler::exports(), &[]),
HleModule::new(MINUSERX, Vec::new(), &["user32.dll"]),
HleModule::new(MINUSERX, user::exports(), &["user32.dll"]),
HleModule::new(XCRDAPI, dstorage::exports(), &[]),
HleModule::new(XG, xg::exports(), &[]),
];
@@ -147,6 +148,8 @@ fn build(config: &Config) -> Registry {
routes.push((MFPLAT.into(), Route::Hle(mf)));
let u = idx(MINUSERX);
routes.push((MINUSERX.into(), Route::Hle(u)));
// the console's ntuser API sets: Windows' user32 but for the ANSI window functions (`user`)
routes.push(("ext-ms-win-rtcore-ntuser-window-ansi-*".into(), Route::Hle(u)));
let s = idx(XCRDAPI);
routes.push((XCRDAPI.into(), Route::Hle(s)));
let g = idx(XG);
+83
View File
@@ -0,0 +1,83 @@
//! `minuserx.dll` / the console's ntuser API sets: the window functions titles use; the rest
//! is Windows' user32.
//!
//! Console titles create their window with the ANSI functions (CreateWindowExA,
//! RegisterClassExA) but give it DefWindowProcW (XDefiant): on Windows that makes the title
//! text show as CJK characters (8-bit text read as UTF-16). The console's user32 is Unicode
//! underneath, so the ANSI calls are made as Unicode ones here – the window is a Unicode window
//! with the text converted.
#![allow(non_snake_case)]
use std::ffi::c_void;
use crate::util::{from_ansi_ptr, wide};
#[link(name = "user32")]
extern "system" {
fn RegisterClassExW(c: *const WndClassEx<u16>) -> u16;
#[allow(clippy::too_many_arguments)]
fn CreateWindowExW(ex_style: u32, class: *const u16, title: *const u16, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void;
}
pub fn exports() -> Vec<(&'static str, usize)> {
crate::hle_exports![CreateWindowExA, RegisterClassExA]
}
/// WNDCLASSEXA (`u8`) / WNDCLASSEXW (`u16`): the same layout, the strings are pointers
#[repr(C)]
pub struct WndClassEx<C> {
cb_size: u32,
style: u32,
wnd_proc: usize,
cls_extra: i32,
wnd_extra: i32,
instance: usize,
icon: usize,
cursor: usize,
background: usize,
menu_name: *const C,
class_name: *const C,
icon_small: usize,
}
/// A class / menu name: an atom (below 0x10000) as it is, a string as UTF-16 (kept alive in
/// `keep`).
unsafe fn name(p: *const u8, keep: &mut Vec<Vec<u16>>) -> *const u16 {
if (p as usize) < 0x1_0000 {
return p as *const u16;
}
keep.push(wide(&from_ansi_ptr(p).unwrap_or_default()));
keep.last().unwrap().as_ptr()
}
pub unsafe extern "system" fn RegisterClassExA(c: *const WndClassEx<u8>) -> u16 {
if c.is_null() {
return 0;
}
let c = &*c;
let mut keep = Vec::new();
let w = WndClassEx::<u16> {
cb_size: std::mem::size_of::<WndClassEx<u16>>() as u32,
style: c.style,
wnd_proc: c.wnd_proc,
cls_extra: c.cls_extra,
wnd_extra: c.wnd_extra,
instance: c.instance,
icon: c.icon,
cursor: c.cursor,
background: c.background,
menu_name: name(c.menu_name, &mut keep),
class_name: name(c.class_name, &mut keep),
icon_small: c.icon_small,
};
RegisterClassExW(&w)
}
#[allow(clippy::too_many_arguments)]
pub unsafe extern "system" fn CreateWindowExA(ex_style: u32, class: *const u8, title: *const u8, style: u32, x: i32, y: i32, w: i32, h: i32, parent: *mut c_void, menu: *mut c_void, instance: *mut c_void, param: *const c_void) -> *mut c_void {
let mut keep = Vec::new();
let class = name(class, &mut keep);
let title = if title.is_null() { std::ptr::null() } else { name(title, &mut keep) };
CreateWindowExW(ex_style, class, title, style, x, y, w, h, parent, menu, instance, param)
}
+11
View File
@@ -29,6 +29,17 @@ pub fn host_main(boot_path: &Path) -> i32 {
std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string());
}
crate::state::set_boot(boot.clone());
// `XCL_RUN_SECONDS=n`: the title ends itself after n seconds – the GPU drained, the log and
// report written (a process killed from outside with GPU work in flight can hang in the driver)
if let Some(secs) = std::env::var("XCL_RUN_SECONDS").ok().and_then(|v| v.parse::<u64>().ok()) {
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(secs));
crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title");
crate::report::write_final(None);
crate::log::flush();
crate::hle::d3d12x::real::end_title(0);
});
}
crate::stubs::init_db(&boot.config.stub_returns);
crate::hle::init(&boot.config);
crate::loader::set_cache_dir(boot.cache_dir());
+42
View File
@@ -505,3 +505,45 @@ fn print_graphics_root_argument_capacity() {
}
}
}
/// A vertex and a pixel shader of the console's compiler that read root constants and a root
/// CBV – translated, drawn with the arguments passed as on a console list's draw
/// (`console_list::user_data_gfx`: from s8, the rest in the table at s[0:1]): the pixels have
/// the values the arguments give.
#[test]
fn console_compiled_graphics_reads_its_root_arguments() {
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R32G32B32_FLOAT;
let Some(c) = console_compiler() else { return };
if runner::adapter().is_err() {
return;
}
let common = "cbuffer k : register(b0) { float k0; float k1; float k2; float k3; };\ncbuffer m : register(b1) { float4 m0; float4 m1; };\n#define ROOT [RootSignature(\"RootConstants(num32BitConstants=4, b0), CBV(b1)\")]\n";
let vs = format!("{common}struct O {{ float4 p : SV_Position; float4 c : COLOR0; }};\nROOT O main(float3 pos : POSITION) {{ O o; o.p = float4(pos.xy * k2, 0.5, 1.0); o.c = m1 * k3; return o; }}\n");
let ps = format!("{common}ROOT float4 main(float4 p : SV_Position, float4 c : COLOR0) : SV_Target {{ return float4(k0, k1, m0.x + c.x, m0.y + c.y); }}\n");
let vs_blob = console_compile(&c, &vs, &["-E", "main", "-T", "vs_6_6"]).unwrap_or_else(|e| panic!("VS: {e}"));
let ps_blob = console_compile(&c, &ps, &["-E", "main", "-T", "ps_6_6"]).unwrap_or_else(|e| panic!("PS: {e}"));
let vs_dxil = pso::console_to_dxil(&vs_blob, pso::Stage::Vertex, 0).unwrap_or_else(|e| panic!("VS translation: {e}")).dxil;
let ps_dxil = pso::console_to_dxil(&ps_blob, pso::Stage::Pixel, 0).unwrap_or_else(|e| panic!("PS translation: {e}")).dxil;
// root arguments: 4 constants (0.25, 0.5, 2.0 – the position scale, 0.5), the CBV's address
let (cbv, table_at) = (0x1000usize, 0x100usize);
let layout = console_list::layout_from_blob(&vs_blob).expect("RTS0");
let mut args: Vec<u8> = [0.25f32, 0.5, 2.0, 0.5].iter().flat_map(|f| f.to_le_bytes()).collect();
args.extend((cbv as u64).to_le_bytes());
let mut mem = vec![0u32; 0x2000 / 4];
for (k, f) in [0.125f32, 0.0625, 0.0, 0.0, 0.5, 0.25, 0.0, 0.0].iter().enumerate() {
mem[cbv / 4 + k] = f.to_bits();
}
for (k, b) in args[layout.inline_gfx as usize..].iter().enumerate() {
mem[(table_at + k) / 4] |= (*b as u32) << (8 * (k % 4));
}
let sgprs = console_list::user_data_gfx(&layout, &args, table_at as u64);
// a triangle over the whole target (positions doubled by k2 = 2)
let tri = [-0.5f32, -0.5, 0.0, 1.5, -0.5, 0.0, -0.5, 1.5, 0.0];
let el = [runner::VertexElement { semantic: "POSITION", index: 0, format: DXGI_FORMAT_R32G32B32_FLOAT, offset: 0 }];
let px = runner::draw(&vs_dxil, &ps_dxil, &el, &tri, 12, &sgprs, &mem, 8, [9.0; 4]).unwrap_or_else(|e| panic!("draw: {e}"));
// k0, k1, m0.x + m1.x · k3, m0.y + m1.y · k3
let want = [0.25f32, 0.5, 0.125 + 0.25, 0.0625 + 0.125];
let p = px[4 * 8 + 4];
println!("pixel {p:?}, want {want:?}");
assert!(p.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-5), "pixel {p:?}, want {want:?}");
}
+61
View File
@@ -215,3 +215,64 @@ fn heaps_over_sections_in_a_placeholder() {
}
}
}
/// A reserved (tiled) buffer of a whole memory window with some 64 KiB tiles mapped onto a
/// default heap (video memory): uploaded data reads back through the window buffer.
/// Standard tiled-resource use; GPU copies only.
#[test]
#[ignore]
fn window_sized_reserved_buffer_on_video_memory_tiles() {
unsafe {
let mut dev: Option<ID3D12Device> = None;
if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut dev).is_err() {
return;
}
let dev = dev.unwrap();
let q: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap();
for size in [4096u64 << 20, (4096u64 << 20) - 0x1_0000] {
let mut rbuf: Option<ID3D12Resource> = None;
let hr = dev.CreateReservedResource(&desc(size, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS), D3D12_RESOURCE_STATE_COMMON, None, &mut rbuf);
let Some(rbuf) = rbuf.filter(|_| hr.is_ok()) else {
println!("reserved buffer of {} MiB: {hr:?}", size >> 20);
continue;
};
let pool_desc = D3D12_HEAP_DESC {
SizeInBytes: 64 << 20,
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
Alignment: 0,
Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES,
};
let mut pool: Option<ID3D12Heap> = None;
dev.CreateHeap(&pool_desc, &mut pool).unwrap();
let pool = pool.unwrap();
// tiles at the start, in the middle and the last one of the window
let last = (size / 0x1_0000 - 1) as u32;
let at = [0u32, 30_000, last];
for (k, &x) in at.iter().enumerate() {
let start = D3D12_TILED_RESOURCE_COORDINATE { X: x, ..Default::default() };
let region = D3D12_TILE_REGION_SIZE { NumTiles: 1, UseBox: false.into(), ..Default::default() };
let (flags, heap_start, n) = (D3D12_TILE_RANGE_FLAG_NONE, k as u32, 1u32);
q.UpdateTileMappings(&rbuf, 1, Some(&start), Some(&region), &pool, 1, Some(&flags), Some(&heap_start), Some(&n), D3D12_TILE_MAPPING_FLAG_NONE);
}
let up = buffer(&dev, D3D12_HEAP_TYPE_UPLOAD, 3 * 0x1_0000, D3D12_RESOURCE_STATE_GENERIC_READ);
let mut p = std::ptr::null_mut();
up.Map(0, None, Some(&mut p)).unwrap();
for i in 0..3 * 0x1_0000 / 4 {
*(p as *mut u32).add(i) = 0x7000_0000 | i as u32;
}
up.Unmap(0, None);
for (k, &x) in at.iter().enumerate() {
gpu_copy(&dev, &q, &rbuf, x as u64 * 0x1_0000, &up, k as u64 * 0x1_0000, 0x1_0000);
}
let rb = buffer(&dev, D3D12_HEAP_TYPE_READBACK, 3 * 0x1_0000, D3D12_RESOURCE_STATE_COPY_DEST);
for (k, &x) in at.iter().enumerate() {
gpu_copy(&dev, &q, &rb, k as u64 * 0x1_0000, &rbuf, x as u64 * 0x1_0000, 0x1_0000);
}
rb.Map(0, None, Some(&mut p)).unwrap();
let ok = (0..3 * 0x1_0000 / 4).all(|i| *(p as *const u32).add(i) == 0x7000_0000 | i as u32);
rb.Unmap(0, None);
println!("reserved buffer of {} MiB, GPU VA {:#x}: tiles 0 / 30000 / {last} on video memory read back: {ok}", size >> 20, rbuf.GetGPUVirtualAddress());
}
}
}