Skip to content
Merged
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
12 changes: 12 additions & 0 deletions crates/victory-gpu/src/bindless.rs
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,18 @@ pub(crate) fn refresh_slot(
}
}

/// Each copy the heap views for unordered access, with the range of it
/// its views reach (address, bytes): what the heap's shaders may write with
/// no list declaring it.
pub(crate) fn written_ranges(viewed: &Viewed, mut each: impl FnMut(&Arc<Shadow>, usize, usize)) {
let inner = viewed.inner.lock().unwrap_or_else(|e| e.into_inner());
for (shadow, address, len, uav, _) in &inner.hulls {
if *uav {
each(shadow, *address as usize, *len as usize);
}
}
}

/// Heap UAV ranges that may need to refresh a widened SRV after a later
/// buffer barrier, added to `out` (the caller's buffer, kept from barrier to
/// barrier: the world's heaps have tens of thousands). Computed heap indices
Expand Down
1 change: 1 addition & 0 deletions crates/victory-gpu/src/draw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3175,6 +3175,7 @@ const QUAD_STRIP: u32 = 20;

#[cfg(test)]
mod tests {
mod flight;
mod tracked_rows;

use super::*;
Expand Down
106 changes: 106 additions & 0 deletions crates/victory-gpu/src/draw/tests/flight.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
//! A Flight-1 flight (`VICTORY_FLIGHT1`, `crate::host::flight`) lands
//! what its shaders wrote with no list declaring it, whatever the title
//! wrote into the same pages while it was in the air.

use std::sync::Arc;

use super::*;
use crate::host::{Gate, ModeGuard};

/// A raw view of a buffer's 256 bytes.
const RAW_256: [u32; 10] = [39, 1, 0, 0, 64, 0, 0, 0, 1, 0];

/// A shader writes a dword through a heap's unordered view (marked, and
/// declared by no list: the bindless path), and while its flight is in the
/// air the title writes another dword of the same 64 KiB page from the CPU,
/// as its render thread goes on writing a frame's data with Flight-1: both
/// writes are in title memory once the flight has landed, as on the
/// console, where memory is written byte by byte.
#[test]
fn a_heap_view_write_and_a_title_write_on_one_page_during_a_flight_both_land() {
let Some(host) = crate::host::host() else {
return;
};
const LIVE_MARKED_WRITE: &str = r#"
RWByteAddressBuffer dst : register(u0);
RWByteAddressBuffer writes : register(u1);
cbuffer c : register(b0) { uint byte_offset; uint value; uint mark_word_bytes; uint mark_mask; }
[numthreads(1, 1, 1)]
void main() {
dst.Store(byte_offset, value);
writes.Store(mark_word_bytes, mark_mask);
}
"#;
let (root, pso) = compile_cs(
LIVE_MARKED_WRITE,
&[
Param::Table(&[uav(0, 1)]),
Param::Uav { register: 1 },
Param::Constants {
register: 0,
count: 4,
},
],
);
let (_, title_heap, heap_host) = view_heap(8);
let p = crate::watch::tests::pool(1);
// SAFETY: a committed write-watched page of ours.
unsafe {
(p as *mut u32).write_volatile(0x1111_1111);
((p + 16) as *mut u32).write_volatile(0x2222_2222);
}
let buf = buffer_at_address(p as u64, crate::watch::PAGE as u64);
let copy = crate::shadow::find(p as u64, crate::watch::PAGE as u64).expect("the page's copy");
let Some((bit, _)) = copy.mark_entry(p as u64) else {
crate::shadow::unregister(buf as usize, p as u64);
return; // no write marks on this host
};
crate::descriptor::create_uav(
std::ptr::null(),
buf,
std::ptr::null(),
&RAW_256,
title_heap.start,
);
let _ = heap_host.mirror(0, title_heap.start, true);
let _mode = ModeGuard::new(true, false);
let mut gate = Gate::hold(host);
let list = Arc::new(host.new_list().unwrap());
// The heap's views brought up to date (its unordered views included),
// as for a list whose shaders index the heap: no write declared.
list.defer_heap(&heap_host.viewed);
let writes = crate::shadow::view_writes(false).expect("the write marks bitmap");
let constants = [0u32, 0xDEAD_BEEF, (bit >> 5) * 4, 1 << (bit & 31)];
// SAFETY: an open list, live objects and descriptors in our heap.
unsafe {
list.list
.SetDescriptorHeaps(&[Some(heap_host.heap.clone())]);
list.list.SetComputeRootSignature(&root);
list.list.SetComputeRootDescriptorTable(0, heap_host.gpu(0));
list.list.SetComputeRootUnorderedAccessView(1, writes);
list.list
.SetComputeRoot32BitConstants(2, 4, constants.as_ptr().cast(), 0);
list.list.SetPipelineState(&pso);
list.list.Dispatch(1, 1, 1);
}
list.close();
host.execute_flight1(vec![list], vec![]);
// The title's render thread goes on, and writes the page meanwhile.
// SAFETY: a dword of our page.
unsafe { ((p + 16) as *mut u32).write_volatile(0xCAFE_BABE) };
gate.open();
host.finish_flight_now();
// SAFETY: dwords of our page.
let (gpu, cpu) = unsafe {
(
(p as *const u32).read_volatile(),
((p + 16) as *const u32).read_volatile(),
)
};
assert_eq!(cpu, 0xCAFE_BABE, "the title's write");
assert_eq!(
gpu, 0xDEAD_BEEF,
"the shader's write, on the page the title wrote during the flight"
);
crate::shadow::unregister(buf as usize, p as u64);
}
2 changes: 2 additions & 0 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
//! overlap them with per-submission fences once more than clears run.

mod flight;
#[cfg(test)]
pub(crate) use flight::{Gate, ModeGuard};
pub(crate) use flight::{async_submit_enabled, flight1_enabled};

use std::sync::atomic::{AtomicU32, Ordering};
Expand Down
120 changes: 119 additions & 1 deletion crates/victory-gpu/src/host/flight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
use std::sync::Arc;
use std::sync::atomic::Ordering;

use super::{Batch, Holding, Host, HostList, Mark};
use super::{Batch, Holding, Host, HostList, Mark, Step};
use crate::object::This;

/// Whether Wait-Before-Prep Flight-1 overlap is enabled (`VICTORY_FLIGHT1=1`,
Expand Down Expand Up @@ -124,6 +124,113 @@ impl Drop for ModeGuard {
}
}

