ソースを参照

Merge local/upcopies

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 2 日 前
親
コミット
ff1bd66387

+ 6 - 0
crates/victory-gpu/src/draw.rs

@@ -3124,6 +3124,12 @@ impl State {
         }
     }
 
+    /// A buffer was copied to: what was clamped of it ahead is clamped anew.
+    pub(crate) fn copied(&mut self) {
+        self.window = None;
+        self.batch = None;
+    }
+
     /// The title waits for earlier work (a barrier or a pipeline sync).
     pub(crate) fn synced(&mut self) {
         if self.batch.as_ref().is_some_and(|b| b.wrote) {

+ 67 - 16
crates/victory-gpu/src/host.rs

@@ -1410,11 +1410,10 @@ impl Drop for Counted {
 }
 
 /// A chunk of upload memory for lists' scratch data: the buffer, its
-/// mapping and its host GPU address.
+/// mapping.
 struct Chunk {
-    _buffer: ID3D12Resource,
+    buffer: ID3D12Resource,
     data: usize,
-    gpu: u64,
 }
 
 // SAFETY: a D3D12 resource (free-threaded) and its persistent mapping,
@@ -1506,14 +1505,11 @@ fn take_chunk(host: &Host, size: u64) -> Option<Chunk> {
     }
     let (buffer, data) = host.upload_buffer(size)?;
     name(&buffer, || "list scratch".into());
-    // SAFETY: a live buffer.
-    let gpu = unsafe { buffer.GetGPUVirtualAddress() };
     ALIVE[1].fetch_add(1, Ordering::Relaxed);
     ALIVE[2].fetch_add(size, Ordering::Relaxed);
     Some(Chunk {
-        _buffer: buffer,
+        buffer,
         data: data as usize,
-        gpu,
     })
 }
 
@@ -1780,6 +1776,9 @@ enum Step {
     /// Brings a texture's staging buffer up to date: once per submission,
     /// whichever lists sample it, until a `Copy` or `Run` intervenes.
     Texture(std::sync::Arc<crate::texture::Staging>),
+    /// A title buffer copy that the list does on the card ([`place`]): what
+    /// is done on the CPU for it.
+    Placed(place::Placed),
 }
 
 /// What a list does on the CPU when it is submitted: copies between host
@@ -2467,6 +2466,8 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op
     if written.is_empty() {
         return None;
     }
+    // Destinations of copies at their place, if a step reads them.
+    let mut placed: Vec<(usize, usize)> = Vec::new();
     for list in runs {
         for step in &list.deferred().copies {
             match step {
@@ -2506,11 +2507,23 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op
                     }
                 }
                 Step::Run(_) => return Some(WHY_RUN),
+                Step::Placed(p) => match p.waits(written) {
+                    place::Waits::No => {}
+                    place::Waits::ForReaders => placed.push((p.dst, p.dst + p.len)),
+                    place::Waits::Yes => {
+                        if count {
+                            LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
+                            #[cfg(feature = "diagnostics")]
+                            blame("a buffer copy at its place", written, p.src, p.len);
+                        }
+                        return Some(WHY_READ);
+                    }
+                },
                 Step::Refresh(..) | Step::GpuWrite(..) | Step::Host(..) => {}
             }
         }
     }
-    None
+    (!placed.is_empty() && place::read_by(runs, placed)).then_some(WHY_READ)
 }
 
 /// With flights in the air, after the submission's write-watch asking:
@@ -3031,6 +3044,16 @@ fn late_line(frames: f64) {
         }
     }
     crate::land::log(frames);
+    if place::on() {
+        let t: Vec<f64> = place::STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect();
+        tracing::info!(
+            "title buffer copies at their place in the lists, per frame (VICTORY_COPIES_IN_PLACE): {:.1} of {:.1} KB, {:.1} of them out              of what shaders wrote; {:.2} copies into textures out of what shaders wrote",
+            t[0],
+            t[1] / 1024.0,
+            t[2],
+            t[3],
+        );
+    }
     card_steps::log(frames);
     crate::picked::log(frames);
     #[cfg(feature = "diagnostics")]
@@ -3046,6 +3069,7 @@ fn late_line(frames: f64) {
 }
 
 mod card_steps;
+mod place;
 mod send;
 mod torn;
 pub(crate) mod upcheck;
@@ -4826,8 +4850,10 @@ impl Host {
         }
         #[cfg(feature = "diagnostics")]
         split.part(1);
