Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/xcl/src/hle/d3d12x/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ mod alloc_pool;
pub use alloc_pool::AllocatorSubmitStats;
mod barrier_groups;
mod build_queue;
#[cfg(test)]
mod submit_order_tests;
pub mod bind;
mod bvh_want;
mod capture;
Expand Down
293 changes: 293 additions & 0 deletions crates/xcl/src/hle/d3d12x/submit_order_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,293 @@
//! Submission order and the transitions XCL records: a harness for the cases of #3094 (a list
//! submitted in another order than it was recorded in, reset unsubmitted, submitted again).
//!
//! A recording is a stand-in PC list that keeps the words XCL's hooks send its `ResourceBarrier`
//! (`list_x::resource_barrier_x`, and the title's enhanced barriers through
//! `list_x::uav_barrier_x`). `Gpu` runs recordings in a submission order and reports each
//! transition whose before-state is not the one the texture is in at that point: what the debug
//! layer reports as 527 / 538. The debug layer itself is not used: it is one per process, and
//! turning it on would remove the devices of the tests running beside these
//! (`gpu::agility::enable_debug_layer`). The textures are WARP resources (`barrier_groups` reads
//! their descriptions); nothing runs on the GPU.
//!
//! The cases here hold on `main`; a case that does not comes with the change that makes it hold.
//! (One that does not: a texture whose first move is a legacy barrier is not tracked by
//! `barrier_groups` (`note_legacy_state` only follows tracked ones, #3489), so the cases here
//! start each texture with an enhanced barrier that names its layout.)

use std::collections::HashMap;
use std::ffi::c_void;
use std::sync::Mutex;

use windows::core::Interface;
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM;
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4};

const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
const BEGIN_ONLY: u32 = D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY.0 as u32;
/// ID3D12CommandList::GetType and ID3D12GraphicsCommandList::ResourceBarrier
const GET_TYPE: usize = 8;
const RESOURCE_BARRIER: usize = 26;
const UNORDERED_ACCESS: u32 = 0x8;
const RENDER_TARGET: u32 = 0x4;
const NON_PIXEL: u32 = 0x40;
const SAMPLED: u32 = 0x40 | 0x80;

/// A stand-in PC list. XCL calls a list's own functions through its original table
/// (`real::orig_fn`: the table whose address is one slot before the object's table); here that
/// table answers GetType and keeps what ResourceBarrier is given.
#[repr(C)]
struct Recording {
vt: *const usize,
ty: D3D12_COMMAND_LIST_TYPE,
words: Mutex<Vec<[u32; 8]>>,
/// slots of the tables called that the stand-in does not answer (`Drop` fails the test)
unexpected: Mutex<Vec<usize>>,
_tables: (Vec<usize>, Vec<usize>),
}

/// Every slot the stand-in does not answer (128 of each table: past DispatchMesh, 78, and the enhanced Barrier, 79): the call is kept and fails the test when the
/// recording is dropped, instead of a jump to address 0 that ends the whole test binary. (Not a
/// panic: it cannot unwind out of an `extern "system"` call; it would abort the binary too.)
unsafe extern "system" fn unexpected<const N: usize>(this: *mut c_void) -> usize {
(*(this as *const Recording)).unexpected.lock().unwrap().push(N);
0
}

macro_rules! unexpected_table {
($($n:literal)*) => { vec![$(unexpected::<$n> as usize),*] };
}

impl Drop for Recording {
fn drop(&mut self) {
let u = self.unexpected.get_mut().unwrap();
if !u.is_empty() && !std::thread::panicking() {
panic!("the stand-in list's slots {u:?} were called; it answers only GetType ({GET_TYPE}) and ResourceBarrier ({RESOURCE_BARRIER})");
}
}
}

unsafe extern "system" fn get_type(this: *mut c_void) -> D3D12_COMMAND_LIST_TYPE {
(*(this as *const Recording)).ty
}

unsafe extern "system" fn resource_barrier(this: *mut c_void, n: u32, b: *const [u32; 8]) {
(*(this as *const Recording)).words.lock().unwrap().extend_from_slice(std::slice::from_raw_parts(b, n as usize));
}

impl Recording {
fn new(ty: D3D12_COMMAND_LIST_TYPE) -> Box<Recording> {
let mut orig = unexpected_table!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127);
orig[GET_TYPE] = get_type as usize;
orig[RESOURCE_BARRIER] = resource_barrier as usize;
// (slot 0 is the original table's address; the object's own table is past it)
let mut ext = vec![0usize];
ext.extend(unexpected_table!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127));
ext[0] = orig.as_ptr() as usize;
let vt = unsafe { ext.as_ptr().add(1) };
Box::new(Recording { vt, ty, words: Mutex::new(Vec::new()), unexpected: Mutex::new(Vec::new()), _tables: (orig, ext) })
}

fn this(&self) -> *mut c_void {
self as *const Recording as *mut c_void
}