/// Before a flight is given to the host GPU: the pages its shaders may
/// write with no list declaring them are armed (`Shadow::arm_undeclared`),
/// the unordered views of its heaps (the bindless path) and every copy the
/// page tables of its title-memory programs name. Their writes are marked
/// and go back by the pages marked (`Shadow::copy_back_marked`), and a page
/// the title wrote since the copy took it, and that nothing saved, keeps
/// the title's bytes whole, the shaders' there dropped. Waited for, the
/// title's thread that submits cannot write meanwhile; a flight lets it go
/// on, and it writes a frame's data into pages the GPU writes too (on the
/// console both land, byte by byte). Armed, the first title write to such
/// a page saves its bytes from before, and the copy-back keeps both. The
/// copies armed, to disarm when it lands.
fn arm_undeclared(
segments: &[Arc<HostList>],
heaps: &[Arc<crate::bindless::Viewed>],
) -> Vec<Arc<crate::shadow::Shadow>> {
let mut armed: Vec<Arc<crate::shadow::Shadow>> = Vec::new();
let mut seen = std::collections::HashSet::new();
let mut arm = |copy: &Arc<crate::shadow::Shadow>, address: usize, len: usize| {
copy.arm_undeclared(address, len);
if seen.insert(Arc::as_ptr(copy) as usize) {
armed.push(copy.clone());
}
};
for heap in heaps {
crate::bindless::written_ranges(heap, &mut arm);
}
for list in segments {
for step in &list.deferred().copies {
if let &Step::Memory(key) = step {
crate::memory::copies(key, |copy| {
let (start, len) = copy.range();
arm(copy, start as usize, len as usize);
});
}
}
}
armed
}

/// Tests: the host queue waits on a fence of ours from [`Gate::hold`] to
/// [`Gate::open`] (or the drop): a flight given meanwhile stays in the air.
/// A watchdog opens it after 2 s: another test's submission behind the gate
/// holds the submission lock while it waits, and the thread that would open
/// it may be waiting for that lock.
#[cfg(test)]
pub(crate) struct Gate {
fence: GateFence,
opened: Arc<std::sync::atomic::AtomicBool>,
}

#[cfg(test)]
#[derive(Clone)]
struct GateFence(windows::Win32::Graphics::Direct3D12::ID3D12Fence);

// SAFETY: D3D12 fences are free-threaded.
#[cfg(test)]
unsafe impl Send for GateFence {}

#[cfg(test)]
impl GateFence {
fn open(&self, opened: &std::sync::atomic::AtomicBool) {
if !opened.swap(true, Ordering::AcqRel) {
// SAFETY: our fence.
unsafe { self.0.Signal(1) }.expect("the gate opens");
}
}
}