+        // What flights in the air may write.
+        let air = line().written.clone();
         for list in runs {
-            list.run_deferred(&mut batch, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
+            list.run_deferred(&mut batch, &air, |i| own.as_ref().is_some_and(|own| own.takes(list, i)));
             firsts.push(lists.len());
             if let Some(prelude) = list.prelude() {
                 lists.push(Some(prelude));
@@ -4866,6 +4892,11 @@ impl Host {
             shadow.writing(*at, *len);
         }
         let card = self.card_before(runs, &picked, flown);
+        // The sends are taken: from here on the references hold what the
+        // copies in the lists put.
+        for (shadow, at, bytes) in batch.placed.drain(..) {
+            shadow.placed_copy(at, &bytes);
+        }
         if let Some(check) = card.as_ref().and_then(|c| c.check.clone()) {
             lists.push(Some(check));
         }
@@ -5858,16 +5889,22 @@ impl HostList {
     /// `len` bytes of upload memory (256-byte aligned) until the list is
     /// reset: the host GPU address and the CPU pointer.
     pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
+        let (buffer, at, data) = self.scratch_at(len)?;
+        // SAFETY: a live buffer.
+        Some((unsafe { buffer.GetGPUVirtualAddress() } + at, data))
+    }
+
+    /// [`HostList::scratch`]: the buffer, the offset in it and the CPU
+    /// pointer.
+    fn scratch_at(&self, len: u64) -> Option<(ID3D12Resource, u64, *mut u8)> {
         let host = host()?;
         let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
         let len = len.max(1).next_multiple_of(256);
         if len > SCRATCH_CHUNK {
             let (buffer, data) = host.upload_buffer(len)?;
             name(&buffer, || format!("list scratch {len:#x}"));
-            // SAFETY: a live buffer.
-            let gpu = unsafe { buffer.GetGPUVirtualAddress() };
-            self.deferred().hold_upload(buffer, len);
-            return Some((gpu, data));
+            self.deferred().hold_upload(buffer.clone(), len);
+            return Some((buffer, 0, data));
         }
         // The chunk in use while `len` fits in what is left of it, else the
         // next one (a list's first chunk may be a small one).
@@ -5884,10 +5921,10 @@ impl HostList {
             s.chunks.push((chunk, size));
             s.used = 0;
         }
-        let (data, gpu) = (s.chunks[s.current].0.data, s.chunks[s.current].0.gpu);
+        let (data, buffer) = (s.chunks[s.current].0.data, s.chunks[s.current].0.buffer.clone());
         let at = s.used;
         s.used += len;
-        Some((gpu + at, (data + at as usize) as *mut u8))
+        Some((buffer, at, (data + at as usize) as *mut u8))
     }
 
     /// The bytes of scratch chunks the list holds now (after a reset:
@@ -6165,7 +6202,7 @@ impl HostList {
     /// lists of a submission, through many ranges). Copies and fills that
     /// `taken` names (by their place) are left out: they are done on the
     /// card ([`card_steps`]).
-    fn run_deferred(&self, batch: &mut Batch, taken: impl Fn(usize) -> bool) {
+    fn run_deferred(&self, batch: &mut Batch, air: &[(usize, usize)], taken: impl Fn(usize) -> bool) {
         #[cfg(feature = "diagnostics")]
         use crate::copystat::{C, add};
         // The time and the bytes of the copies and fills, some 13,000 a
@@ -6204,6 +6241,17 @@ impl HostList {
                     copy_mapped(dst as *mut u8, src as *const u8, len, false);
                     (started, len)
                 }
+                Step::Placed(p) => {
+                    let started = std::time::Instant::now();
+                    let free = !touches(air, p.src, p.src + p.len) && !touches(air, p.dst, p.dst + p.len);
+                    if free {
+                        batch.title_written();
+                    }
+                    if let Some(bytes) = p.prepare(free) {
+                        batch.placed.push((p.shadow.clone(), p.dst, bytes));
+                    }
+                    (started, p.len)
+                }
                 Step::Refresh(shadow, address, len) => {
                     #[cfg(feature = "diagnostics")]
                     {
@@ -6466,6 +6514,9 @@ struct Batch {
     textures: std::collections::HashSet<usize>,
     /// Those due ([`Batch::refresh_textures`]).
     due: Vec<std::sync::Arc<crate::texture::Staging>>,
+    /// What copies at their place in the submission's lists put into title
+    /// memory ([`place`]): the host copy, the title address, the bytes.
+    placed: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, Vec<u8>)>,
 }
 
 /// Whether a submission's textures are brought up to date on several

+ 12 - 0
crates/victory-gpu/src/host/card_steps.rs

@@ -194,6 +194,8 @@ enum Does {
     Read { from: usize, to: usize, asked: bool },
     /// A refresh of a host copy (named by its address).
     Refresh { shadow: usize, from: usize, to: usize },
+    /// A copy that its list does on the card ([`place`]).
+    Placed { dst: usize, src: usize, len: usize },
     /// Anything, anywhere.
     Run,
 }
@@ -271,6 +273,15 @@ fn plan(does: &[Does], stage: u32) -> Result<Vec<(usize, u32)>, &'static str> {
             }
         }
     }
+    // A copy at its place in a list comes after what is done in front of all
+    // of them.
+    for d in does {
+        if let Does::Placed { dst, src, len } = *d
+            && (touched(&read, (dst, dst + len)) || touched(&written, (dst, dst + len)) || touched(&written, (src, src + len)))
+        {
+            return Err("a copy at its place in a list writes what it reads, or reads or writes what it writes");
+        }
+    }
     let order: Vec<usize> = (0..does.len()).filter(|&i| taken[i]).collect();
     // What stays on the CPU and reads what an earlier taken copy writes
     // would read it too early.
@@ -572,6 +583,7 @@ impl Host {
                         to: *at + *len,
                     },
                     Step::Run(_) => Does::Run,
+                    Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len },
                     Step::GpuWrite(..) | Step::Host(..) => continue,
                 });
                 steps.push((std::ptr::from_ref::<HostList>(list) as usize, i));

+ 320 - 0
crates/victory-gpu/src/host/place.rs

@@ -0,0 +1,320 @@
+//! The title's buffer copies, done on the card at their place in the list
+//! (`VICTORY_COPIES_IN_PLACE`, on by default; `0`: all at submission, on the
+//! CPU, as before).
+//!
+//! A buffer copy was done in title memory when its list was submitted, before
+//! any draw of the submission ran, and the host copies refreshed after it.
+//! That is another order than the list's: draws ahead of the copy read what
+//! it put; of two copies to the same bytes with a draw behind each, both
+//! draws read the second; a source that a dispatch of the same submission
+//! writes first was read as it was before it; and a destination the
+//! submissions in the air still read changed under them (where its host copy
+//! has one side only, `crate::shadow::card_all`).
+//!
+//! Now the list copies, in the destination's host copy: out of the source's
+//! host copy where shaders write that one, else out of upload memory of the
+//! list that takes the source's bytes when the list is submitted (a source
+//! shaders never wrote is the title's CPU's, or a copy's put there earlier in
+//! the submission). What is written there is a shader's write from then on:
+//! the bytes are declared, and what the card made of them is put into title
+//! memory before the title is told of the submission.
+//!
+//! Title memory takes the copy at submission as well, as it did: fills of
+//! upload memory, textures and host copies that lie over the same bytes read
+//! it there. The reference of the destination's host copy takes the same
+//! bytes ([`Shadow::placed_copy`]), so what the landing finds is what the card
+//! made of them afterwards (a counter copied to zero and counted up; a source
+//! that a shader wrote in between), and nothing is sent up over it. Where
+//! flights in the air may write the source or the destination this is left to
+//! the landing: what they wrote is not in title memory yet, and what they
+//! will put there must not stand over this copy's bytes. If a step of the
+//! submission reads the destination on the CPU, it waits for them instead
+//! ([`Placed::waits`]).
+//!
+//! Copies to memory that has no host copy yet are done as before: nothing on
+//! the card has read or written it. So are those of more than 8 MiB out of
+//! memory shaders do not write (streaming).
+
+use super::*;
+use crate::shadow::Shadow;
+
+pub(super) fn on() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_COPIES_IN_PLACE").is_none_or(|v| v != "0"))
+}
+
+/// The most bytes copied out of memory shaders do not write.
+const MOST: usize = 8 << 20;
+
+/// Since the last frame-rate line: copies at their place, their bytes, those
+/// out of a host copy, and texture copies out of one.
+pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
+
+/// What the CPU does at submission for a copy at its place in a list.
+pub(super) struct Placed {
+    pub(super) dst: usize,
+    pub(super) src: usize,
+    pub(super) len: usize,
+    /// The destination's host copy.
+    pub(super) shadow: std::sync::Arc<Shadow>,
+    /// Upload memory the list copies from, to be given the source's bytes.
+    from: Option<usize>,
+}
+
+impl Placed {
+    /// Whether flights that write `written` are waited for.
+    pub(super) fn waits(&self, written: &[(usize, usize)]) -> Waits {
+        let source = touches(written, self.src, self.src + self.len);
+        if source && self.from.is_some() {
+            return Waits::Yes;
+        }
+        match source || touches(written, self.dst, self.dst + self.len) {
+            true => Waits::ForReaders,
+            false => Waits::No,
+        }
+    }
+
+    /// At submission, in the order of the steps: the list's upload memory
+    /// takes the source's bytes and, if `free` (no flight in the air may write
+    /// source or destination), title memory at the destination does. Gives
+    /// the bytes if it took them.
+    pub(super) fn prepare(&self, free: bool) -> Option<Vec<u8>> {
+        if !free && self.from.is_none() {
+            return None;
+        }
+        let mut bytes = vec![0u8; self.len];
+        // (What is not there reads as zeros, as any copy's source.)
+        copy_mapped(bytes.as_mut_ptr(), self.src as *const u8, self.len, false);
+        if let Some(to) = self.from {
+            // SAFETY: the list's own upload memory of that many bytes.
+            unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), to as *mut u8, self.len) };
+        }
+        if !free {
+            return None;
+        }
+        copy_mapped(self.dst as *mut u8, bytes.as_ptr(), self.len, true);
+        crate::watch::wrote(self.dst, self.len);
+        // Title memory that is not all there was left alone.
+        let mut there = vec![0u8; self.len];
+        (read_into(self.dst as *const u8, &mut there) && there == bytes).then_some(bytes)
+    }
+}
+
+/// Whether a copy waits for flights before its submission is prepared: not;
+/// yes, as it takes a source on the CPU that they may write; or only if
+/// another step of the submission reads its destination on the CPU.
+pub(super) enum Waits {
+    No,
+    ForReaders,
+    Yes,
+}
+
+/// Whether a step of `runs` reads one of `ranges` on the CPU.
+pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bool {
+    join_ranges(&mut ranges, []);
+    runs.iter().any(|list| {
+        list.deferred().copies.iter().any(|step| match step {
+            &Step::Copy(_, src, len) | &Step::Fill(_, src, len, _) => touches(&ranges, src, src + len),
+            Step::Texture(staging) => {
+                let (at, len) = staging.memory();
+                touches(&ranges, at, at + len)
+            }
+            Step::Host(_, (from, to)) => touches(&ranges, *from, *to),
+            Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len),
+            _ => false,
+        })
+    })
+}
+
+/// Everything recorded so far is done, and seen, before what follows.
+///
+/// # Safety
+/// An open list.
+unsafe fn wait_for_all(host: &Host, list: &ID3D12GraphicsCommandList) {
+    static ENHANCED: OnceLock<bool> = OnceLock::new();
+    let enhanced = *ENHANCED.get_or_init(|| {
+        let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default();
+        // SAFETY: a feature structure of its size.
+        let known = unsafe {
+            host.device.CheckFeatureSupport(
+                D3D12_FEATURE_D3D12_OPTIONS12,
+                (&raw mut o).cast(),
+                size_of::<D3D12_FEATURE_DATA_D3D12_OPTIONS12>() as u32,
+            )
+        };
+        known.is_ok() && o.EnhancedBarriersSupported.as_bool()
+    });
+    // SAFETY: the caller's.
+    unsafe {
+        if enhanced && let Ok(list) = list.cast::<ID3D12GraphicsCommandList7>() {
+            let all = [D3D12_GLOBAL_BARRIER {
+                SyncBefore: D3D12_BARRIER_SYNC_ALL,
+                SyncAfter: D3D12_BARRIER_SYNC_ALL,
+                AccessBefore: D3D12_BARRIER_ACCESS_COMMON,
+                AccessAfter: D3D12_BARRIER_ACCESS_COMMON,
+            }];
+            list.Barrier(&[D3D12_BARRIER_GROUP {
+                Type: D3D12_BARRIER_TYPE_GLOBAL,
+                NumBarriers: 1,
+                Anonymous: D3D12_BARRIER_GROUP_0 {
+                    pGlobalBarriers: all.as_ptr(),
+                },
+            }]);
+            return;
+        }
+        let alias = D3D12_RESOURCE_BARRIER {
+            Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
+            Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+            Anonymous: D3D12_RESOURCE_BARRIER_0 {
+                Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
+                    pResourceBefore: std::mem::ManuallyDrop::new(None),
+                    pResourceAfter: std::mem::ManuallyDrop::new(None),
+                }),
+            },
+        };
+        let uav = D3D12_RESOURCE_BARRIER {
+            Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
+            Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
+            Anonymous: D3D12_RESOURCE_BARRIER_0 {
+                UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
+                    pResource: std::mem::ManuallyDrop::new(None),
+                }),
+            },
+        };
+        list.ResourceBarrier(&[alias, uav]);
+    }
+}
+
+/// The host copy of `[src, src + len)` if shaders write it: what it holds at
+/// a place in a list is not what title memory holds at submission.
+fn shaders_own(src: usize, len: usize) -> Option<std::sync::Arc<Shadow>> {
+    crate::shadow::peek(src as u64, len as u64).filter(|s| s.written() && !s.in_place())
+}
+
+impl HostList {
+    /// Copies `len` bytes of title memory at `src` to `dst`, at this place of
+    /// the list (see the file). `false` if it is to be done at submission.
+    pub(crate) fn place_copy(&self, dst: usize, src: usize, len: usize) -> bool {
+        if !on() {
+            return false;
+        }
+        let Some(host) = host() else {
+            return false;
+        };
+        let Some(to) = crate::shadow::peek(dst as u64, len as u64).filter(|s| !s.in_place()) else {
+            return false;
+        };
+        let own = shaders_own(src, len);
+        let scratch = match &own {
+            Some(_) => None,
+            None if len <= MOST => match self.scratch_at(len as u64) {
+                Some(scratch) => Some(scratch),
+                None => return false,
+            },
+            None => return false,
+        };
+        let at = to.offset(dst as u64);
+        // What the title's CPU wrote around and under it so far goes first.
+        to.refresh(self, dst as u64, len as u64);
+        // SAFETY (both): an open list; live buffers (the list holds the
+        // copies and its scratch memory), ranges inside them.
+        unsafe { wait_for_all(host, &self.list) };
+        match (&own, &scratch) {
+            (Some(from), _) => {
+                from.refresh(self, src as u64, len as u64);
+                let offset = from.offset(src as u64);
+                if from.buffer.as_raw() == to.buffer.as_raw() {
+                    let Some(between) = self.between(host, len as u64) else {
+                        return false;
+                    };
+                    unsafe {
+                        self.list.CopyBufferRegion(&between, 0, &from.buffer, offset, len as u64);
+                        self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
+                        wait_for_all(host, &self.list);
+                        self.list.CopyBufferRegion(&to.buffer, at, &between, 0, len as u64);
+                    }
+                } else {
+                    unsafe { self.list.CopyBufferRegion(&to.buffer, at, &from.buffer, offset, len as u64) };
+                }
+                STATS[2].fetch_add(1, Ordering::Relaxed);
+            }
+            (None, Some((from, offset, _))) => unsafe {
+                self.list.CopyBufferRegion(&to.buffer, at, from, *offset, len as u64);
+            },
+            (None, None) => return false,
+        }
+        unsafe { wait_for_all(host, &self.list) };
+        STATS[0].fetch_add(1, Ordering::Relaxed);
+        STATS[1].fetch_add(len as u64, Ordering::Relaxed);
+        to.gpu_writes(self, dst as u64, len as u64);
+        let mut deferred = self.deferred();
+        deferred.copies.push(Step::Placed(Placed {
+            dst,
+            src,
+            len,
+            shadow: to,
+            from: scratch.map(|s| s.2 as usize),
+        }));
+        deferred.refreshed.clear();
+        true
+    }
+
+    /// For a copy of `[src, src + len)` into a texture: a buffer (readable by
+    /// copies) that holds what shaders wrote there, at this place of the list.
+    /// `None` where shaders do not write it.
+    pub(crate) fn place_source(&self, src: usize, len: usize) -> Option<ID3D12Resource> {
+        if !on() {
+            return None;
+        }
+        let host = host()?;
+        let from = shaders_own(src, len)?;
+        let between = self.between(host, len as u64)?;
+        from.refresh(self, src as u64, len as u64);
+        STATS[3].fetch_add(1, Ordering::Relaxed);
+        // SAFETY: an open list; live buffers, ranges inside them.
+        unsafe {
+            wait_for_all(host, &self.list);
+            self.list.CopyBufferRegion(&between, 0, &from.buffer, from.offset(src as u64), len as u64);
+            self.list.ResourceBarrier(&[transition(&between, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
+            wait_for_all(host, &self.list);
+        }
+        Some(between)
+    }
+
+    /// A buffer on the card for this recording alone.
+    fn between(&self, host: &Host, len: u64) -> Option<ID3D12Resource> {
+        let buffer = host.uav_buffer(len.next_multiple_of(1 << 16))?;
+        name(&buffer, || "bytes between copies".into());
+        self.keep(&buffer);
+        Some(buffer)
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    /// What copies with two sides cost to make (ignored: a measurement for
+    /// `VICTORY_CARD_ALL`): buffers of 64 KiB on the card and in the PC's
+    /// memory.
+    #[test]
+    #[ignore]
+    fn small_buffers_cost() {
+        let Some(host) = super::host() else {
+            return;
+        };
+        const N: usize = 1000;
+        let used = || host.video_memory().map_or(0, |m| m[1] >> 20);
+        let before = used();
+        let t = std::time::Instant::now();
+        let card: Vec<_> = (0..N).map(|_| host.uav_buffer(1 << 16)).collect();
+        let card_us = t.elapsed().as_micros() as f64 / N as f64;
+        let after = used();
+        let t = std::time::Instant::now();
+        let pc: Vec<_> = (0..N).map(|_| host.shared_buffer(1 << 16)).collect();
+        let pc_us = t.elapsed().as_micros() as f64 / N as f64;
+        println!(
+            "{N} buffers of 64 KiB: on the card {card_us:.0} us each, {} MB of its memory; in the PC's memory {pc_us:.0} us each",
+            after.saturating_sub(before)
+        );
+        drop((card, pc));
+    }
+}

+ 235 - 0
crates/victory-gpu/src/host/upcheck.rs

@@ -954,6 +954,241 @@ mod tests {
         each_reads_its_own(256 << 10, 0x8888, std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1"));
     }
 
+    /// What a draw of `list` reads at `at`: comes to `out`.
+    fn read_out(list: &HostList, shadow: &std::sync::Arc<Shadow>, at: usize, n: usize, out: (&ID3D12Resource, u64)) {
+        shadow.refresh(list, shadow.span().0 + at as u64, n as u64);
+        // SAFETY: an open list; live buffers.
+        unsafe {
+            list.list.CopyBufferRegion(out.0, out.1, &shadow.buffer, at as u64, n as u64);
+            list.list
+                .ResourceBarrier(&[transition(&shadow.buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]);
+        }
+    }
+
+    /// Copies, shader writes and reads in random order, within lists and
+    /// across submissions in the air, the title's CPU writing sources in
+    /// between: every read sees what stands before it, and in the end title
+    /// memory and the copies hold the last of everything.
+    fn in_order(resource: usize, sizes: [usize; 3]) {
+        let Some(host) = host() else {
+            return;
+        };
+        let buffers: Vec<_> = sizes.iter().enumerate().map(|(i, &n)| title_of(resource + i, i == 0, n)).collect();
+        let slow = Slow::new(host);
+        let (out, out_data) = host.shared_buffer(1 << 20).unwrap();
+        let mut seed = 0x9e37_79b9_7f4a_7c15u64 ^ resource as u64;
+        let mut next = move |n: usize| {
+            seed ^= seed << 13;
+            seed ^= seed >> 7;
+            seed ^= seed << 17;
+            (seed >> 11) as usize % n
+        };
+        // Of each buffer: the first 4 KiB are the title's own (sources), the
+        // next 12 are written by copies and shaders.
+        const OWN: usize = 4096;
+        const ALL: usize = 16384;
+        // (Of the third only the first 4 KiB: shaders never write it.)
+        let mut model = [vec![0u8; ALL], vec![0u8; ALL], vec![0u8; ALL]];
+        let mut titles: Vec<&'static mut [u8]> = Vec::new();
+        let mut made = Vec::new();
+        for (title, start, shadow) in buffers {
+            titles.push(title);
+            made.push((start, shadow));
+        }
+        let mut lists = Vec::new();
+        for (start, shadow) in &made {
+            let all = host.new_list().unwrap();
+            shadow.refresh(&all, *start as u64, ALL as u64);
+            all.close();
+            host.execute_own(&all);
+            lists.push(all);
+        }
+        settle_now(WHY_SYNC);
+        for round in 0..150 {
+            // (offset in `out`, what was expected, where from)
+            let mut expected: Vec<(usize, Vec<u8>, String)> = Vec::new();
+            let mut told = String::new();
+            for submission in 0..1 + next(5) {
+                for _ in 0..next(6) {
+                    let (b, at) = (next(3), next(OWN / 64) * 64);
+                    let value = next(255) as u8 + 1;
+                    // (A copy with one side is what submissions in the air
+                    // read: the title's CPU waits for them, as it does.)
+                    if !made[b].1.carded() {
+                        settle_now(WHY_SYNC);
+                    }
+                    titles[b][at..at + 64].fill(value);
+                    model[b][at..at + 64].fill(value);
+                }
+                let list = host.new_list().unwrap();
+                if next(3) == 0 {
+                    slow.record(&list, 4 + next(12));
+                }
+                for op in 0..1 + next(10) {
+                    let word = |next: &mut dyn FnMut(usize) -> usize| OWN + next((ALL - OWN - 256) / 4) * 4;
+                    match next(5) {
+                        0 | 1 => {
+                            let (d, s) = (next(2), next(3));
+                            let n = 4 * (1 + next(64));
+                            let to = word(&mut next);
+                            let from = if s == 2 || next(2) == 0 { next((OWN - 256) / 4) * 4 } else { word(&mut next) };
+                            if d == s && from < to + n && to < from + n {
+                                continue;
+                            }
+                            assert!(list.place_copy(made[d].0 + to, made[s].0 + from, n), "done in the list");
+                            let bytes = model[s][from..from + n].to_vec();
+                            model[d][to..to + n].copy_from_slice(&bytes);
+                            told += &format!("\n  s{submission} op{op}: copy {d}+{to:#x} <- {s}+{from:#x} {n:#x}");
+                        }
+                        2 => {
+                            let (b, at, n) = (next(2), word(&mut next), 4 * (1 + next(32)));
+                            let value = next(255) as u8 + 1;
+                            let (start, shadow) = &made[b];
+                            shadow.refresh(&list, (*start + at) as u64, n as u64);
+                            shadow.gpu_writes(&list, (*start + at) as u64, n as u64);
+                            write(host, &list, shadow, at, &vec![value; n]);
+                            model[b][at..at + n].fill(value);
+                            told += &format!("\n  s{submission} op{op}: shader {b}+{at:#x} {n:#x} = {value:#x}");
+                        }
+                        _ => {
+                            let (b, n) = (next(2), 256);
+                            let at = if next(4) == 0 { next((OWN - 256) / 4) * 4 } else { word(&mut next) };
+                            let place = expected.len() * 256;
+                            read_out(&list, &made[b].1, at, n, (&out, place as u64));
+                            expected.push((place, model[b][at..at + n].to_vec(), format!("s{submission} op{op}: read {b}+{at:#x}")));
+                        }
+                    }
+                }
+                list.close();
+                host.execute_own(&list);
+                lists.push(list);
+            }
+            settle_now(WHY_SYNC);
+            for (at, bytes, what) in expected {
+                // SAFETY: inside the mapping; the copies into it have run.
+                let got = unsafe { std::slice::from_raw_parts(out_data.add(at), bytes.len()) };
+                if let Some(k) = (0..bytes.len()).find(|&k| got[k] != bytes[k]) {
+                    panic!("round {round}, {what}: at +{k:#x} {:#x}, not {:#x}{told}", got[k], bytes[k]);
+                }
+            }
+            for (b, title) in titles.iter().enumerate() {
+                if let Some(k) = (0..ALL).find(|&k| title[k] != model[b][k]) {
+                    panic!("round {round}: title memory {b}+{k:#x} is {:#x}, not {:#x}{told}", title[k], model[b][k]);
+                }
+            }
+            // Brought up to date by the next, the copies hold it too.
+            let list = host.new_list().unwrap();
+            for (b, (_, shadow)) in made.iter().enumerate() {
+                read_out(&list, shadow, 0, ALL, (&out, (b * ALL) as u64));
+            }
+            list.close();
+            host.execute_own(&list);
+            lists.push(list);
+            settle_now(WHY_SYNC);
+            for (b, model) in model.iter().enumerate() {
+                // SAFETY: as above.
+                let got = unsafe { std::slice::from_raw_parts(out_data.add(b * ALL), ALL) };
+                if let Some(k) = (0..ALL).find(|&k| got[k] != model[k]) {
+                    panic!("round {round}: the copy {b}+{k:#x} is {:#x}, not {:#x}{told}", got[k], model[k]);
+                }
+            }
+            if on() {
+                assert_eq!(look(host), Some(0), "round {round}");
+            }
+        }
+        eprintln!(
+            "copies at their place, bytes, out of host copies, into textures: {:?}",
+            super::place::STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect::<Vec<_>>()
+        );
+    }
+
+    /// Two buffers with two sides.
+    #[test]
+    #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
+    fn copies_stand_where_the_list_has_them_on_the_card() {
+        in_order(0x9100, [LEN, LEN, LEN]);
+    }
+
+    /// One in the card's memory, one in the PC's (one side without
+    /// `VICTORY_CARD_ALL`).
+    #[test]
+    #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
+    fn copies_stand_where_the_list_has_them_mixed() {
+        in_order(0x9200, [LEN, 256 << 10, 256 << 10]);
+    }
+
+    #[test]
+    #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
+    fn copies_stand_where_the_list_has_them_in_pc_memory() {
+        in_order(0x9300, [256 << 10, 256 << 10, LEN]);
+    }
+
+    /// As the title records it: copy, draw, copy, draw in one list; a source
+    /// a shader writes first; a counter copied to zero and counted up.
+    #[test]
+    #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
+    fn copy_draw_copy_draw() {
+        let Some(host) = host() else {
+            return;
+        };
+        let (title, start, shadow) = title_of(0x9400, true, LEN);
+        let (out, out_data) = host.shared_buffer(1 << 16).unwrap();
+        let all = host.new_list().unwrap();
+        shadow.refresh(&all, start as u64, LEN as u64);
+        all.close();
+        host.execute_own(&all);
+        settle_now(WHY_SYNC);
+        title[0..64].fill(1);
+        title[64..128].fill(2);
+        title[128..192].fill(0);
+        let list = host.new_list().unwrap();
+        const D: usize = 0x10000;
+        const S: usize = 0x20000;
+        assert!(list.place_copy(start + D, start, 64));
+        read_out(&list, &shadow, D, 64, (&out, 0));
+        assert!(list.place_copy(start + D, start + 64, 64));
+        read_out(&list, &shadow, D, 64, (&out, 64));
+        // A shader writes S, and it is copied on.
+        shadow.gpu_writes(&list, (start + S) as u64, 64);
+        write(host, &list, &shadow, S, &[7; 64]);
+        assert!(list.place_copy(start + D + 64, start + S, 64));
+        read_out(&list, &shadow, D + 64, 64, (&out, 128));
+        // Zero, counted up, taken away.
+        assert!(list.place_copy(start + D + 128, start + 128, 64));
+        shadow.gpu_writes(&list, (start + D + 128) as u64, 64);
+        write(host, &list, &shadow, D + 128, &[5; 64]);
+        assert!(list.place_copy(start + D + 192, start + D + 128, 64));
+        read_out(&list, &shadow, D + 192, 64, (&out, 192));
+        // What a copy into a texture takes of S here.
+        let between = list.place_source(start + S, 64).expect("shaders write it");
+        shadow.gpu_writes(&list, (start + S) as u64, 64);
+        write(host, &list, &shadow, S, &[9; 64]);
+        // SAFETY: an open list; live buffers.
+        unsafe { list.list.CopyBufferRegion(&out, 256, &between, 0, 64) };
+        assert!(list.place_source(start + (1 << 20), 64).is_some(), "the buffer is written");
+        // And zero for the next frame.
+        assert!(list.place_copy(start + D + 128, start + 128, 64));
+        list.close();
+        host.execute_own(&list);
+        settle_now(WHY_SYNC);
+        // SAFETY: the mapping; the copies into it have run.
+        let read = unsafe { std::slice::from_raw_parts(out_data, 320) };
+        assert_eq!(read[256], 7, "what a texture takes");
+        assert_eq!([read[0], read[64], read[128], read[192]], [1, 2, 7, 5], "what the draws read");
+        assert_eq!(
+            [title[D], title[D + 64], title[D + 128], title[D + 192], title[S]],
+            [2, 7, 0, 5, 9],
+            "title memory"
+        );
+        let holds = card(host, &shadow);
+        assert_eq!([holds[D], holds[D + 64], holds[D + 128], holds[D + 192], holds[S]], [2, 7, 0, 5, 9], "the card");
+        assert_eq!(look(host), Some(0));
+        // With the debug layer.
+        if let Some(said) = host.log_messages() {
+            eprintln!("{said}");
+        }
+    }
+
     /// Declared writes beside the title's own, in the same 64 KiB pieces and
     /// dword by dword, flights landing while later ones are in the air: in
     /// the end title memory and the card hold what each wrote last. (A byte

+ 33 - 7
crates/victory-gpu/src/list.rs

@@ -809,6 +809,20 @@ fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
     Some(unsafe { data.add(offset as usize) })
 }
 
+/// A copy of title memory that `list` records: on the card at its place in
+/// the list ([`crate::host::HostList::place_copy`]), or at submission.
+#[cfg(windows)]
+fn buffer_copy(this: This, list: &crate::host::HostList, to: *mut u8, from: *const u8, len: usize) {
+    if len == 0 {
+        return;
+    }
+    if list.place_copy(to as usize, from as usize, len) {
+        with_state(this, |_, state| state.copied());
+    } else {
+        list.defer_copy(to, from, len);
+    }
+}
+
 /// Buffer to buffer: both are host memory, copied at submission.
 extern "system" fn copy_buffer_region(
     this: This,
@@ -823,7 +837,7 @@ extern "system" fn copy_buffer_region(
         && let Some(to) = buffer_range(dst, dst_offset, len)
         && let Some(from) = buffer_range(src, src_offset, len)
     {
-        list.defer_copy(to, from, len as usize);
+        buffer_copy(this, list, to, from, len as usize);
     }
     #[cfg(not(windows))]
     let _ = (this, dst, dst_offset, src, src_offset, len);
@@ -879,7 +893,7 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) {
             crate::resource::buffer_bytes(dst),
             crate::resource::buffer_bytes(src),
         ) {
-            list.defer_copy(to, from, a.min(b) as usize);
+            buffer_copy(this, list, to, from, a.min(b) as usize);
         }
     }
     #[cfg(not(windows))]
@@ -973,12 +987,20 @@ extern "system" fn copy_texture_region(
             let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
                 return;
             };
-            let Some((buffer, staging)) = list.upload(host, bytes) else {
-                return;
+            let buffer = match list.place_source(data as usize, bytes as usize) {
+                // What shaders wrote to it, at this place of the list.
+                Some(buffer) => buffer,
+                None => {
+                    let Some((buffer, staging)) = list.upload(host, bytes) else {
+                        return;
+                    };
+                    // The list owns this mapped D3D12 upload buffer. Wine can
+                    // report its address as MEM_FREE, so use the host-upload
+                    // path.
+                    list.defer_fill_buffer(&buffer, staging, data, bytes as usize);
+                    buffer
+                }
             };
-            // The list owns this mapped D3D12 upload buffer. Wine can report
-            // its address as MEM_FREE, so use the host-upload path.
-            list.defer_fill_buffer(&buffer, staging, data, bytes as usize);
             from.resource = buffer.as_raw().cast_const().cast();
             from.footprint.offset = 0;
             #[cfg(feature = "diagnostics")]
@@ -1309,6 +1331,10 @@ extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags:
         && src != 0
     {
         let len = len as usize;
+        if list.place_copy(dst as usize, src as usize, len) {
+            with_state(this, |_, state| state.copied());
+            return;
+        }
         list.defer(move || {
             if crate::texture::committed(src as *const u8, len)
                 && crate::texture::committed(dst as *const u8, len)

+ 65 - 0
crates/victory-gpu/src/shadow.rs

@@ -73,6 +73,8 @@ pub(crate) struct Shadow {
     /// Asks for the copy that gave no length (root views: they read from
     /// their address to the copy's end, whatever lies there).
     unsized_asks: AtomicU64,
+    /// Whether shaders were ever declared to write it.
+    written: std::sync::atomic::AtomicBool,
     /// A number no other copy has had. Its address is no name for a copy:
     /// one let go and another made may share it.
     id: u64,
@@ -425,6 +427,32 @@ static WINDOW_CARD_BYTES: AtomicU64 = AtomicU64::new(0);
 /// A buffer in the card's memory for a window of `size` bytes, if it is to
 /// be there ([`window_card_most`]).
 fn window_card_for(size: u64) -> Option<ID3D12Resource> {
+    let there = window_room_for(size);
+    if there.is_some() || !windows_own() || !cards() {
+        return there;
+    }
+    // Two sides all the same, the card's in the PC's memory.
+    let host = host()?;
+    if !host.card_ready() {
+        return None;
+    }
+    let (buffer, _) = host.shared_buffer(size)?;
+    WINDOW_CARD_BYTES.fetch_add(size, Ordering::Relaxed);
+    Some(buffer)
+}
+
+/// Whether windows outside buffers have two sides too, so that submissions
+/// in the air read the bytes they were prepared with (`VICTORY_WINDOWS_OWN=1`;
+/// off by default: it takes the windows' bytes again, 3.3 GB in capture
+/// replay2, and what changes in them under submissions in the air is what the
+/// title's CPU writes, which it does not while they read it).
+fn windows_own() -> bool {
+    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_WINDOWS_OWN").is_some_and(|v| v == "1"))
+}
+
+/// [`window_card_for`] in the card's own memory.
+fn window_room_for(size: u64) -> Option<ID3D12Resource> {
     let most = window_card_most();
     if most == 0 || !cards() {
         return None;
@@ -2590,6 +2618,7 @@ impl Shadow {
             used: AtomicU64::new(crate::host::moment()),
             asked: [AtomicU64::new(u64::MAX), AtomicU64::new(0)],
             unsized_asks: AtomicU64::new(0),
+            written: Default::default(),
             id: {
                 static NEXT: AtomicU64 = AtomicU64::new(1);
                 NEXT.fetch_add(1, Ordering::Relaxed)
@@ -2625,6 +2654,7 @@ impl Shadow {
         if self.place.is_some() {
             return;
         }
+        self.written.store(true, Ordering::Relaxed);
         let len = len.min(self.left(address));
         list.defer_gpu_write(self, address as usize, len as usize);
     }
@@ -3573,6 +3603,35 @@ impl Shadow {
         card.touched.store(true, Ordering::Release);
     }
 
+    /// Whether shaders were ever declared to write it.
+    pub(crate) fn written(&self) -> bool {
+        self.written.load(Ordering::Relaxed)
+    }
+
+    /// `bytes` were put into title memory at `address`, and the submission
+    /// being prepared copies the same to the copy at that copy's place in its
+    /// list: the reference (the CPU's side of a copy in the card's memory, the
+    /// snapshot) takes them and nothing is sent. What the card makes of them
+    /// is then what differs from them when the submission has run. The range
+    /// is declared written by it, and its sends are taken.
+    pub(crate) fn placed_copy(&self, address: usize, bytes: &[u8]) {
+        let (from, to) = self.inside(address, bytes.len());
+        if from >= to || self.place.is_some() {
+            return;
+        }
+        let bytes = &bytes[self.start as usize + from - address..][..to - from];
+        let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
+        if self.card.is_some() {
+            // SAFETY: inside the mapping of the CPU's side, in a range no
+            // refresh writes; the lock keeps the landing out.
+            unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), self.data.add(from), bytes.len()) };
+        } else if let Some(snapshot) = self.before.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
+            // SAFETY: the snapshot's allocation holds the copy's length.
+            unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), snapshot.as_mut_ptr().add(from), bytes.len()) };
+        }
+        self.changed(from, to);
+    }
+
     /// Of a copy in the card's memory: where its CPU side is.
     pub(crate) fn card_data(&self) -> *const u8 {
         self.data
@@ -4254,6 +4313,12 @@ pub(crate) fn find_any(address: u64, len: u64) -> Option<Arc<Shadow>> {
     lookup(address, len, true)
 }
 
+/// The copy [`find`] gives for a range inside a title buffer, if it was made.
+pub(crate) fn peek(address: u64, len: u64) -> Option<Arc<Shadow>> {
+    let end = address.checked_add(len.max(1))?;
+    buffers().range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end).and_then(|(_, e)| e.shadow.clone())
+}
+
 fn lookup(address: u64, len: u64, any: bool) -> Option<Arc<Shadow>> {
     let end = address.checked_add(len.max(1))?;
     let mut map = buffers();