Skip to content
Open
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
86 changes: 86 additions & 0 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5729,6 +5729,92 @@ fn gpu_direct_compute_waves_take_consecutive_threads_of_2d_and_3d_groups() {
}
}

/// A 2-D group takes the same course through `pso::direct_compute` (the route #3189 restores) as
/// through the HLSL path (`pso::console_dxil_noremap`) with this tree's compute entry
/// (nvidia-dev's branch-free thread limits, `kernel::compute_gate`), including when a DispatchX
/// thread limit cuts inside a group. The program is 8 x 8 groups. Each thread stores its console
/// thread index, its group (y << 16 | x), its wave's first thread and its lane at its own slot.
/// It runs as 2 x 2 groups, with no limit and with limits in X, in Y and in both. The wave64
/// program runs split on a GPU with only 32-lane waves. With a group barrier first, the direct
/// translator leaves the program to the HLSL path (`routed_to_hlsl`, as the runtime does when
/// the group is several hardware waves) and the HLSL form alone must give the table.
#[test]
fn gpu_2d_group_direct_route_matches_the_hlsl_path_under_thread_limits() {
use super::IO_THREAD_LIMIT;
if !gpu_ready() {
return;
}
const NONE: u32 = u32::MAX;
let program = |wave64: bool, barrier: bool| {
program_of(&[
if barrier { ins("S_BARRIER", "ENC_SOPP", &[], None) } else { Vec::new() },
ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 1), ("SRC1", 1), ("SRC2", V)], None),
ins("V_MAD_U32_U24", "ENC_VOP3", &[("VDST", 3), ("SRC0", V + 2), ("SRC1", 2), ("SRC2", V + 3)], None), // thread index
ins("V_MBCNT_LO_U32_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", 193), ("SRC1", 128)], None),
if wave64 { ins("V_MBCNT_HI_U32_B32", "ENC_VOP3", &[("VDST", 14), ("SRC0", 193), ("SRC1", V + 14)], None) } else { Vec::new() }, // lane
ins("V_READFIRSTLANE_B32", "ENC_VOP1", &[("VDST", 6), ("SRC0", V + 3)], None),
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 13), ("SRC0", 6)], None), // the wave's first thread
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 11), ("SRC0", V + 3)], None),
ins("V_LSHL_OR_B32", "ENC_VOP3", &[("VDST", 12), ("SRC0", 4), ("SRC1", 144), ("SRC2", 3)], None), // group y << 16 | x
ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 4), ("SRC1", 129), ("SRC2", 3)], None), // group y · 2 + x
ins("V_LSHL_ADD_U32", "ENC_VOP3", &[("VDST", 10), ("SRC0", V + 9), ("SRC1", 134), ("SRC2", V + 3)], None), // slot
ins("V_LSHLREV_B32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 132), ("VSRC1", 10)], None),
ins("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 7), ("SRC0", 0), ("VSRC1", 7)], None),
ins("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", 128)], None),
ins("GLOBAL_STORE_DWORDX4", "ENC_FLAT_GLBL", &[("ADDR", 7), ("DATA", 11), ("SADDR", 0x7D)], None),
])
};
// `cs_container` with the group ids in s3 (x) and s4 (y)
let container = |code: &[u8], wave64: bool| {
use crate::gpu::xbox::tests::{fssm, sample};
let mut f = fssm(code, &[(6, 0)]);
f[0x138..0x13C].copy_from_slice(&(3u32 << 1 | 1 << 7 | 1 << 8 | 2 << 11).to_le_bytes());
for (k, t) in [8u32, 8, 1].iter().enumerate() {
f[0x13C + 4 * k..0x140 + 4 * k].copy_from_slice(&t.to_le_bytes());
}
if !wave64 {
f[0xD4..0xD8].copy_from_slice(&0x20u32.to_le_bytes());
}
sample(5, &[f])
};
let base = 0x100usize;
for (wave64, barrier) in [(true, false), (false, false), (true, true), (false, true)] {
let lanes = if wave64 { 64 } else { 32 };
let split = wave64 && runner::split_wave64();
let blob = container(&program(wave64, barrier), wave64);
let what = format!("wave64 {wave64}, split {split}, barrier {barrier}");
let direct = match super::pso::direct_compute(&blob, 0, 1, split) {
Ok(c) => Some(c),
Err(e) if barrier && routed_to_hlsl(&e) => None,
Err(e) => panic!("{what}: direct: {e}"),
};
assert!(direct.as_ref().is_none_or(|c| c.dispatch_chain.is_none()), "{what}: a chain");
let hlsl = super::pso::console_dxil_noremap(&blob, split, 1).unwrap_or_else(|e| panic!("{what}: HLSL: {e}"));
for (lx, ly) in [(0u32, 0u32), (11, 0), (0, 13), (11, 13), (3, 5)] {
let mut io = vec![0u32; 128];
io[..3].copy_from_slice(&[base as u32, 8, 64]);
(io[IO_THREAD_LIMIT[0]], io[IO_THREAD_LIMIT[1]]) = (lx, ly);
let mem = vec![NONE; (base + 4 * 64 * 16) / 4];
let d = direct.as_ref().map(|c| runner::dispatch(&c.dxil, [2, 2, 1], &io, &mem).unwrap_or_else(|e| panic!("{what}: direct: {e}")));
let h = runner::dispatch(&hlsl, [2, 2, 1], &io, &mem).unwrap_or_else(|e| panic!("{what}: HLSL: {e}"));
for s in 0..4 * 64usize {
let (g, t) = (s / 64, s % 64);
let (gx, gy) = (g % 2, g / 2);
let (x, y) = ((gx * 8 + t % 8) as u32, (gy * 8 + t / 8) as u32);
let ran = (lx == 0 || x < lx) && (ly == 0 || y < ly);
// (the lowest thread of a console wave has its lowest x and y: it runs if any does)
let want = if ran { [t as u32, (gy << 16 | gx) as u32, (t - t % lanes) as u32, (t % lanes) as u32] } else { [NONE; 4] };
let at = (base + s * 16) / 4;
let where_ = format!("{what}, limit {lx} x {ly}: group ({gx}, {gy}) thread {t}");
if let Some(d) = &d {
assert_eq!(d[at..at + 4], want, "{where_}: direct (thread, group, wave's first thread, lane)");
}
assert_eq!(h[at..at + 4], want, "{where_}: HLSL (thread, group, wave's first thread, lane)");
}
}
}
}

