Skip to content
Closed
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
1 change: 1 addition & 0 deletions THIRD_PARTY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ carry a note in their header about its origin and the date of changes (GPL-3.0
| [AMD Machine-Readable GPU ISA](https://gpuopen.com/machine-readable-isa/) | MIT | `crates/xcl/src/gpu/rdna2_spec.rs` (generated by `scripts/gen_rdna2.py`) | encoding and instruction tables |
| [AMD addrlib](https://gitlab.freedesktop.org/mesa/mesa/-/tree/main/src/amd/addrlib) (Mesa) | MIT | `crates/xcl/src/gpu/tiling_tables.rs` (generated by `scripts/gen_tiling.py` from `gfx10SwizzlePattern.h`); GFX10 mip chain / mip tail layout in `gpu/tiling.rs` (after `Gfx10Lib::ComputeSurfaceInfoMacroTiled`) | swizzle tables; layout logic ported with annotation |
| [VIctory](https://github.com/Marvisak/VIctory) | GPL-3.0 | `crates/xcl/src/hle/bcpack/`: port of its `victory-formats/src/bcpack.rs`, and `tables.rs` generated by `scripts/gen_bcpack_victory_tables.py` from its `bcpack-tables.bin` (the format's constant tables; its 128 rANS models are those of Microsoft's [silicon-rans](https://github.com/microsoft/silicon-rans) sample, MIT) | port to Rust; tables |
| [Vice-Tay](https://github.com/TaynanGT/Vice-Tay) | GPL-3.0-or-later | no code; the mechanism of `b06fdd5` (a submission whose bounded wait timed out stays pending until its fence has passed, and is not reset or reused before) in `crates/xcl/src/hle/d3d12x/sparse.rs` (`hold_pending`), implemented independently | mechanism, reimplemented |
| [LLVM](https://github.com/llvm/llvm-project) | Apache-2.0 WITH LLVM-exception | `tests/data/llvm-amdgpu/*` (test data, not part of the program); GFX10 buffer format values (`UfmtSymbolicGFX10`) in `gpu/recomp/emit.rs` | test vectors; hardware facts |
| [WinDurango](https://github.com/WinDurango/WinDurango) | LGPL-3.0 | no code; d3d12_x.dll export numbers (facts) in `crates/xcl/data/stubdb.toml` | reference only |
| [libHttpClient](https://github.com/microsoft/libHttpClient) | MIT | no code; XTaskQueue/XAsync contract | specification |
Expand Down
235 changes: 226 additions & 9 deletions crates/xcl/src/hle/d3d12x/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ const STAGING: usize = 64 << 20;
const RING_ALIGN: usize = 64;
/// number of in-flight upload command allocators / lists
const UPLOAD_SLOTS: usize = 16;

/// How long a wait for the sparse queue goes on before it gives up: 5 s (tests set less).
fn wait_ms() -> u32 {
#[cfg(test)]
if let Some(ms) = tests::WAIT_MS.with(|w| w.get()) {
return ms;
}
5000
}
/// bytes of the dedicated pre-zeroed buffer for tile/hole clears (1 MiB)
const ZERO_BUF: usize = 1 << 20;
/// bytes of the GPU→CPU readback staging buffer
Expand Down Expand Up @@ -258,6 +267,9 @@ struct State {
rb_alloc: ID3D12CommandAllocator,
rb_list: ID3D12GraphicsCommandList,
rb_last_fence: u64,
/// allocators and lists whose submission (the fence value with them) a bounded wait gave up
/// on, kept until the queue has passed it (`hold_pending`)
held_lists: Vec<(u64, ID3D12CommandAllocator, ID3D12GraphicsCommandList)>,
/// the fence value each title queue last waited for
waited: FxHashMap<usize, u64>,
/// `mapped` as sorted (start, end) runs (None: to be made again)
Expand Down Expand Up @@ -572,6 +584,7 @@ pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> {
rb_alloc,
rb_list,
rb_last_fence: 0,
held_lists: Vec::new(),
waited: FxHashMap::default(),
runs: None,
scratch_runs: Vec::new(),
Expand Down Expand Up @@ -829,20 +842,71 @@ impl State {
let _ = self.queue.Signal(&self.fence, self.value);
}

/// Waits at most `wait_ms()` for the queue to reach `target`; whether it has.
#[inline]
unsafe fn wait_for(&self, target: u64) {
unsafe fn wait_for(&self, target: u64) -> bool {
if target == 0 || self.fence.GetCompletedValue() >= target {
return;
return true;
}
use windows::Win32::Foundation::WAIT_OBJECT_0;
let _ = self.fence.SetEventOnCompletion(target, self.event);
windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000);
if self.fence.GetCompletedValue() < target {
crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue());
let ms = wait_ms();
let start = std::time::Instant::now();
// The event is shared and auto-reset: a wake can be left over from an earlier wait
// that gave up (its value was reached later). So the fence is checked after every wake,
// and the wait goes on against the same deadline until `target` is reached.
loop {
let left = ms.saturating_sub(start.elapsed().as_millis().min(u32::MAX as u128) as u32);
let woke = windows::Win32::System::Threading::WaitForSingleObject(self.event, left) == WAIT_OBJECT_0;
if self.fence.GetCompletedValue() >= target {
return true;
}
if !woke || left == 0 {
break;
}
}
crate::xlog_warn!("sparse: the queue has not reached fence value {target} after {:.3} s (at {})", start.elapsed().as_secs_f64(), self.fence.GetCompletedValue());
false
}

/// `alloc` and `list`, last submitted at fence value `fv`, which a bounded wait gave up on:
/// the GPU may still execute that submission, and resetting them then is not allowed. They go
/// to `held_lists` until the queue has passed `fv` (`reclaim_ring`), and a new pair takes
/// their place. Whether it did: when no new pair can be made, this waits for `fv` without a
/// bound instead. (After Vice-Tay b06fdd5, where a timed-out submission stays pending until
/// its fence has passed.)
unsafe fn hold_pending(&mut self, fv: u64, alloc: &mut ID3D12CommandAllocator, list: &mut ID3D12GraphicsCommandList) -> bool {
let made = (|| -> windows::core::Result<(ID3D12CommandAllocator, ID3D12GraphicsCommandList)> {
let a: ID3D12CommandAllocator = self.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
let l: ID3D12GraphicsCommandList = self.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &a, None)?;
l.Close()?;
Ok((a, l))
})();
match made {
Ok((a, l)) => {
let _ = l.SetName(windows::core::w!("xcl sparse list (in place of one still in flight)"));
self.held_lists.push((fv, std::mem::replace(alloc, a), std::mem::replace(list, l)));
static N: AtomicU64 = AtomicU64::new(0);
let n = N.fetch_add(1, Ordering::Relaxed) + 1;
if n.is_power_of_two() {
crate::xlog_warn!("sparse: {n} command lists still in flight after the wait were held, not reset ({} held now)", self.held_lists.len());
}
true
}
Err(e) => {
crate::xlog_warn!("sparse: no new command list in place of one still in flight ({e}): waiting for fence value {fv}");
while !self.wait_for(fv) {}
false
}
}
}

#[inline]
unsafe fn reclaim_ring(&mut self) {
if !self.held_lists.is_empty() {
let completed = self.fence.GetCompletedValue();
self.held_lists.retain(|h| h.0 > completed);
}
if self.inflight.is_empty() {
return;
}
Expand All @@ -858,13 +922,20 @@ impl State {
}

/// Acquire the next upload command slot, waiting only if that slot's previous submission is
/// still executing on the GPU, then reset its allocator and list.
/// still executing on the GPU, then reset its allocator and list (a pair the wait gave up on
/// is held and replaced: `hold_pending`).
unsafe fn begin_slot(&mut self) -> usize {
let idx = self.next_slot;
self.next_slot = (self.next_slot + 1) % self.slots.len();
let fv = self.slots[idx].fence_val;
if fv > 0 && self.fence.GetCompletedValue() < fv {
self.wait_for(fv);
if !self.wait_for(fv) {
let (mut alloc, mut list) = (self.slots[idx].alloc.clone(), self.slots[idx].list.clone());
if self.hold_pending(fv, &mut alloc, &mut list) {
let slot = &mut self.slots[idx];
(slot.alloc, slot.list, slot.fence_val) = (alloc, list, 0);
}
}
self.reclaim_ring();
}
let slot = &self.slots[idx];
Expand Down Expand Up @@ -1037,8 +1108,22 @@ impl State {
}
s.signal();
s.rb_last_fence = s.value;
s.wait_for(s.value);
let reached = s.wait_for(s.value);
s.reclaim_ring();
if !reached {
// The copies into the readback buffer have not run: it still holds an earlier
// readback, of other addresses. The CPU view keeps its bytes and `sent` its
// hashes.
static N: AtomicU64 = AtomicU64::new(0);
let n = N.fetch_add(1, Ordering::Relaxed) + 1;
if n.is_power_of_two() {
let bytes: usize = pending.iter().map(|r| r.2).sum();
crate::xlog_warn!("sparse: {n} readbacks not done after the wait were not copied ({bytes} bytes of the CPU view left as they were this time)");
}
pending.clear();
*used = 0;
return;
}
}
for &(dst, off, len) in pending.iter() {
// copy only committed (non-hole) bytes
Expand Down Expand Up @@ -1082,7 +1167,13 @@ impl State {
let to_win_end = (b + crate::gpu::uma::WINDOW) - cur;
let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end);
if !open {
self.wait_for(self.rb_last_fence);
let fv = self.rb_last_fence;
if !self.wait_for(fv) {
let (mut alloc, mut list) = (self.rb_alloc.clone(), self.rb_list.clone());
if self.hold_pending(fv, &mut alloc, &mut list) {
(self.rb_alloc, self.rb_list) = (alloc, list);
}
}
let _ = self.rb_alloc.Reset();
let _ = self.rb_list.Reset(&self.rb_alloc, None);
open = true;
Expand Down Expand Up @@ -1733,6 +1824,11 @@ fn forget_in(s: &mut State, res: usize) {
mod tests {
use super::*;

thread_local! {
/// `wait_ms` on this test's thread (None: the runtime's 5 s)
pub(super) static WAIT_MS: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
}

/// `queue()` answers while the state's lock is held: a resource's last `Release` asks for
/// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be
/// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`).
Expand Down Expand Up @@ -1863,6 +1959,7 @@ mod tests {
rb_alloc,
rb_list,
rb_last_fence: 0,
held_lists: Vec::new(),
waited: FxHashMap::default(),
runs: None,
scratch_runs: Vec::new(),
Expand Down Expand Up @@ -2071,6 +2168,7 @@ mod tests {
rb_alloc,
rb_list,
rb_last_fence: 0,
held_lists: Vec::new(),
waited: FxHashMap::default(),
runs: None,
scratch_runs: Vec::new(),
Expand Down Expand Up @@ -2168,6 +2266,7 @@ mod tests {
rb_alloc,
rb_list,
rb_last_fence: 0,
held_lists: Vec::new(),
waited: FxHashMap::default(),
runs: None,
scratch_runs: Vec::new(),
Expand Down Expand Up @@ -2293,6 +2392,7 @@ mod tests {
rb_alloc,
rb_list,
rb_last_fence: 0,
held_lists: Vec::new(),
waited: FxHashMap::default(),
runs: None,
scratch_runs: Vec::new(),
Expand Down Expand Up @@ -2336,6 +2436,123 @@ mod tests {
}
}

/// An upload slot whose submission the queue has not finished when the bounded wait gives up
/// is not reset (the GPU may still execute it): its allocator and list are held until the
/// queue has passed that submission, and the slot goes on with a new pair.
#[test]
fn a_slot_still_in_flight_after_the_wait_is_held_not_reset() {
use windows_sys::Win32::System::Memory::MEM_RELEASE;

unsafe {
let (base, mut s) = test_state_with_reserved(1);
let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("allocator");
let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list");
list.Close().expect("list close");
s.slots.push(UploadSlot { alloc, list, fence_val: 0 });

let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence");
let unblock = SignalOnDrop(gate.clone(), 1);
s.queue.Wait(&gate, 1).expect("gate sparse queue");

// a submission the queue cannot reach while `gate` holds it
let idx = s.begin_slot();
s.submit_slot(idx);
let first = s.slots[idx].alloc.as_raw();
// the one slot comes round again, and its wait gives up
WAIT_MS.with(|w| w.set(Some(20)));
let again = s.begin_slot();
WAIT_MS.with(|w| w.set(None));
assert_eq!(again, idx);
assert_ne!(s.slots[idx].alloc.as_raw(), first, "an allocator the GPU may still execute was reset for reuse");
assert_eq!(s.held_lists.len(), 1);
assert_eq!(s.held_lists[0].1.as_raw(), first);
s.submit_slot(again);

gate.Signal(1).expect("release sparse queue");
assert!(s.wait_for(s.value));
s.reclaim_ring();
assert!(s.held_lists.is_empty(), "a held pair goes once the queue has passed its submission");
drop(unblock);
drop(s);
assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
}
}

/// A wake left on the shared event by an earlier wait that gave up does not end the next
/// wait: it goes on until its own value is reached, within the same bound.
#[test]
fn a_stale_wake_does_not_end_the_next_wait() {
use windows_sys::Win32::System::Memory::MEM_RELEASE;

unsafe {
let (base, mut s) = test_state_with_reserved(1);
s.wait_for(s.value);
let (old, new) = (s.value + 1, s.value + 2);
s.value = new;
// an earlier wait registered `old` and gave up; `old` is reached afterwards
s.fence.SetEventOnCompletion(old, s.event).expect("register the earlier wait");
s.fence.Signal(old).expect("reach the earlier value");
let fence = s.fence.clone();
let later = std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_millis(20));
fence.Signal(new).expect("reach the new value");
});
WAIT_MS.with(|w| w.set(Some(2000)));
let t = std::time::Instant::now();
let reached = s.wait_for(new);
WAIT_MS.with(|w| w.set(None));
let waited = t.elapsed();
later.join().expect("signalling thread");
assert!(reached, "the wait ended on a stale wake after {waited:?} (fence at {})", s.fence.GetCompletedValue());
assert!(waited >= std::time::Duration::from_millis(10), "the wait ended before the value was signalled ({waited:?})");
drop(s);
assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
}
}

/// A readback whose wait gives up has not copied into the readback buffer yet: the buffer
/// still holds an earlier readback, of other addresses, which must not land in the CPU view.
#[test]
fn a_readback_the_wait_gave_up_on_leaves_the_cpu_view_as_it_was() {
use windows_sys::Win32::System::Memory::MEM_RELEASE;

unsafe {
let (base, mut s) = test_state_with_reserved(1);
assert!(!VirtualAlloc(base as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null());
s.commit_range(base, PAGE);
let alloc: ID3D12CommandAllocator = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("allocator");
let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).expect("list");
list.Close().expect("list close");
s.slots.push(UploadSlot { alloc, list, fence_val: 0 });
// what the GPU holds for the page
std::ptr::write_bytes(base as *mut u8, 0x3C, PAGE);
s.upload_dirty(&[(base, PAGE)]);
assert!(s.wait_for(s.value));
std::ptr::write_bytes(base as *mut u8, 0xAA, PAGE);
// what an earlier readback left in the buffer
let (_, p) = s.readback_buf().expect("readback buffer");
std::ptr::write_bytes(p, 0xBB, PAGE);

let gate: ID3D12Fence = s.dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).expect("gate fence");
let unblock = SignalOnDrop(gate.clone(), 1);
s.queue.Wait(&gate, 1).expect("gate sparse queue");
WAIT_MS.with(|w| w.set(Some(20)));
s.readback_ranges(&[(base, PAGE)]);
WAIT_MS.with(|w| w.set(None));
let view = std::slice::from_raw_parts(base as *const u8, PAGE);
assert!(view.iter().all(|&b| b == 0xAA), "bytes of an earlier readback were copied into the CPU view");

gate.Signal(1).expect("release sparse queue");
assert!(s.wait_for(s.value));
// the same readback again, once the queue can run it, brings the GPU's bytes
s.readback_ranges(&[(base, PAGE)]);
assert!(view.iter().all(|&b| b == 0x3C), "a readback after the queue was released did not copy the GPU's bytes");
drop(unblock);
drop(s);
assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0);
}
}

/// `flush_parked` must keep unmapped pool tiles quarantined until every active title queue has
/// finished its prior work, even after `s.queue` itself finishes unmapping.
#[test]
Expand Down
Loading