#[cfg(test)]
impl Gate {
pub(crate) fn hold(host: &Host) -> Gate {
// SAFETY: plain creation; our queue waits on our fence.
let fence = unsafe {
let fence: windows::Win32::Graphics::Direct3D12::ID3D12Fence = host
.device
.CreateFence(
0,
windows::Win32::Graphics::Direct3D12::D3D12_FENCE_FLAG_NONE,
)
.expect("a gate fence");
host.queue()
.Wait(&fence, 1)
.expect("the queue waits on the gate");
GateFence(fence)
};
let opened = Arc::new(std::sync::atomic::AtomicBool::new(false));
let (f, o) = (fence.clone(), opened.clone());
std::thread::spawn(move || {
std::thread::sleep(std::time::Duration::from_secs(2));
f.open(&o);
});
Gate { fence, opened }
}

pub(crate) fn open(&mut self) {
self.fence.open(&self.opened);
}
}

#[cfg(test)]
impl Drop for Gate {
fn drop(&mut self) {
self.fence.open(&self.opened);
}
}

/// Protected by `Host::flight` (leaf lock strictly below `HELD` and
/// `Host::submitted`, above only `Fence::waiters`).
#[derive(Default)]
Expand All @@ -147,6 +254,9 @@ pub(super) struct FlightState {
struct InFlight {
fence_value: u64,
segments: Vec<Arc<HostList>>,
/// Copies whose pages it armed for its shaders' undeclared writes
/// ([`arm_undeclared`]), disarmed once it has landed.
armed: Vec<Arc<crate::shadow::Shadow>>,
uploads: Option<crate::bindless::Uploads>,
batch: Batch,
heaps: Vec<Arc<crate::bindless::Viewed>>,
Expand Down Expand Up @@ -232,6 +342,9 @@ impl Host {
mark.arm(fence_value);
group.push(mark.list());
}
// Armed before the GPU may write: a title write from here on saves
// its page.
let armed = arm_undeclared(&segments, &prep.heaps);
let queue = self.queue();
let launched = std::time::Instant::now();
// SAFETY: closed lists; fence and events are ours.
Expand Down Expand Up @@ -267,6 +380,7 @@ impl Host {
let flight = InFlight {
fence_value,
segments,
armed,
uploads: prep.uploads,
batch: prep.batch,
heaps: prep.heaps,
Expand Down Expand Up @@ -427,6 +541,10 @@ impl Host {
);
}

// Its copy-back is done: what it armed is as anything else again.
for copy in &flight.armed {
copy.disarm_undeclared();
}
// Return the upload list to `bindless::LIST` and recycle host lists
// only after the GPU fence and post-GPU work have finished.
drop(flight.uploads);
Expand Down
10 changes: 10 additions & 0 deletions crates/victory-gpu/src/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,16 @@ impl Shared {
}
}

/// The copies the page table of view heap `key` names: what programs using
/// title memory with that heap bound may write, at addresses they compute
/// (`crate::host::flight` arms them for a flight).
#[cfg(windows)]
pub(crate) fn copies(key: usize, mut each: impl FnMut(&Arc<Shadow>)) {
for copy in &layout(key).copies {
each(copy);
}
}

/// The page table of view heap `key`, as the last submission using it
/// left it.
fn layout(key: usize) -> Arc<Layout> {
Expand Down
28 changes: 28 additions & 0 deletions crates/victory-gpu/src/shadow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,34 @@ impl Shadow {
list.mark_widened_write(self, address as usize, len as usize);
}

/// Arms the pages of `[address, address + len)` (tracked memory only)
/// for shaders that may write them through views no list declared (a
/// flight's heaps and title-memory programs, `crate::host::flight`): a
/// title write there before the copy-back saves the page's bytes from
/// before it, so that [`Shadow::copy_back_marked`] keeps both writers'
/// bytes, as for a declared marked write ([`Shadow::writing`]), instead
/// of the title's page whole.
pub(crate) fn arm_undeclared(&self, address: usize, len: usize) {
if let Some(t) = &self.tracked {
t.arm(address, address.saturating_add(len));
}
}

/// The flight that armed the copy ([`Shadow::arm_undeclared`]) has been
/// copied back: nothing stays armed or saved, unless a submitted list
/// still declares writes there (its own copy-back disarms it then).
pub(crate) fn disarm_undeclared(&self) {
if let Some(t) = &self.tracked
&& self
.pending
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty()
{
t.disarm();
}
}

/// At submission, after the range's refresh: a submitted list's shaders
/// write this range. Its bytes are kept to tell later what the GPU wrote:
/// per copy and submission, segments covering the ranges the submission
Expand Down