/// A wave32 program in a 64-lane hardware wave (what VS / PS may get from the driver): the
/// two halves behave as separate waves – ballots, lane counts, readlane and mbcnt per half.
#[test]
Expand Down
41 changes: 41 additions & 0 deletions crates/xcl/src/hle/d3d12x/console_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,19 @@ struct QueueFences(HashMap<usize, (ID3D12Fence, u64)>);
unsafe impl Send for QueueFences {}

static HEAP_FENCES: Mutex<Option<QueueFences>> = Mutex::new(None);

/// A retired queue (`present::invalidate_queue_caches`): its signal fence goes, rather than stay
/// in `HEAP_FENCES` for every queue address the title ever used. (Retired ranges keep clones of
/// the fences they wait for.)
pub(super) fn forget_queue(id: super::present::QueueId) {
forget_queue_fence(id.raw());
}

fn forget_queue_fence(queue: usize) {
let gone = HEAP_FENCES.lock().unwrap().as_mut().and_then(|fences| fences.0.remove(&queue));
// (dropped outside the lock)
drop(gone);
}
static GLOBAL_RETIRED: AtomicBool = AtomicBool::new(false);
/// Serialises `drain_global_retired` across `fill_nulls` and `merge_release` so a concurrent
/// `slot()` cannot miss ranges popped from `GLOBAL.retired` before they reach `GLOBAL.free`.
Expand Down Expand Up @@ -1957,6 +1970,34 @@ mod tests {
assert!(made.is_ok(), "a shader-visible sampler heap of {}: {made:?}", d.NumDescriptors);
}

