diff --git a/crates/leonida-gpu/src/host.rs b/crates/leonida-gpu/src/host.rs index e1ac23c6a..0e8767375 100644 --- a/crates/leonida-gpu/src/host.rs +++ b/crates/leonida-gpu/src/host.rs @@ -5,6 +5,8 @@ //! (unless `LEONIDA_LATE_WAIT=1`, see [`late`]); //! overlap them with per-submission fences once more than clears run. +use crate::readback::{Access as ReadBackAccess, ReadBacks, join_ranges, touches}; + use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Mutex, OnceLock}; @@ -2526,8 +2528,8 @@ struct Sent { number: u64, card: Option, back: Vec, - /// Title-memory ranges written when its shader textures are copied back. - texture_back_ranges: Vec<(usize, usize)>, + /// Destinations of texture readbacks, copied before completion is signalled. + read_backs: ReadBacks, /// Its bottom-of-pipe writes. writes: Vec<(usize, crate::queue::Written, usize)>, } @@ -2543,7 +2545,7 @@ struct Flight { order: Vec, card: Option, back: Vec, - texture_back_ranges: Vec<(usize, usize)>, + read_backs: ReadBacks, } /// One thing in the line of what waits for the card, in order. @@ -2560,6 +2562,8 @@ struct Line { /// The title memory the flights' shaders and texture readbacks may write /// (address, end), in order and joined. written: Vec<(usize, usize)>, + /// Definite readback destinations: never speculated past while preparing. + read_backs: ReadBacks, /// Host lists in the flights. lists: usize, /// The value signalled on the host's fence behind the last flight. @@ -2586,6 +2590,7 @@ unsafe impl Send for Line {} static LINE: Mutex = Mutex::new(Line { line: Vec::new(), written: Vec::new(), + read_backs: ReadBacks::new(), lists: 0, target: 0, settling: false, @@ -2623,29 +2628,6 @@ static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atom /// card, by why they settled (the `WHY_` places). static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; -/// Whether `[from, to)` touches one of `ranges` (in order, joined). -fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { - if from >= to { - return false; - } - let at = ranges.partition_point(|r| r.1 <= from); - ranges.get(at).is_some_and(|r| r.0 < to) -} - -/// `ranges` with `more`, in order, joined where they overlap or touch. -fn join_ranges(ranges: &mut Vec<(usize, usize)>, more: impl IntoIterator) { - ranges.extend(more.into_iter().filter(|r| r.0 < r.1)); - ranges.sort_unstable(); - let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); - for &(from, to) in ranges.iter() { - match out.last_mut() { - Some(last) if from <= last.1 => last.1 = last.1.max(to), - _ => out.push((from, to)), - } - } - *ranges = out; -} - /// Whether anything is in the air. fn flying() -> bool { if !late() { @@ -2662,25 +2644,52 @@ fn flying() -> bool { /// runs steps of ours that may read or write it anywhere; what the /// flights' shaders write is not there yet. fn late_blocked(runs: &[&HostList]) -> Option { - let written = { + let (written, read_backs) = { let line = line(); if line.written.is_empty() { return None; } - line.written.clone() + (line.written.clone(), line.read_backs.clone()) }; - blocked_by(&written, runs, true) + blocked_by(&written, &read_backs, runs, true) } /// [`late_blocked`] against `written`, the title memory flights' shaders /// may write (in order, joined); `count` whether the kind of read is /// counted for the frame line. -fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Option { +fn blocked_by( + written: &[(usize, usize)], + read_backs: &ReadBacks, + runs: &[&HostList], + count: bool, +) -> Option { if written.is_empty() { return None; } for list in runs { for step in &list.deferred().copies { + // These are definite CPU-side writes still to land, unlike a + // shader's broad writable view. In particular, fill_ahead must + // not let a copy or upload consume the old readback contents. + let access = match step { + &Step::Copy(dst, src, len) => ReadBackAccess::Copy { dst, src, len }, + &Step::Fill(_, at, len) + | &Step::Refresh(_, at, len) + | &Step::GpuWrite(_, at, len) => ReadBackAccess::Range(at, len), + Step::Texture(staging) => { + let (at, len) = staging.memory(); + ReadBackAccess::Range(at, len) + } + Step::Run(_) => ReadBackAccess::Unknown, + Step::Host(_) => ReadBackAccess::HostOnly, + }; + if read_backs.blocks(access) { + return Some(if matches!(step, Step::Run(_)) { + WHY_RUN + } else { + WHY_READ + }); + } match step { &Step::Copy(dst, src, len) => { if touches(written, src, src + len) || touches(written, dst, dst + len) { @@ -3713,6 +3722,22 @@ pub(crate) fn walls_trace() -> bool { *ON.get_or_init(|| std::env::var_os("LEONIDA_WALLS_TRACE").is_some_and(|v| v == "1" || v == "2")) } +/// Readbacks of these lists whose destinations must remain pending until +/// the CPU copy-back finishes, including ordinary texture-to-buffer copies. +fn pending_read_backs(runs: &[&HostList]) -> ReadBacks { + let mut pending = ReadBacks::default(); + for list in runs { + let deferred = list.deferred(); + pending.extend(deferred.texture_backs.iter().map(crate::texback::Back::range)); + for (_, at, layout) in &deferred.backs { + if !pending.rows(*at, *layout) { + fail(format_args!("texture readback destination range overflow")); + } + } + } + pending +} + /// After `list` has run: the texels its read-backs copied into host /// buffers of ours go to the title's memory (`HostList::defer_read_back`). /// @@ -5030,6 +5055,7 @@ impl Host { let Line { line: items, written, + read_backs, lists, settling, poke, @@ -5041,16 +5067,20 @@ impl Host { in_hand.clear(); // What is still in the air, from the flights that are. written.clear(); + read_backs.clear(); *lists = 0; let mut ranges = Vec::new(); for item in items.iter() { if let Late::Run(flight) = item { *lists += flight.order.len().max(1); ranges.extend(flight.back.iter().flat_map(|(_, r)| r.iter().copied())); - ranges.extend(flight.texture_back_ranges.iter().copied()); + read_backs.extend(flight.read_backs.ranges().iter().copied()); } } - join_ranges(written, ranges); + join_ranges( + written, + ranges.into_iter().chain(read_backs.ranges().iter().copied()), + ); *settling = false; // The landed lists are reset, and what queues hold looked at, // by the helper thread (they take locks a waiter may hold). @@ -5246,14 +5276,15 @@ impl Host { let told = !sent.writes.is_empty(); let most = { let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; + let Line { line: items, written, read_backs, lists: flying, target, .. } = &mut *line; join_ranges( written, sent.back .iter() .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), + .chain(sent.read_backs.ranges().iter().copied()), ); + read_backs.extend(sent.read_backs.ranges().iter().copied()); *flying += order.len(); *target = *submitted; items.push(Late::Run(Flight { @@ -5263,7 +5294,7 @@ impl Host { order, card: sent.card, back: sent.back, - texture_back_ranges: sent.texture_back_ranges, + read_backs: sent.read_backs, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); *flying >= late_most() @@ -5297,14 +5328,15 @@ impl Host { let number = sent.number; { let mut line = line(); - let Line { line: items, written, lists: flying, target, .. } = &mut *line; + let Line { line: items, written, read_backs, lists: flying, target, .. } = &mut *line; join_ranges( written, sent.back .iter() .flat_map(|(_, ranges)| ranges.iter().copied()) - .chain(sent.texture_back_ranges.iter().copied()), + .chain(sent.read_backs.ranges().iter().copied()), ); + read_backs.extend(sent.read_backs.ranges().iter().copied()); *flying += 1; *target = *submitted; items.push(Late::Run(Flight { @@ -5314,7 +5346,7 @@ impl Host { order: Vec::new(), card: sent.card, back: sent.back, - texture_back_ranges: sent.texture_back_ranges, + read_backs: sent.read_backs, })); items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes))); } @@ -5362,6 +5394,7 @@ impl Host { } line.settling = true; line.written.clear(); + line.read_backs.clear(); line.lists = 0; std::mem::take(&mut line.line) }; @@ -5503,7 +5536,9 @@ impl Host { if relay_exact() && why == WHY_READ { // Only until the flights that may write what is read have // landed: their copy-back's end, not the card's other work. - relay_wait(why, |line| blocked_by(&line.written, runs, false).is_none()); + relay_wait(why, |line| { + blocked_by(&line.written, &line.read_backs, runs, false).is_none() + }); } else { self.settle(&mut submitted, why); } @@ -5626,10 +5661,7 @@ impl Host { fail(format_args!("a submission sent ahead could not be followed by a signal ({e})")); } let back = declared_writes(runs); - let mut texture_back_ranges = Vec::new(); - for list in runs { - texture_back_ranges.extend(list.deferred().texture_backs.iter().map(crate::texback::Back::range)); - } + let read_backs = pending_read_backs(runs); let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); submission_us(0, (prepared - started).saturating_sub(settled).as_micros() as u64); submitting(0, 0); @@ -5639,7 +5671,7 @@ impl Host { number: this_submission, card, back, - texture_back_ranges, + read_backs, writes, }; working(was_working); @@ -9320,3 +9352,175 @@ void main() { drop((a, b, trial)); } } + +/// Optional end-to-end check, alone in a fresh process: +/// LEONIDA_TEST_READBACK_ORDER=1 LEONIDA_D3D12_WARP=1 LEONIDA_LATE_WAIT=3 +/// LEONIDA_RELAY=0 (also 1 and 2), with diagnostics and one test thread. +/// A hardware adapter requires LEONIDA_TEST_READBACK_HARDWARE=1 instead of WARP. +/// No device is created without explicit test and adapter opt-ins. This tests separate +/// submissions; dependencies inside one submission need command-list splitting. +#[cfg(all(test, feature = "diagnostics"))] +mod readback_order_tests { + use super::*; + + #[test] + fn later_submission_copies_texture_readback_after_completion() { + let hardware = std::env::var("LEONIDA_TEST_READBACK_HARDWARE").as_deref() == Ok("1"); + if std::env::var("LEONIDA_TEST_READBACK_ORDER").as_deref() != Ok("1") + || (!hardware && std::env::var("LEONIDA_D3D12_WARP").as_deref() != Ok("1")) + { + eprintln!("readback order test skipped: explicit test and adapter opt-ins required"); + return; + } + let host = host().expect("explicitly selected host device"); + // SAFETY: a plain query; hardware requires its own explicit opt-in. + let software = host + .adapter + .as_ref() + .and_then(|a| unsafe { a.GetDesc1() }.ok()) + .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); + assert!(software || hardware, "hardware execution was not explicitly requested"); + assert!( + late(), + "readback order test requires asynchronous submissions" + ); + assert!(late_most() > 1, "producer must remain in flight for this test"); + assert!( + fill_ahead::on(), + "exercise the default speculative-read path" + ); + settle_now(WHY_SYNC); + + let mut title = Box::new([0u32; 2]); + let source = title.as_mut_ptr().cast::(); + // SAFETY: the second dword of this allocation, alive through settling. + let destination = unsafe { source.add(4) }; + let producer = host.new_list().expect("producer list"); + let (upload, data) = producer.upload(host, 256).expect("one upload row"); + // SAFETY: the upload mapping has at least one dword. + unsafe { data.cast::().write(37) }; + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 1, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R32_UINT, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + ..Default::default() + }; + let mut texture: Option = None; + // SAFETY: ordinary creation of a one-texel texture. + unsafe { + host.device + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut texture, + ) + .expect("one-texel texture"); + } + let texture = texture.unwrap(); + let back = host.read_back_buffer(256).expect("one readback row"); + let rows = |buffer: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: borrowed resource kept alive until both submissions settle. + pResource: unsafe { std::mem::transmute_copy(buffer) }, + Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R32_UINT, + Width: 1, + Height: 1, + Depth: 1, + RowPitch: 256, + }, + }, + }, + }; + let whole = D3D12_TEXTURE_COPY_LOCATION { + // SAFETY: borrowed texture kept alive through both submissions. + pResource: unsafe { std::mem::transmute_copy(&texture) }, + Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: 0, + }, + }; + // SAFETY: open list, live resources, matching one-texel footprints. + unsafe { + producer + .list + .CopyTextureRegion(&whole, 0, 0, 0, &rows(&upload), None); + producer.list.ResourceBarrier(&[transition( + &texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); + producer + .list + .CopyTextureRegion(&rows(&back), 0, 0, 0, &whole, None); + } + producer.defer_read_back(back, source, [4, 1, 256]); + producer.close(); + + // Hold the GPU before the first submission. Release only after the + // consumer either enters the real dependency wait or has already + // copied stale bytes (the old bug). No elapsed-time guess decides + // which happened; the deadline only prevents a broken test hanging. + // SAFETY: a fence owned by the test, signalled by the coordinator. + let gate: ID3D12Fence = unsafe { + host.device + .CreateFence(0, D3D12_FENCE_FLAG_NONE) + .expect("test gate") + }; + let consumer = host.new_list().expect("consumer list"); + consumer.defer_copy(destination, source, 4); + let (copied, observed) = std::sync::mpsc::channel(); + consumer.defer_host(move || { + let _ = copied.send(()); + }); + consumer.close(); + let before_wait = LATE_STATS[WHY_READ].load(Ordering::Relaxed); + // SAFETY: the gate will be signalled independently of this queue. + unsafe { host.queue.Wait(&gate, 1).expect("hold first submission") }; + let coordinator = std::thread::spawn(move || { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + let reason = loop { + if LATE_STATS[WHY_READ].load(Ordering::Relaxed) != before_wait { + break "dependency wait"; + } + if observed.try_recv().is_ok() { + break "copy before completion"; + } + if std::time::Instant::now() >= deadline { + break "deadline"; + } + std::thread::yield_now(); + }; + // SAFETY: release the test's gate even if its deadline expired. + unsafe { gate.Signal(1).expect("release test gate") }; + reason + }); + host.execute_late(vec![crate::list::Detached::for_test(producer)], vec![0]); + host.execute_late(vec![crate::list::Detached::for_test(consumer)], vec![0]); + settle_now(WHY_SYNC); + let reason = coordinator.join().expect("test coordinator"); + assert_ne!(reason, "deadline", "consumer made no observable progress"); + assert_eq!(title[0], 37, "texture readback did not land"); + assert_eq!( + title[1], 37, + "later submission copied before readback completion" + ); + assert_eq!(reason, "dependency wait"); + } +} diff --git a/crates/leonida-gpu/src/lib.rs b/crates/leonida-gpu/src/lib.rs index e09a219dc..de32532b5 100644 --- a/crates/leonida-gpu/src/lib.rs +++ b/crates/leonida-gpu/src/lib.rs @@ -61,6 +61,8 @@ pub mod query; pub mod queue; #[cfg(windows)] mod queue2; +#[cfg(any(windows, test))] +mod readback; pub mod resource; pub mod root; #[cfg(windows)] diff --git a/crates/leonida-gpu/src/list.rs b/crates/leonida-gpu/src/list.rs index b96818835..c9948ab6e 100644 --- a/crates/leonida-gpu/src/list.rs +++ b/crates/leonida-gpu/src/list.rs @@ -198,6 +198,11 @@ impl Detached { pub(crate) fn host(&self) -> &crate::host::HostList { &self.host } + + #[cfg(all(test, feature = "diagnostics"))] + pub(crate) fn for_test(host: crate::host::HostList) -> Self { + Self { host, _uploads: Vec::new(), _state: crate::draw::State::default() } + } } /// A host list that has run and waits to be used again, and the bytes of diff --git a/crates/leonida-gpu/src/readback.rs b/crates/leonida-gpu/src/readback.rs new file mode 100644 index 000000000..4d7a9c69f --- /dev/null +++ b/crates/leonida-gpu/src/readback.rs @@ -0,0 +1,186 @@ +//! Dependencies on texture readbacks still to land in title memory. +//! +//! Unlike a shader's broad writable view, a readback describes bytes that +//! will be copied. Submission preparation must not speculate past them. +//! This orders separate submissions; it does not split dependencies between +//! commands that are already grouped into one submission. + +/// The title memory a submission-time step reads or overwrites. +#[derive(Clone, Copy)] +pub(crate) enum Access { + Range(usize, usize), + Copy { dst: usize, src: usize, len: usize }, + Unknown, + HostOnly, +} + +/// Exact destination ranges, kept until their flights have landed. +#[derive(Clone, Default)] +pub(crate) struct ReadBacks(Vec<(usize, usize)>); + +impl ReadBacks { + pub(crate) const fn new() -> Self { + Self(Vec::new()) + } + + pub(crate) fn ranges(&self) -> &[(usize, usize)] { + &self.0 + } + + pub(crate) fn extend(&mut self, ranges: impl IntoIterator) { + join_ranges(&mut self.0, ranges); + } + + /// Only written bytes, not the padding between the title's rows. + pub(crate) fn rows(&mut self, at: usize, [row, rows, pitch]: [usize; 3]) -> bool { + if row == 0 || rows == 0 { + return true; + } + if (rows - 1) + .checked_mul(pitch) + .and_then(|offset| at.checked_add(offset)) + .and_then(|last| last.checked_add(row)) + .is_none() + { + return false; + } + self.extend((0..rows).map(|line| { + let from = at + line * pitch; + (from, from + row) + })); + true + } + + pub(crate) fn clear(&mut self) { + self.0.clear(); + } + + /// This check precedes the optional read-ahead of shader-write ranges. + pub(crate) fn blocks(&self, access: Access) -> bool { + let hits = |at: usize, len: usize| touches(&self.0, at, at.saturating_add(len)); + match access { + Access::Range(at, len) => hits(at, len), + Access::Copy { dst, src, len } => hits(src, len) || hits(dst, len), + Access::Unknown => !self.0.is_empty(), + Access::HostOnly => false, + } + } +} + +/// Whether `[from, to)` touches a sorted, joined range. +pub(crate) fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { + if from >= to { + return false; + } + let at = ranges.partition_point(|r| r.1 <= from); + ranges.get(at).is_some_and(|r| r.0 < to) +} + +/// Adds ranges in order, joining overlapping or adjacent spans. +pub(crate) fn join_ranges( + ranges: &mut Vec<(usize, usize)>, + more: impl IntoIterator, +) { + ranges.extend(more.into_iter().filter(|r| r.0 < r.1)); + ranges.sort_unstable(); + let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(from, to) in ranges.iter() { + match out.last_mut() { + Some(last) if from <= last.1 => last.1 = last.1.max(to), + _ => out.push((from, to)), + } + } + *ranges = out; +} + +#[cfg(test)] +mod tests { + use super::{Access, ReadBacks}; + + /// Two separate submissions: the first texture copy has not landed + /// when the second's CPU-side buffer copy is prepared. Its source must + /// become visible first, even with speculative shader fills enabled. + #[test] + fn later_submission_copies_the_readback_result() { + let mut pending = ReadBacks::default(); + pending.rows(0x1000, [4, 1, 256]); + let access = Access::Copy { + dst: 0x2000, + src: 0x1000, + len: 4, + }; + let mut source = 0; + let mut copied = None; + // This is the mandatory production decision, before fill_ahead. + if !pending.blocks(access) { + copied = Some(source); + } + assert_eq!(copied, None, "copy prepared before its producer landed"); + source = 37; + pending.clear(); + if !pending.blocks(access) { + copied = Some(source); + } + assert_eq!(copied, Some(37)); + } + + #[test] + fn overwritten_readback_and_cpu_uploads_wait_too() { + let mut pending = ReadBacks::default(); + pending.rows(0x1000, [16, 1, 256]); + assert!(pending.blocks(Access::Copy { + dst: 0x1008, + src: 0x2000, + len: 4 + })); + // Fills, shadow refreshes, write snapshots and texture staging all + // read a range of title memory during submission preparation. + assert!(pending.blocks(Access::Range(0x1008, 4))); + assert!(pending.blocks(Access::Unknown)); + assert!(!pending.blocks(Access::HostOnly)); + assert!(!pending.blocks(Access::Range(0x2000, 16))); + } + + #[test] + fn pitched_rows_do_not_block_padding_or_unrelated_memory() { + let mut pending = ReadBacks::default(); + pending.rows(0x1000, [8, 2, 256]); + assert!(pending.blocks(Access::Range(0x1004, 4))); + assert!(pending.blocks(Access::Range(0x1104, 4))); + assert!(!pending.blocks(Access::Range(0x1008, 248))); + assert!(!pending.blocks(Access::Range(0x0ff0, 16))); + assert!(!pending.blocks(Access::Range(0x1108, 16))); + assert!(!pending.blocks(Access::Range(0x1000, 0))); + } + + #[test] + fn empty_and_overflowing_footprints_do_not_add_partial_ranges() { + let mut pending = ReadBacks::new(); + assert!(pending.rows(usize::MAX, [0, 2, 256])); + assert!(pending.rows(usize::MAX, [16, 0, 256])); + assert!(!pending.rows(usize::MAX - 3, [8, 1, 256])); + assert!(!pending.rows(0x1000, [8, usize::MAX, 256])); + assert!(!pending.blocks(Access::Unknown)); + } + + #[test] + fn landing_one_flight_keeps_later_readbacks_pending() { + let mut first = ReadBacks::default(); + first.rows(0x1000, [16, 1, 256]); + let mut later = ReadBacks::default(); + later.rows(0x1008, [16, 1, 256]); + later.extend([(0x3000, 0x3100)]); // A tiled texture readback. + let mut pending = first.clone(); + pending.extend(later.ranges().iter().copied()); + // Removing flights from the queue to land them does not clear the + // pending ranges: a CPU readback can still be in progress. + assert!(pending.blocks(Access::Range(0x1000, 4))); + // After the first flight's copy-back, rebuild from those still in + // flight. Overlap with the landed flight must not erase the later one. + pending.clear(); + pending.extend(later.ranges().iter().copied()); + assert!(!pending.blocks(Access::Range(0x1000, 4))); + assert!(pending.blocks(Access::Range(0x1008, 4))); + assert!(pending.blocks(Access::Range(0x3000, 4))); + } +} diff --git a/docs/fork-notes.md b/docs/fork-notes.md index b0ab765c4..49f7997c6 100644 --- a/docs/fork-notes.md +++ b/docs/fork-notes.md @@ -5,6 +5,40 @@ The status summary is in [README.md](../README.md). ## Newest (2026-11-26) +**Wait for texture readbacks before preparing dependent submissions.** +Ordinary texture-to-buffer copies were missing from the ranges tracked while +submissions were in flight. A later submission's CPU-side buffer copy could +therefore consume stale title memory before the earlier texture readback landed. +The pending ranges now include the bytes actually written by each readback row, +excluding pitch padding. Overlapping CPU reads and writes wait for these definite +writes even when speculative shader fills are enabled; unrelated work can proceed. +The ranges remain pending until CPU copy-back completes, including when the relay +lands only part of the queue. + +An original one-texel D3D12 regression holds the first submission behind a fence +and queues a dependent copy in a second submission. It releases the fence when +the consumer enters the dependency wait, or after the old implementation has +copied stale bytes; timing does not choose the outcome. On `63fb0e8` with the test +only, the destination is 0 instead of 37 in all three `LEONIDA_RELAY=0/1/2` modes. +With the fix it is 37 in all three modes, with `LEONIDA_LATE_WAIT=3`, queue2 and +the default speculative-fill path enabled. Measured on an Intel Core i9-14900KS, +RTX 5090, NVIDIA 580.173.02, Pop!_OS 22.04, Proton 11's Wine and vkd3d-proton 3.2. +Five CPU tests also cover row padding, destination overwrites, empty and +overflowing footprints, and retaining later flights' pending ranges. + +Run the optional test alone in a fresh diagnostics test process with +`LEONIDA_TEST_READBACK_ORDER=1`, `LEONIDA_LATE_WAIT=3`, the desired +`LEONIDA_RELAY` value, and either `LEONIDA_D3D12_WARP=1` or the explicit hardware +opt-in `LEONIDA_TEST_READBACK_HARDWARE=1`: +`cargo test -p leonida-gpu --features diagnostics --locked +host::readback_order_tests::later_submission_copies_texture_readback_after_completion +-- --exact --nocapture --test-threads=1`. + +This orders separate submissions only. Dependencies between commands already +grouped in one submission still need command-list splitting. This synthetic +correctness result does not establish the cause of the washed-out game frames +or claim a gameplay or frame-rate improvement. + **R-7: buffer view addresses by view heap slot.** The 5 `CS_TraceShadowRays_*` compute programs ("a descriptor read only as data") load a buffer descriptor from the view heap at an index they compute