/// The title's ResourceBarrier: one transition of every subresource.
fn legacy(&self, t: &ID3D12Resource, before: u32, after: u32) {
let r = t.as_raw() as usize;
let b = [0, 0, r as u32, (r as u64 >> 32) as u32, ALL, before, after, 0];
unsafe { super::list_x::resource_barrier_x(self.this(), 1, &b) };
}

/// The title's enhanced barrier (list #146) of a whole texture between two layouts.
fn enhanced(&self, t: &ID3D12Resource, layout: (i32, i32), access: (i32, i32)) {
let tb = D3D12_TEXTURE_BARRIER {
SyncBefore: D3D12_BARRIER_SYNC_ALL,
SyncAfter: D3D12_BARRIER_SYNC_ALL,
AccessBefore: D3D12_BARRIER_ACCESS(access.0),
AccessAfter: D3D12_BARRIER_ACCESS(access.1),
LayoutBefore: D3D12_BARRIER_LAYOUT(layout.0),
LayoutAfter: D3D12_BARRIER_LAYOUT(layout.1),
pResource: unsafe { std::mem::transmute_copy(t) },
Subresources: D3D12_BARRIER_SUBRESOURCE_RANGE { IndexOrFirstMipLevel: ALL, ..Default::default() },
Flags: D3D12_TEXTURE_BARRIER_FLAG_NONE,
};
let g = D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 1, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: &tb } };
unsafe { super::list_x::uav_barrier_x(self.this(), 1, &g as *const D3D12_BARRIER_GROUP as *const c_void) };
}

fn transitions(&self) -> Vec<[u32; 8]> {
self.words.lock().unwrap().iter().filter(|w| w[0] == 0).copied().collect()
}
}

/// The textures' states as the GPU finds them, by subresource, as recordings run.
struct Gpu {
subresources: HashMap<usize, u32>,
state: HashMap<(usize, u32), u32>,
}

impl Gpu {
/// `textures`: (texture, its subresources, the state it was made in)
fn new(textures: &[(usize, u32, u32)]) -> Gpu {
let mut g = Gpu { subresources: HashMap::new(), state: HashMap::new() };
for &(r, n, s) in textures {
g.subresources.insert(r, n);
(0..n).for_each(|k| _ = g.state.insert((r, k), s));
}
g
}

/// `words` run: the transitions that start from a state their texture is not in.
fn run(&mut self, words: &[[u32; 8]]) -> Vec<String> {
let mut wrong = Vec::new();
for w in words.iter().filter(|w| w[0] == 0 && w[1] & BEGIN_ONLY == 0) {
let r = (w[2] as u64 | (w[3] as u64) << 32) as usize;
let Some(&n) = self.subresources.get(&r) else { continue };
let subs = if w[4] == ALL { 0..n } else { w[4]..w[4] + 1 };
for k in subs {
let now = self.state.insert((r, k), w[6]).unwrap_or(0);
if now != w[5] {
wrong.push(format!("{r:#x} subresource {k}: {:#x} -> {:#x} while it is in {now:#x}", w[5], w[6]));
}
}
}
wrong
}
}

/// A WARP device, or None (the test is skipped).
fn warp() -> Option<ID3D12Device> {
unsafe {
let factory: IDXGIFactory4 = CreateDXGIFactory1().ok()?;
let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?;
let mut dev: Option<ID3D12Device> = None;
D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_11_0, &mut dev).ok()?;
dev
}
}

/// A 64x64 texture of one level that can be a render target and take unordered access.
fn texture(dev: &ID3D12Device, state: u32) -> ID3D12Resource {
let d = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: 64,
Height: 64,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT_R8G8B8A8_UNORM,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
..Default::default()
};
let mut t: Option<ID3D12Resource> = None;
unsafe {
dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATES(state as i32), None, &mut t)
.expect("a WARP texture");
}
t.unwrap()
}

/// None when the test cannot run (no WARP device; `XCL_BARRIER_GROUPS=0`).
fn setup() -> Option<ID3D12Device> {
if !super::barrier_groups::enabled() {
crate::gpu::recomp::runner::skip_test("XCL_BARRIER_GROUPS=0: the title's enhanced barriers move no texture");
return None;
}
let dev = warp();
if dev.is_none() {
crate::gpu::recomp::runner::skip_test("no WARP device");
}
dev
}

// enhanced layouts and accesses (D3D12_BARRIER_LAYOUT / D3D12_BARRIER_ACCESS)
const UNDEFINED: i32 = -1;
const NO_ACCESS: i32 = i32::MIN;
const L_RT: i32 = 2;
const L_UAV: i32 = 3;
const L_SRV: i32 = 6;
const A_RT: i32 = 0x8;
const A_UAV: i32 = 0x10;
const A_SRV: i32 = 0x80;