/// A retired queue's signal fence leaves `HEAP_FENCES`; another queue's stays.
#[test]
fn a_retired_queue_leaves_the_heap_fences() {
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;
let dev = unsafe {
let mut dev: Option<ID3D12Device> = None;
match CreateDXGIFactory1::<IDXGIFactory4>().and_then(|f| f.EnumWarpAdapter::<IDXGIAdapter>()) {
Ok(warp) if D3D12CreateDevice(&warp, D3D_FEATURE_LEVEL_11_0, &mut dev).is_ok() => dev.unwrap(),
_ => return crate::gpu::recomp::runner::skip_test("no WARP device"),
}
};
let (gone, kept) = (0x7E57_0000_C0A0usize, 0x7E57_0000_C0B0usize);
for key in [gone, kept] {
let fence: ID3D12Fence = unsafe { dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) }.unwrap();
HEAP_FENCES.lock().unwrap().get_or_insert_with(|| QueueFences(HashMap::new())).0.insert(key, (fence, 3));
}
let fence = HEAP_FENCES.lock().unwrap().as_ref().unwrap().0[&gone].0.clone();
forget_queue_fence(gone);
let g = HEAP_FENCES.lock().unwrap();
let fences = &g.as_ref().unwrap().0;
assert!(!fences.contains_key(&gone), "the retired queue's fence is gone");
assert_eq!(fences.get(&kept).map(|f| f.1), Some(3), "the other queue's stays");
drop(g);
assert_eq!(unsafe { fence.GetCompletedValue() }, 0, "a mark's clone of the fence still works");
HEAP_FENCES.lock().unwrap().as_mut().unwrap().0.remove(&kept);
}

/// Every descriptor of a range that is not handed out gets a null view, an SRV at even and a
/// UAV at odd indices (a range starting at an odd one too), a block at a time.
#[test]
Expand Down
41 changes: 41 additions & 0 deletions crates/xcl/src/hle/d3d12x/list_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11236,6 +11236,47 @@ mod tests {
}
}

/// A spare whose Reset fails does not stand in for a list reset while its last submit is on
/// the GPU (`reset_stand_in`), and stays among the list's spares (released with the list)
/// instead of being dropped. (A put-off dispatch's segment is reserved closed, without a
/// Reset: this is where a spare's Reset can fail.)
#[test]
fn a_spare_whose_reset_fails_stays_with_the_list_on_the_software_adapter() {
use super::super::title_list;
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0;
use windows::Win32::Graphics::Dxgi::*;

unsafe {
let mut dev: Option<ID3D12Device> = None;
let warp = CreateDXGIFactory1::<IDXGIFactory4>().and_then(|f| f.EnumWarpAdapter::<IDXGIAdapter>());
if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() {
crate::gpu::recomp::runner::skip_test("no WARP adapter");
return;
}
let dev = dev.unwrap();
let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE;
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap();
real::adopt(alloc.as_raw(), real::Kind::CommandAllocator);
let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap();
// still open, and of another type than the list's own allocator: its Reset fails
let direct: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let open: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &direct, None).unwrap();
let pc0 = raw.into_raw();
real::adopt(pc0, real::Kind::CommandList);
on_create(pc0, alloc.as_raw() as usize, 0, ty);
let wrap = title_list::wrap(pc0);
let spare = open.into_raw();
real::adopt(spare, real::Kind::CommandList);
title_list::put_spare(wrap, spare);

assert_eq!(reset_stand_in(wrap, pc0, alloc.as_raw() as usize, 0), None, "the spare whose Reset failed does not stand in");
assert_eq!(title_list::spares_for_test(wrap), vec![spare as usize], "it stays the list's");

let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2));
assert_eq!(rel_fn(wrap), 0);
}
}

/// Reproduces the exact intra-list fork-join pattern seen on retail compute queues:
/// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame)
/// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame)
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/present.rs
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,7 @@ pub(super) fn invalidate_queue_caches(id: QueueId) {
super::sparse::forget_queue(id);
super::title_textures::forget_queue(id);
super::vram::forget_queue(id);
super::console_heap::forget_queue(id);
}

fn retirement_worker() -> Option<&'static mpsc::Sender<()>> {
Expand Down
15 changes: 4 additions & 11 deletions crates/xcl/src/hle/d3d12x/pso_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4343,17 +4343,8 @@ pub fn submit(standin: usize, compute: bool, job: Job) {
submit_eager_with(standin, compute, job, 0, None, 0);
}

pub(super) fn submit_eager(
standin: usize,
compute: bool,
job: Job,
key: u64,
compute_key: Option<super::real::compute_build_key::ComputeBuildKey>,
) {
submit_eager_with(standin, compute, job, key, compute_key, 0);
}

