mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
Console command lists of the title's own code; compute root arguments; safety nets
- title_list: console code gets command list objects of the console's shape whose record buffer never has room, so the SDK's inline writers call the list methods instead; each runs on the adopted PC list behind it. - bind: compute root signature and arguments of console code are packed by the root signature's layout and passed the console way (user SGPRs, table) on each Dispatch with a translated pipeline. - ResourceBarrier: aliasing barriers cover any resources (the PC allows them only between placed / reserved ones; the list failed to Close). - Safety: translated shader loops have a per-lane iteration budget; the title is stopped when the D3D12 device is removed. XDefiant now runs: 957 presents in a minute, 3 443 pipelines from 966 translated console shaders, no crash.
This commit is contained in:
+18
-5
@@ -1073,11 +1073,24 @@ of the title (it writes to address 0 after a failed D3D12 call: `call 0x14068c76
|
||||
- **Device #27 CreateCommittedResource from console code**: buffers go to unified memory (as #76); textures get UMA
|
||||
memory of the console size and become title-memory textures (`place_console_texture`), their GetGPUVirtualAddress
|
||||
is that address – XDefiant clears a 32 MB texture with memset through it.
|
||||
- **Where it stops now**: D3D12.X code compiled into the title writes graphics records into the command list object
|
||||
(+0x18 write pointer, +0x30 end; e.g. 0xC000B600 + topology from `IASetPrimitiveTopology`). A PC list has other
|
||||
data there (write to 0x100000000). `XCL_CONSOLE_LISTS=1` (compute records only) gets less far: its lists are not
|
||||
DMA lists. Next: console-shaped graphics lists – the record formats from the title's inline writers, as done for
|
||||
compute in `console_list`.
|
||||
- **Command lists of console code** (`title_list`): the SDK's inline writers put records into the list object when
|
||||
its buffer has room (+0x18 write pointer, +0x30 end, +0x28 dispatch limit) and otherwise call the method the
|
||||
record stands for (0xC000B600 + topology → #20 IASetPrimitiveTopology, 0xC000B800 → the method at vtable +0xC0).
|
||||
Console code gets a console-shaped object whose buffer never has room: every inline write becomes the method call
|
||||
on the adopted PC list behind it (a thunk per slot). `XCL_LIST_TRACE=1` keeps the last 64 slots called and logs
|
||||
them when Close fails.
|
||||
- **Compute root arguments of console code** (`bind`): SetComputeRootSignature / tables / constants / root
|
||||
descriptors (#33–#45) are packed by the root signature's layout; a Dispatch (#14) with a translated pipeline binds
|
||||
XCL's ABI root signature, writes the user SGPRs and the table to unified memory (`user_data`) and dispatches; that
|
||||
memory is freed when the list's allocator is reset. A dispatch whose pipeline has no translation is skipped.
|
||||
- **ResourceBarrier** (#26): aliasing barriers become ones for any resources (both pointers null) – the PC allows
|
||||
them only between placed / reserved resources, and the console's texture memory is mostly XCL's committed
|
||||
resources (the list failed to Close with E_INVALIDARG); console state bits the PC does not know are dropped.
|
||||
- **Result**: the title runs – in one minute 957 presents, 3 443 pipelines from translated console shaders, 966 of
|
||||
966 programs translated, no failed pipeline, no crash. Whether the picture is right is not checked yet.
|
||||
- **Safety nets** (after a GPU hang that needed a PC restart – it came from a diagnostic run that skipped barriers):
|
||||
every loop of a translated shader has a per-lane budget (`LOOP_GUARD`, 4 M iterations); when the D3D12 device is
|
||||
removed (after ExecuteCommandLists, at PresentX) the title is stopped with the reason in the log and the report.
|
||||
- Diagnostics added: `XCL_WATCH_DEVICE=1` / `XCL_WATCH_DMA=1` put a hardware write watchpoint (debug registers, all
|
||||
threads) on the title's device / first DMA list and log each writer with its callers (`eh::watch_writes`);
|
||||
`XCL_D3D12_DEBUG=1` turns on the debug layer and copies its messages into the log (needs the Windows "Graphics
|
||||
|
||||
@@ -4359,6 +4359,8 @@ 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;
|
||||
// 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)
|
||||
|
||||
@@ -399,6 +399,12 @@ fn why(_at: u64, msg: &str) {
|
||||
/// (lo, hi, exit, nest, loop head of `continue`, targets entering the range)
|
||||
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
|
||||
/// leaves at its next iteration and the program runs to its end.
|
||||
const LOOP_GUARD: &str = "if (xcl_budget == 0u) break; xcl_budget--;";
|
||||
|
||||
/// Target of an s_endpgm before the end of the program: "skip to the end".
|
||||
const END: u64 = u64::MAX;
|
||||
/// "Target" of a jump back to the head of the innermost loop: `continue`.
|
||||
@@ -717,7 +723,7 @@ fn emit_structured(
|
||||
}
|
||||
let raised: BTreeSet<u64> = match it {
|
||||
Item::Loop { a, b, latch, entry } => {
|
||||
body.push_str(&format!("{ipad}[loop] for (;;) {{\n"));
|
||||
body.push_str(&format!("{ipad}[loop] for (;;) {{\n{ipad} {LOOP_GUARD}\n"));
|
||||
let (lcont, lin) = if entry.is_none() { (Some(a), &inner) } else { (None, &none) };
|
||||
let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, lcont, lin, d + 1, blocks, flags);
|
||||
for &t in &r {
|
||||
@@ -822,7 +828,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d
|
||||
let start = c.leaders[i];
|
||||
let inner = c.loops.iter().filter(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)).max_by_key(|x| x.1).copied();
|
||||
if let Some((a, b)) = inner {
|
||||
body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n"));
|
||||
body.push_str(&format!("{pad}[loop] while (pc >= {a}u && pc < {b}u) {{\n{pad} {LOOP_GUARD}\n"));
|
||||
emit_range(c, em, body, a, b, depth + 1, blocks, flags);
|
||||
body.push_str(&format!("{pad}}}\n"));
|
||||
i = c.leaders.partition_point(|&l| l < b);
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Root arguments of console code, bound when it dispatches with a translated pipeline.
|
||||
//!
|
||||
//! A translated console shader reads its root arguments the console's way (user SGPRs s4…,
|
||||
//! the rest from a table at s[0:1]: `console_list::user_data`) and memory through XCL's
|
||||
//! shader ABI (u0 io, u1 res, u2… unified memory). So on a command list of console code the
|
||||
//! compute root signature and root arguments are kept here – packed by the root signature's
|
||||
//! layout – instead of going to the PC list, and each Dispatch with a translated pipeline
|
||||
//! binds the ABI root signature, writes the user SGPRs (`io`) and the argument table to
|
||||
//! unified memory and dispatches. That memory stays until the list's allocator is reset.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::c_void;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use windows::core::Interface;
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
|
||||
use super::console_list::{self, Layout, Param};
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
layout: Option<Arc<Layout>>,
|
||||
args: Vec<u8>,
|
||||
pso: usize,
|
||||
allocator: usize,
|
||||
/// unified memory of this recording (io, argument tables)
|
||||
uma: Vec<usize>,
|
||||
}
|
||||
|
||||
static STATES: Mutex<Option<HashMap<usize, State>>> = Mutex::new(None);
|
||||
|
||||
fn with<R>(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R {
|
||||
f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default())
|
||||
}
|
||||
|
||||
/// The list was reset onto `allocator`: the previous recording's memory is the previous
|
||||
/// allocator's until that one is reset.
|
||||
pub(super) fn reset(list: *mut c_void, allocator: usize) {
|
||||
let (old, blocks) = with(list, |s| {
|
||||
let old = std::mem::replace(&mut s.allocator, allocator);
|
||||
(old, std::mem::take(&mut s.uma))
|
||||
});
|
||||
console_list::hold_until_reset(old, blocks);
|
||||
}
|
||||
|
||||
/// The list is gone.
|
||||
pub(super) fn forget(list: *mut c_void) {
|
||||
if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) {
|
||||
console_list::hold_until_reset(s.allocator, s.uma);
|
||||
}
|
||||
}
|
||||
|
||||
/// bytes of parameter `i` at constant `offset`
|
||||
fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) {
|
||||
with(list, |s| {
|
||||
let Some(at) = s.layout.as_ref().and_then(|l| l.params.get(i as usize)).map(|p| match *p {
|
||||
Param::Constants { at, .. } => at as usize + 4 * offset as usize,
|
||||
Param::Descriptor { at } | Param::Table { at } => at as usize,
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
if let Some(t) = s.args.get_mut(at..at + bytes.len()) {
|
||||
t.copy_from_slice(bytes);
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// #33 SetComputeRootSignature (PC #29)
|
||||
pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) {
|
||||
let layout = console_list::layout_of(rs as usize);
|
||||
with(this, |s| {
|
||||
s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)];
|
||||
s.layout = layout;
|
||||
});
|
||||
}
|
||||
|
||||
/// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits
|
||||
pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) {
|
||||
put(this, i, 0, &(handle as u32).to_le_bytes());
|
||||
}
|
||||
|
||||
/// #37 SetComputeRoot32BitConstant (PC #33)
|
||||
pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) {
|
||||
put(this, i, offset, &value.to_le_bytes());
|
||||
}
|
||||
|
||||
/// #39 SetComputeRoot32BitConstants (PC #35)
|
||||
pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) {
|
||||
if !data.is_null() {
|
||||
let bytes: Vec<u8> = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
put(this, i, offset, &bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// #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) {
|
||||
put(this, i, 0, &va.to_le_bytes());
|
||||
}
|
||||
|
||||
/// #25 SetPipelineState: noted, then bound as on the PC
|
||||
pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) {
|
||||
with(this, |s| s.pso = pso as usize);
|
||||
super::real::bind_pipeline(this, pso);
|
||||
}
|
||||
|
||||
/// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments
|
||||
pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) {
|
||||
let pso = with(this, |s| s.pso);
|
||||
let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return };
|
||||
if !super::real::is_translated_compute(pso) {
|
||||
// a console pipeline without a translation: nothing to run (its root arguments were
|
||||
// not given to the PC list either)
|
||||
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
|
||||
crate::xlog_warn!("D3D12.X: Dispatch with a pipeline that has no translated console shader ({pso:#x}) skipped");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Err(e) = translated_dispatch(this, list, pso, x, y, z) {
|
||||
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
|
||||
crate::xlog_warn!("D3D12.X: Dispatch with a translated pipeline skipped: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, x: u32, y: u32, z: u32) -> Result<(), String> {
|
||||
let u = crate::gpu::uma::get().ok_or("no unified memory")?;
|
||||
let windows = super::real::uma_window_vas();
|
||||
let first = *windows.first().ok_or("unified memory is not open on the GPU")?;
|
||||
let (layout, args) = with(this, |s| (s.layout.clone(), s.args.clone()));
|
||||
let mut owned = Vec::new();
|
||||
let mut copy = |bytes: &[u8]| -> Result<usize, String> {
|
||||
let p = u.alloc_in(0, bytes.len().max(16), 256).ok_or("unified memory is full")?; // 32-bit console addresses: window 0
|
||||
std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len());
|
||||
owned.push(p as usize);
|
||||
Ok(p as usize)
|
||||
};
|
||||
let inline = layout.as_ref().map_or(0, |l| l.inline as usize).min(args.len());
|
||||
let table_at = copy(&args[inline..])?;
|
||||
let mut io = match layout.as_ref() {
|
||||
Some(l) => console_list::user_data(l, &args, table_at as u64),
|
||||
None => vec![table_at as u32, (table_at >> 32) as u32],
|
||||
};
|
||||
io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0);
|
||||
let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::<Vec<u8>>())?;
|
||||
let res_at = copy(&[0u8; 256])?;
|
||||
with(this, |s| s.uma.extend(owned));
|
||||
let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first);
|
||||
// a pipeline still being built in the background is waited for
|
||||
let real = super::pso_async::resolve_wait(pso);
|
||||
let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?;
|
||||
let rs = rs as *mut c_void;
|
||||
let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?;
|
||||
list.SetComputeRootSignature(rs);
|
||||
list.SetComputeRootUnorderedAccessView(0, va(io_at));
|
||||
list.SetComputeRootUnorderedAccessView(1, va(res_at));
|
||||
for k in 0..4 {
|
||||
list.SetComputeRootUnorderedAccessView(2 + k as u32, windows.get(k).copied().unwrap_or(first));
|
||||
}
|
||||
let real = real as *mut c_void;
|
||||
let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?;
|
||||
list.SetPipelineState(pc);
|
||||
list.Dispatch(x, y, z);
|
||||
Ok(())
|
||||
}
|
||||
@@ -137,7 +137,7 @@ pub fn note_root_signature(rs: usize, blob: &[u8]) {
|
||||
}
|
||||
}
|
||||
|
||||
fn layout_of(rs: usize) -> Option<Arc<Layout>> {
|
||||
pub(super) fn layout_of(rs: usize) -> Option<Arc<Layout>> {
|
||||
LAYOUTS.lock().unwrap().as_ref()?.get(&rs).cloned()
|
||||
}
|
||||
|
||||
@@ -250,6 +250,14 @@ static LISTS: Mutex<Option<HashMap<usize, ListState>>> = Mutex::new(None);
|
||||
/// unified-memory blocks of finished recordings, freed when their allocator is reset
|
||||
static PENDING: Mutex<Option<HashMap<usize, Vec<usize>>>> = Mutex::new(None);
|
||||
|
||||
/// Unified-memory blocks a recording on `allocator` uses: freed when it is reset (no
|
||||
/// allocator known: kept until the next reset of any – never freed early).
|
||||
pub(super) fn hold_until_reset(allocator: usize, blocks: Vec<usize>) {
|
||||
if !blocks.is_empty() {
|
||||
PENDING.lock().unwrap().get_or_insert_with(HashMap::new).entry(allocator).or_default().extend(blocks);
|
||||
}
|
||||
}
|
||||
|
||||
/// An allocator was reset: the GPU no longer uses what its recordings put in unified memory.
|
||||
pub fn allocator_reset(allocator: *mut c_void) {
|
||||
let blocks = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&(allocator as usize)));
|
||||
|
||||
@@ -89,6 +89,12 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso:
|
||||
crate::eh::watch_writes(*ppv as usize);
|
||||
}
|
||||
}
|
||||
// the title's inline D3D12.X code writes into the list object: it gets one of the
|
||||
// console's shape (`title_list`)
|
||||
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() && !super::console_list::enabled() {
|
||||
super::bind::reset(*ppv, alloc);
|
||||
*ppv = super::title_list::wrap(*ppv);
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,6 @@ use super::real;
|
||||
const PC_GET_TYPE: usize = 8;
|
||||
const PC_RESET: usize = 10;
|
||||
const PC_DRAW_INDEXED: usize = 13;
|
||||
const PC_DISPATCH: usize = 14;
|
||||
const PC_COPY_BUFFER_REGION: usize = 15;
|
||||
const PC_COPY_TEXTURE_REGION: usize = 16;
|
||||
const PC_COPY_RESOURCE: usize = 17;
|
||||
@@ -304,7 +303,7 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min:
|
||||
|
||||
/// command list #78 DispatchX(x, y, z, flags)
|
||||
pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) {
|
||||
pc::<unsafe extern "system" fn(*mut c_void, u32, u32, u32)>(this, PC_DISPATCH)(this, x, y, z);
|
||||
super::bind::dispatch(this, x, y, z);
|
||||
}
|
||||
|
||||
/// command list #84 CopyResourceX(destination, source, flags); in place (the console's
|
||||
@@ -431,6 +430,7 @@ pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, ps
|
||||
if let Some(m) = OCCLUSION.lock().unwrap().as_mut() {
|
||||
m.remove(&(this as usize));
|
||||
}
|
||||
super::bind::reset(this, alloc);
|
||||
// the PC runtime writes its own vtable into a copy list again on Reset: keep XCL's
|
||||
let ext = *(this as *const usize);
|
||||
let hr = pc::<unsafe extern "system" fn(*mut c_void, usize, usize) -> i32>(this, PC_RESET)(this, alloc, pso);
|
||||
@@ -440,6 +440,52 @@ pub(super) unsafe extern "system" fn reset_x(this: *mut c_void, alloc: usize, ps
|
||||
hr
|
||||
}
|
||||
|
||||
/// the D3D12_RESOURCE_STATES bits the PC knows
|
||||
const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 | 0x200 | 0x400 | 0x800 | 0x1000 | 0x2000 | 0xF_0000 | 0x20_0000 | 0x40_0000 | 0x80_0000 | 0x100_0000;
|
||||
|
||||
/// #26 ResourceBarrier(count, barriers): console barriers (D3D12_RESOURCE_BARRIER, 32 bytes) as
|
||||
/// PC ones – state bits the PC does not know are dropped (logged: the console's own), a
|
||||
/// transition left with nothing to do goes, aliasing barriers cover any resources
|
||||
pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) {
|
||||
static N: AtomicU64 = AtomicU64::new(0);
|
||||
if barriers.is_null() || n == 0 {
|
||||
return;
|
||||
}
|
||||
let mut out: Vec<[u32; 8]> = Vec::with_capacity(n as usize);
|
||||
for k in 0..n as usize {
|
||||
let mut b = barriers.add(k).read_unaligned();
|
||||
let (ty, flags) = (b[0], b[1]);
|
||||
if ty > 2 || flags > 3 {
|
||||
if N.fetch_add(1, Ordering::Relaxed) < 16 {
|
||||
crate::xlog_warn!("D3D12.X: ResourceBarrier: console barrier type {ty} flags {flags:#x} dropped ({:x?})", b);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ty == 1 {
|
||||
// aliasing (resource before +8, after +16): on the PC only between placed / reserved
|
||||
// resources, and the console's texture memory is mostly XCL's committed resources
|
||||
// (the list would fail to Close) – an aliasing barrier for any resources instead
|
||||
b[2..6].fill(0);
|
||||
}
|
||||
if ty == 0 {
|
||||
// transition: resource (+8), subresource (+16), before (+20), after (+24)
|
||||
let (before, after) = (b[5], b[6]);
|
||||
if (before | after) & !PC_STATES != 0 && N.fetch_add(1, Ordering::Relaxed) < 16 {
|
||||
crate::xlog_warn!("D3D12.X: ResourceBarrier: console state bits {:#x} → {:#x} dropped", before & !PC_STATES, after & !PC_STATES);
|
||||
}
|
||||
b[5] &= PC_STATES;
|
||||
b[6] &= PC_STATES;
|
||||
if b[5] == b[6] {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(b);
|
||||
}
|
||||
if !out.is_empty() {
|
||||
pc::<unsafe extern "system" fn(*mut c_void, u32, *const [u32; 8])>(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr());
|
||||
}
|
||||
}
|
||||
|
||||
/// A D3D12_TEXTURE_COPY_LOCATION for the log.
|
||||
unsafe fn location(l: *const D3D12_TEXTURE_COPY_LOCATION) -> String {
|
||||
if l.is_null() {
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
|
||||
#![allow(non_snake_case)]
|
||||
|
||||
pub mod bind;
|
||||
pub mod console_heap;
|
||||
pub mod console_list;
|
||||
pub mod device_x;
|
||||
@@ -21,6 +22,7 @@ pub mod null;
|
||||
pub mod present;
|
||||
pub mod pso_async;
|
||||
pub mod real;
|
||||
pub mod title_list;
|
||||
pub mod title_textures;
|
||||
|
||||
use std::ffi::c_void;
|
||||
|
||||
@@ -50,6 +50,7 @@ pub unsafe extern "system" fn present_x(queue: *mut c_void, plane_count: u32, pl
|
||||
}
|
||||
super::frame::mark_flipped((planes as *const u64).read_unaligned());
|
||||
BOUNDARIES.fetch_add(1, Ordering::Relaxed);
|
||||
super::real::stop_if_device_removed();
|
||||
if !PRESENTX.swap(true, Ordering::Relaxed) {
|
||||
crate::xlog_info!("D3D12.X: PresentX – the title presents its own frames ({plane_count} plane(s))");
|
||||
}
|
||||
|
||||
@@ -676,8 +676,20 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> {
|
||||
Kind::CommandQueue => vec![(30, super::present::present_x as usize)],
|
||||
Kind::DmaList => vec![(9, super::list_x::dma_close_x as usize), (10, super::list_x::reset_x as usize), (12, super::list_x::dma_copy_texture_region_x as usize)],
|
||||
Kind::CommandList => {
|
||||
use super::bind as b;
|
||||
use super::list_x as l;
|
||||
vec![
|
||||
// compute root arguments of console code: kept for translated dispatches
|
||||
(14, b::dispatch as usize),
|
||||
(26, l::resource_barrier_x as usize),
|
||||
(25, b::set_pipeline_state as usize),
|
||||
(33, b::set_compute_root_signature as usize),
|
||||
(35, b::set_compute_root_table as usize),
|
||||
(37, b::set_compute_root_constant as usize),
|
||||
(39, b::set_compute_root_constants as usize),
|
||||
(41, b::set_compute_root_descriptor as usize),
|
||||
(43, b::set_compute_root_descriptor as usize),
|
||||
(45, b::set_compute_root_descriptor as usize),
|
||||
(10, l::reset_x as usize),
|
||||
(28, l::begin_query_x as usize),
|
||||
(29, l::end_query_x as usize),
|
||||
@@ -976,7 +988,18 @@ unsafe extern "system" fn pso_release(this: *mut c_void) -> u32 {
|
||||
|
||||
/// A pipeline state is gone: drop what XCL keeps by its address (a later pipeline may get the
|
||||
/// same address and must not inherit its root signature or compute pass).
|
||||
/// compute pipelines that run a translated console shader
|
||||
static TRANSLATED_COMPUTE: Mutex<Option<HashSet<usize>>> = Mutex::new(None);
|
||||
|
||||
/// Whether `pso` runs a translated console compute shader.
|
||||
pub fn is_translated_compute(pso: usize) -> bool {
|
||||
pso != 0 && TRANSLATED_COMPUTE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&pso))
|
||||
}
|
||||
|
||||
fn forget_pso(pso: usize) {
|
||||
if let Some(s) = TRANSLATED_COMPUTE.lock().unwrap().as_mut() {
|
||||
s.remove(&pso);
|
||||
}
|
||||
if let Some(m) = PSO_RS.lock().unwrap().as_mut() {
|
||||
m.remove(&pso);
|
||||
}
|
||||
@@ -1982,6 +2005,12 @@ pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void,
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn note_translated_compute(hr: HRESULT, ppv: *mut *mut c_void) {
|
||||
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() {
|
||||
TRANSLATED_COMPUTE.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
|
||||
super::null::capture_compute_desc(desc as *const u8);
|
||||
let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState")));
|
||||
@@ -1991,12 +2020,14 @@ unsafe extern "system" fn dev_create_compute_pso(this: *mut c_void, desc: *const
|
||||
// a console program the worker is translating (its root signature comes with it)
|
||||
LAST_COMPUTE_TRANSLATED.with(|c| c.set(true));
|
||||
LAST_COMPUTE_RS.with(|c| c.set(0));
|
||||
note_translated_compute(hr, ppv);
|
||||
return hr;
|
||||
}
|
||||
console = translated_compute_pso(this, f, desc, riid, ppv);
|
||||
}
|
||||
LAST_COMPUTE_TRANSLATED.with(|c| c.set(matches!(console, Some(Ok(hr)) if hr >= 0)));
|
||||
if let Some(Ok(hr)) = console {
|
||||
note_translated_compute(hr, ppv);
|
||||
return hr;
|
||||
}
|
||||
// a console shader the recompiler could not take must not reach the driver: AMD's shader
|
||||
@@ -2356,6 +2387,11 @@ unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rt
|
||||
}
|
||||
|
||||
/// A stand-in pipeline is bound as its real pipeline once that is built (compute: waited for).
|
||||
/// SetPipelineState on the PC list (a pipeline still building in the background: its stand-in)
|
||||
pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) {
|
||||
cl_set_pipeline_state(this, pso)
|
||||
}
|
||||
|
||||
unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) {
|
||||
type F = unsafe extern "system" fn(*mut c_void, *mut c_void);
|
||||
let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState")));
|
||||
@@ -2381,7 +2417,7 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis
|
||||
// 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() {
|
||||
mapped = std::slice::from_raw_parts(lists, n as usize).iter().map(|&l| super::console_list::pc_list(l).unwrap_or(l)).collect();
|
||||
mapped = std::slice::from_raw_parts(lists, n as usize).iter().map(|&l| super::console_list::pc_list(l).or_else(|| super::title_list::backing(l)).unwrap_or(l)).collect();
|
||||
mapped.as_ptr()
|
||||
} else {
|
||||
lists
|
||||
@@ -2390,4 +2426,22 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis
|
||||
if n > 0 && !lists.is_null() {
|
||||
super::present::note_execute(this, std::slice::from_raw_parts(lists, n as usize));
|
||||
}
|
||||
stop_if_device_removed();
|
||||
}
|
||||
|
||||
/// 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.
|
||||
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() } {
|
||||
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));
|
||||
crate::log::flush();
|
||||
unsafe {
|
||||
windows_sys::Win32::System::Threading::TerminateProcess(windows_sys::Win32::System::Threading::GetCurrentProcess(), e.code().0 as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Command lists of console code.
|
||||
//!
|
||||
//! The D3D12.X code compiled into a title (the SDK's inline functions) writes command records
|
||||
//! straight into the list object when the list's buffer has room – +0x18 write pointer, +0x30
|
||||
//! end, +0x28 the limit for dispatch records – and otherwise calls the list method the record
|
||||
//! stands for, with the method's own arguments (HANDOFF: "inline writers"; e.g. 0xC000B600 +
|
||||
//! a hardware topology, else #20 IASetPrimitiveTopology). A PC list object has other data at
|
||||
//! those offsets. So console code gets a list object of the console's shape whose buffer never
|
||||
//! has room: every inline write becomes the method call, and each method runs on the
|
||||
//! (adopted) PC list behind it – with all of XCL's console slot handling.
|
||||
//!
|
||||
//! The object: the console fields, the PC list at `F_BACKING`; its vtable is a thunk per slot
|
||||
//! (`mov rcx, [rcx + F_BACKING]` and on to the PC list's own vtable entry). QueryInterface
|
||||
//! hands out the console object again, Release frees it with the PC list, and
|
||||
//! ExecuteCommandLists runs the PC lists (`backing`).
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use windows_sys::core::GUID;
|
||||
|
||||
use crate::util::HRESULT;
|
||||
|
||||
const LIST_SLOTS: usize = 600;
|
||||
/// the object: console fields up to `ROOM`, no-room "buffer" at `ROOM` (with slack after it
|
||||
/// for code that would write before checking), the PC list at `F_BACKING`
|
||||
const OBJECT_BYTES: usize = 0x3000;
|
||||
const ROOM: usize = 0x1000;
|
||||
const F_BACKING: usize = 0x2FF8;
|
||||
const F_WRITE: usize = 0x18;
|
||||
const F_DISPATCH_END: usize = 0x28;
|
||||
const F_END: usize = 0x30;
|
||||
/// `XCL_LIST_TRACE`: the last `RING` slots called (u16 each) and a counter
|
||||
const F_RING: usize = 0x2000;
|
||||
const F_RING_AT: usize = 0x2100;
|
||||
const RING: usize = 64;
|
||||
|
||||
struct Vtable(usize);
|
||||
|
||||
/// The console list vtable: QueryInterface / Release of their own, every other slot a thunk
|
||||
/// to the PC list's entry.
|
||||
fn vtable() -> usize {
|
||||
static V: OnceLock<Vtable> = OnceLock::new();
|
||||
V.get_or_init(|| {
|
||||
let mut v = vec![0usize; LIST_SLOTS];
|
||||
let trace = std::env::var_os("XCL_LIST_TRACE").is_some();
|
||||
for (slot, e) in v.iter_mut().enumerate() {
|
||||
*e = if trace { forward_traced(slot) } else { forward(slot) };
|
||||
}
|
||||
v[0] = qi as usize;
|
||||
v[2] = release as usize;
|
||||
v[9] = close as usize;
|
||||
Vtable(Box::leak(v.into_boxed_slice()).as_ptr() as usize)
|
||||
})
|
||||
.0
|
||||
}
|
||||
|
||||
/// `mov rcx, [rcx + F_BACKING]; mov rax, [rcx]; jmp [rax + slot * 8]`
|
||||
fn forward(slot: usize) -> usize {
|
||||
let mut c = vec![0x48, 0x8B, 0x89];
|
||||
c.extend_from_slice(&(F_BACKING as u32).to_le_bytes());
|
||||
c.extend_from_slice(&[0x48, 0x8B, 0x01, 0xFF, 0xA0]);
|
||||
c.extend_from_slice(&((slot * 8) as u32).to_le_bytes());
|
||||
let p = crate::stubs::alloc_code(c.len());
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len());
|
||||
}
|
||||
p as usize
|
||||
}
|
||||
|
||||
/// `forward` after `record(this, slot)` (argument registers, xmm0–3 kept)
|
||||
fn forward_traced(slot: usize) -> usize {
|
||||
let mut c: Vec<u8> = vec![0x51, 0x52, 0x41, 0x50, 0x41, 0x51]; // push rcx, rdx, r8, r9
|
||||
c.extend_from_slice(&[0x48, 0x83, 0xEC, 0x68]); // sub rsp, 0x68
|
||||
for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] {
|
||||
c.extend_from_slice(&[0xF3, 0x0F, 0x7F, reg, 0x24, off]); // movdqu [rsp+off], xmmN
|
||||
}
|
||||
c.push(0xBA); // mov edx, slot
|
||||
c.extend_from_slice(&(slot as u32).to_le_bytes());
|
||||
c.extend_from_slice(&[0x48, 0xB8]); // mov rax, record
|
||||
c.extend_from_slice(&(record as usize as u64).to_le_bytes());
|
||||
c.extend_from_slice(&[0xFF, 0xD0]); // call rax
|
||||
for (reg, off) in [(0x44u8, 0x20u8), (0x4C, 0x30), (0x54, 0x40), (0x5C, 0x50)] {
|
||||
c.extend_from_slice(&[0xF3, 0x0F, 0x6F, reg, 0x24, off]); // movdqu xmmN, [rsp+off]
|
||||
}
|
||||
c.extend_from_slice(&[0x48, 0x83, 0xC4, 0x68]); // add rsp, 0x68
|
||||
c.extend_from_slice(&[0x41, 0x59, 0x41, 0x58, 0x5A, 0x59]); // pop r9, r8, rdx, rcx
|
||||
c.extend_from_slice(&[0x48, 0x8B, 0x89]);
|
||||
c.extend_from_slice(&(F_BACKING as u32).to_le_bytes());
|
||||
c.extend_from_slice(&[0x48, 0x8B, 0x01, 0xFF, 0xA0]);
|
||||
c.extend_from_slice(&((slot * 8) as u32).to_le_bytes());
|
||||
let p = crate::stubs::alloc_code(c.len());
|
||||
unsafe {
|
||||
std::ptr::copy_nonoverlapping(c.as_ptr(), p, c.len());
|
||||
}
|
||||
p as usize
|
||||
}
|
||||
|
||||
unsafe extern "system" fn record(this: *mut c_void, slot: u32) {
|
||||
let at = (this as usize + F_RING_AT) as *mut usize;
|
||||
let k = *at % RING;
|
||||
*((this as usize + F_RING + 2 * k) as *mut u16) = slot as u16;
|
||||
*at += 1;
|
||||
}
|
||||
|
||||
/// #9 Close: a failure is logged with the last methods called (`XCL_LIST_TRACE`)
|
||||
unsafe extern "system" fn close(this: *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) -> HRESULT = std::mem::transmute(pc_slot(pc, 9));
|
||||
let hr = f(pc);
|
||||
let n = *((this as usize + F_RING_AT) as *const usize);
|
||||
if hr < 0 && n > 0 {
|
||||
let first = n.saturating_sub(RING);
|
||||
let slots: Vec<String> = (first..n).map(|k| (*((this as usize + F_RING + 2 * (k % RING)) as *const u16)).to_string()).collect();
|
||||
crate::xlog_warn!("D3D12.X: console list Close → {:#x}; console slots called since Reset (last {}): {}", hr as u32, slots.len(), slots.join(" "));
|
||||
}
|
||||
// a new recording starts at Reset
|
||||
*((this as usize + F_RING_AT) as *mut usize) = 0;
|
||||
hr
|
||||
}
|
||||
|
||||
/// The console object for the PC list `pc` (adopted; one reference moves to it).
|
||||
pub unsafe fn wrap(pc: *mut c_void) -> *mut c_void {
|
||||
if pc.is_null() {
|
||||
return pc;
|
||||
}
|
||||
let layout = std::alloc::Layout::from_size_align(OBJECT_BYTES, 64).unwrap();
|
||||
let o = std::alloc::alloc_zeroed(layout);
|
||||
if o.is_null() {
|
||||
return pc;
|
||||
}
|
||||
*(o as *mut usize) = vtable();
|
||||
let room = o as usize + ROOM;
|
||||
for f in [F_WRITE, F_DISPATCH_END, F_END] {
|
||||
*(o.add(f) as *mut usize) = room;
|
||||
}
|
||||
*(o.add(F_BACKING) as *mut usize) = pc as usize;
|
||||
o as *mut c_void
|
||||
}
|
||||
|
||||
/// The PC list behind a console list object (None: not one).
|
||||
pub fn backing(list: *mut c_void) -> Option<*mut c_void> {
|
||||
if list.is_null() || !crate::gpu::shader::readable(list as usize, 8) {
|
||||
return None;
|
||||
}
|
||||
unsafe { (*(list as *const usize) == vtable()).then(|| *((list as usize + F_BACKING) as *const *mut c_void)) }
|
||||
}
|
||||
|
||||
unsafe fn pc_slot(pc: *mut c_void, slot: usize) -> usize {
|
||||
*(*(pc as *const *const usize)).add(slot)
|
||||
}
|
||||
|
||||
/// QueryInterface: the PC list answers; where it hands out itself, the console object goes out.
|
||||
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));
|
||||
let hr = f(pc, riid, ppv);
|
||||
if hr >= 0 && !ppv.is_null() && *ppv == pc {
|
||||
*ppv = this;
|
||||
}
|
||||
hr
|
||||
}
|
||||
|
||||
/// Release: the console object goes with the PC list's last reference.
|
||||
unsafe extern "system" fn release(this: *mut c_void) -> u32 {
|
||||
let pc = *((this as usize + F_BACKING) as *const *mut c_void);
|
||||
let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(pc, 2));
|
||||
let n = f(pc);
|
||||
if n == 0 {
|
||||
super::bind::forget(pc);
|
||||
std::alloc::dealloc(this as *mut u8, std::alloc::Layout::from_size_align(OBJECT_BYTES, 64).unwrap());
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A stand-in PC object: slot 5 returns `this`, slots 0 / 2 count.
|
||||
#[repr(C)]
|
||||
struct Fake {
|
||||
vt: *const usize,
|
||||
refs: u32,
|
||||
}
|
||||
|
||||
unsafe extern "system" fn fake_qi(this: *mut c_void, _riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
|
||||
(*(this as *mut Fake)).refs += 1;
|
||||
*ppv = this;
|
||||
0
|
||||
}
|
||||
unsafe extern "system" fn fake_release(this: *mut c_void) -> u32 {
|
||||
(*(this as *mut Fake)).refs -= 1;
|
||||
(*(this as *mut Fake)).refs
|
||||
}
|
||||
unsafe extern "system" fn fake_this(this: *mut c_void, a: u64, b: u64, c: u64, d: u64) -> u64 {
|
||||
this as u64 + a + 10 * b + 100 * c + 1000 * d
|
||||
}
|
||||
|
||||
/// The SDK's inline writers check `write < end` (or `write + n <= end`): never room here.
|
||||
#[test]
|
||||
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[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 }));
|
||||
unsafe {
|
||||
let o = wrap(fake as *mut c_void);
|
||||
assert_eq!(backing(o), Some(fake as *mut c_void));
|
||||
assert_eq!(backing(fake as *mut c_void), None);
|
||||
let (w, e) = (*((o as usize + F_WRITE) as *const usize), *((o as usize + F_END) as *const usize));
|
||||
assert!(w >= e && *((o as usize + F_DISPATCH_END) as *const usize) == w);
|
||||
let slot = |i: usize| *(*(o as *const *const usize)).add(i);
|
||||
// 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
|
||||
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 r: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(slot(2));
|
||||
assert_eq!(r(o), 1);
|
||||
assert_eq!(r(o), 0); // the object is freed with it
|
||||
drop(Box::from_raw(fake));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user