/// The model reports a transition from a state the texture is not in, and only that one.
#[test]
fn the_gpu_model_reports_a_before_state_the_texture_is_not_in() {
let mut gpu = Gpu::new(&[(0xA0, 1, SAMPLED)]);
let w = |before: u32, after: u32| [0, 0, 0xA0, 0, ALL, before, after, 0];
assert!(gpu.run(&[w(SAMPLED, RENDER_TARGET), w(RENDER_TARGET, SAMPLED)]).is_empty());
let wrong = gpu.run(&[w(UNORDERED_ACCESS, RENDER_TARGET)]);
assert_eq!(wrong.len(), 1, "{wrong:?}");
// a split transition counts at its end, a UAV barrier moves nothing
let mut begin = w(RENDER_TARGET, SAMPLED);
begin[1] = BEGIN_ONLY;
assert!(gpu.run(&[begin, [2, 0, 0, 0, 0, 0, 0, 0], w(RENDER_TARGET, SAMPLED)]).is_empty());
}

/// Two lists submitted in the order they were recorded in: the second's move from the undefined
/// layout starts where the first left the texture, and the GPU finds every before-state.
#[test]
fn lists_submitted_in_their_recording_order_start_where_the_one_before_left_off() {
let Some(dev) = setup() else { return };
let t = texture(&dev, SAMPLED);
let r = t.as_raw() as usize;
let (a, b) = (Recording::new(D3D12_COMMAND_LIST_TYPE_DIRECT), Recording::new(D3D12_COMMAND_LIST_TYPE_DIRECT));
// (tracked from its first enhanced barrier on; a legacy one keeps it in step after that)
a.enhanced(&t, (L_SRV, L_RT), (A_SRV, A_RT));
a.legacy(&t, RENDER_TARGET, UNORDERED_ACCESS);
b.enhanced(&t, (UNDEFINED, L_RT), (NO_ACCESS, A_RT));
b.enhanced(&t, (L_RT, L_SRV), (A_RT, A_SRV));
assert_eq!(b.transitions().first().map(|w| (w[5], w[6])), Some((UNORDERED_ACCESS, RENDER_TARGET)), "{:x?}", b.transitions());
let mut gpu = Gpu::new(&[(r, 1, SAMPLED)]);
let wrong: Vec<String> = [&a, &b].iter().flat_map(|l| gpu.run(&l.transitions())).collect();
assert!(wrong.is_empty(), "{wrong:?}");
}

/// A list submitted twice in a row that leaves the texture where its move from the undefined
/// layout starts: the second run finds the same before-states.
#[test]
fn a_list_submitted_again_that_ends_where_it_starts_finds_its_states() {
let Some(dev) = setup() else { return };
let t = texture(&dev, SAMPLED);
let r = t.as_raw() as usize;
let (a, b) = (Recording::new(D3D12_COMMAND_LIST_TYPE_DIRECT), Recording::new(D3D12_COMMAND_LIST_TYPE_DIRECT));
a.enhanced(&t, (L_SRV, L_UAV), (A_SRV, A_UAV));
b.enhanced(&t, (UNDEFINED, L_RT), (NO_ACCESS, A_RT));
b.enhanced(&t, (L_RT, L_UAV), (A_RT, A_UAV));
let mut gpu = Gpu::new(&[(r, 1, SAMPLED)]);
let wrong: Vec<String> = [&a, &b, &b].iter().flat_map(|l| gpu.run(&l.transitions())).collect();
assert!(wrong.is_empty(), "{wrong:?}");
}

/// The same on COMPUTE lists, whose states have no pixel-shader part.
#[test]
fn compute_lists_submitted_in_their_recording_order_find_their_states() {
let Some(dev) = setup() else { return };
let t = texture(&dev, NON_PIXEL);
let r = t.as_raw() as usize;
let (a, b) = (Recording::new(D3D12_COMMAND_LIST_TYPE_COMPUTE), Recording::new(D3D12_COMMAND_LIST_TYPE_COMPUTE));
a.enhanced(&t, (L_SRV, L_UAV), (A_SRV, A_UAV));
a.legacy(&t, UNORDERED_ACCESS, NON_PIXEL);
b.enhanced(&t, (UNDEFINED, L_UAV), (NO_ACCESS, A_UAV));
b.enhanced(&t, (L_UAV, L_SRV), (A_UAV, A_SRV));
assert_eq!(b.transitions().first().map(|w| (w[5], w[6])), Some((NON_PIXEL, UNORDERED_ACCESS)), "{:x?}", b.transitions());
assert!(b.transitions().iter().all(|w| (w[5] | w[6]) & 0x80 == 0), "no pixel-shader state on a compute list: {:x?}", b.transitions());
let mut gpu = Gpu::new(&[(r, 1, NON_PIXEL)]);
let wrong: Vec<String> = [&a, &b].iter().flat_map(|l| gpu.run(&l.transitions())).collect();
assert!(wrong.is_empty(), "{wrong:?}");
}

/// A slot the stand-in does not answer is recorded, not a jump to address 0 that ends the test binary.
#[test]
fn an_unanswered_slot_is_recorded_not_a_crash() {
let r = Recording::new(D3D12_COMMAND_LIST_TYPE_DIRECT);
unsafe {
let orig = *(r.vt.sub(1)) as *const usize;
let f: unsafe extern "system" fn(*mut c_void) -> usize = std::mem::transmute(*orig.add(12));
assert_eq!(f(r.this()), 0);
}
assert_eq!(std::mem::take(&mut *r.unexpected.lock().unwrap()), [12]);
}
Loading