From e03f0181c6faba1905c2f3df1f73c79257388b65 Mon Sep 17 00:00:00 2001 From: Saurabh Suresh Date: Fri, 27 Nov 2026 20:00:01 +0400 Subject: [PATCH] fix(gpu): keep a flight's undeclared shader writes on pages the title writes meanwhile With VICTORY_FLIGHT1=1 the first indoor area after the opening renders much darker (#447: median luma 13/255 against 39 without the switch). Shaders that write through a heap's unordered views (the bindless path) or through title-memory programs declare nothing. Their writes are marked in the write-mark bitmap and copied back by the pages marked (copy_back_marked), but those pages were never armed. So a title write to one before the copy-back saved nothing, and the copy-back kept the title's page whole and dropped the shader's bytes there. Waited for, the submitting thread cannot write meanwhile. A flight lets it go on, and it writes the next frame's data into pages the GPU writes too (on the console both land, byte by byte), so GPU-written results are lost. Before a flight is given to the host GPU, the unordered views of its heaps and the copies its title-memory programs' page tables name are now armed (Shadow::arm_undeclared). The first title write to such a page during the flight saves the page's bytes from before, and the copy-back merges both writers' bytes, as for a declared marked write. Once the flight has landed they are disarmed, unless a list still declares writes there. Only the Flight-1 path changes. The test a_heap_view_write_and_a_title_write_on_one_page_during_a_flight_both_land makes a heap-view write and a title write on one page while the flight is held in the air (a test gate: the host queue waits on a fence of the test's). It fails without the fix (the shader's dword comes back as the old value) and passes with it. Co-Authored-By: Claude Opus 5.5 --- crates/victory-gpu/src/bindless.rs | 12 ++ crates/victory-gpu/src/draw.rs | 1 + crates/victory-gpu/src/draw/tests/flight.rs | 106 +++++++++++++++++ crates/victory-gpu/src/host.rs | 2 + crates/victory-gpu/src/host/flight.rs | 120 +++++++++++++++++++- crates/victory-gpu/src/memory.rs | 10 ++ crates/victory-gpu/src/shadow.rs | 28 +++++ 7 files changed, 278 insertions(+), 1 deletion(-) create mode 100644 crates/victory-gpu/src/draw/tests/flight.rs diff --git a/crates/victory-gpu/src/bindless.rs b/crates/victory-gpu/src/bindless.rs index a6ea20c79..3a5dc536f 100644 --- a/crates/victory-gpu/src/bindless.rs +++ b/crates/victory-gpu/src/bindless.rs @@ -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, 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 diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index ae0ba7aab..ba045352d 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -3175,6 +3175,7 @@ const QUAD_STRIP: u32 = 20; #[cfg(test)] mod tests { + mod flight; mod tracked_rows; use super::*; diff --git a/crates/victory-gpu/src/draw/tests/flight.rs b/crates/victory-gpu/src/draw/tests/flight.rs new file mode 100644 index 000000000..7856e3f62 --- /dev/null +++ b/crates/victory-gpu/src/draw/tests/flight.rs @@ -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); +} diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 4c8e1bfac..0e1e0f07b 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -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}; diff --git a/crates/victory-gpu/src/host/flight.rs b/crates/victory-gpu/src/host/flight.rs index d87e006dd..16993f9f4 100644 --- a/crates/victory-gpu/src/host/flight.rs +++ b/crates/victory-gpu/src/host/flight.rs @@ -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`, @@ -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], + heaps: &[Arc], +) -> Vec> { + let mut armed: Vec> = Vec::new(); + let mut seen = std::collections::HashSet::new(); + let mut arm = |copy: &Arc, 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, +} + +#[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)] @@ -147,6 +254,9 @@ pub(super) struct FlightState { struct InFlight { fence_value: u64, segments: Vec>, + /// Copies whose pages it armed for its shaders' undeclared writes + /// ([`arm_undeclared`]), disarmed once it has landed. + armed: Vec>, uploads: Option, batch: Batch, heaps: Vec>, @@ -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. @@ -267,6 +380,7 @@ impl Host { let flight = InFlight { fence_value, segments, + armed, uploads: prep.uploads, batch: prep.batch, heaps: prep.heaps, @@ -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); diff --git a/crates/victory-gpu/src/memory.rs b/crates/victory-gpu/src/memory.rs index 959e45228..1bc32c0e5 100644 --- a/crates/victory-gpu/src/memory.rs +++ b/crates/victory-gpu/src/memory.rs @@ -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)) { + 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 { diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index a5dcd2f86..a10016a57 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -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