/// `submit_eager`, with a compute pipeline's console program for the log (`record`; 0: not known).
/// `submit` with the shaders' key, a coalescing key and a compute pipeline's console program for
/// the log (`record`; 0: not known).
pub(super) fn submit_eager_with(
standin: usize,
compute: bool,
Expand Down Expand Up @@ -4383,6 +4374,7 @@ pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) {
submit_lazy_keyed_with(standin, compute, job, key, None, None, 0);
}

#[cfg(test)]
pub(super) fn submit_lazy_keyed(
standin: usize,
compute: bool,
Expand All @@ -4408,6 +4400,7 @@ pub(super) fn submit_lazy_keyed_with(
submit_as(standin, compute, job, None, false, key, compute_key, warm, record);
}

#[cfg(test)]
pub(super) fn submit_recipe_keyed(
standin: usize,
compute: bool,
Expand Down
12 changes: 11 additions & 1 deletion crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11529,13 +11529,17 @@ 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 (split title lists expand
// into all of their recorded PC segments in exact chronological order)
let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize);
// (the put-off dispatches' waits for their builds are not the submit's cost: the put-off line)
let mut deferred = std::time::Duration::ZERO;
for &l in title_lists {
if let Some(pc) = super::console_list::pc_list(l) {
mapped.push(pc);
} else {
// Deferred recording can wait for a pipeline. Keep that time solely in PipelineWait.
drop(preparation_stall);
let t = std::time::Instant::now();
super::list_x::record_deferred(l);
deferred += t.elapsed();
preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation);
if !super::title_list::push_segments(l, &mut mapped) {
mapped.push(l);
Expand All @@ -11547,11 +11551,15 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis
return;
}
// textures in title memory the CPU wrote since: uploaded again first
let t_refresh = std::time::Instant::now();
prepare_title_submission(this, title_lists);
let t_lists = std::time::Instant::now();
super::submit_cost::call(t_lists - t_refresh);
super::list_x::note_queue_for_lists(this as usize, &mapped);
super::gpu_profile::note_queue(this);
let t_exec = std::time::Instant::now();
super::submit_cost::call(t_exec - submit_t0);
// the lists made ready: mapped to their PC lists before the refresh, noted for the queue after it
super::submit_cost::lists((t_refresh - submit_t0).saturating_sub(deferred) + (t_exec - t_lists));
let plan = super::list_x::submission_plan(&mapped);
drop(preparation_stall);
let mut chunks = 0usize;
Expand Down Expand Up @@ -11592,12 +11600,14 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis
) {
return (false, None);
}
let t_after = std::time::Instant::now();
super::gpu_times::executed(this, lists);
chunks += 1;
submitted.extend_from_slice(lists);
super::list_x::copy_scratch_submitted(this, lists);
let effects = chunk.submit_effects(this);
super::list_x::note_submitted(this);
super::submit_cost::after(t_after.elapsed());
(true, effects)
})
});
Expand Down
8 changes: 7 additions & 1 deletion crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -990,6 +990,9 @@ mod tests {
let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE;
let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap();
let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap();
// (adopted as a title's list is: the split binds through the list's original
// SetPipelineState, `real::bind_pipeline_exact`)
super::super::adopt(list.as_raw(), super::super::Kind::CommandList);
let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize);
super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0);
let args = pso::chain_commands_buffer(&dev, 1).unwrap();
Expand All @@ -1000,7 +1003,10 @@ mod tests {
list_reset(raw_list);
let next_recording = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap();
assert!(!Arc::ptr_eq(&recorded, &next_recording));
list.Close().unwrap();
// (the list's own Close, not XCL's hook of a title list's)
type Close = unsafe extern "system" fn(*mut c_void) -> HRESULT;
let close: Close = std::mem::transmute(super::super::orig_fn(list.as_raw(), 9));
assert!(close(list.as_raw()) >= 0);
allocator_reset(allocator);
list_reset(raw_list);
forget(key);
Expand Down
1 change: 1 addition & 0 deletions crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ pub(super) unsafe fn graphics_stream_key(stream: &[u8], samplers: &[crate::gpu::
stream_key(stream, samplers, GRAPHICS_STREAM_CACHE_SCHEMA, 3, 0, mem_windows)
}

#[allow(dead_code)] // consumed by main's next stacked cache stage
pub(super) fn two_pass_cs_key(cs: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> u64 {
let mut h = Fnv64::new();
h.u32(TWO_PASS_CACHE_SCHEMA);
Expand Down
Loading
Loading