Răsfoiți Sursa

Merge local/next into day/shaders

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 1 zi în urmă
părinte
comite
393e74fb5e

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

@@ -4171,6 +4171,8 @@ fn readable(list: &HostList, kind: ResourceType, view: &View) {
         (View::Unordered(resource, _, _), ResourceType::Uav) => {
             #[cfg(feature = "diagnostics")]
             crate::capture::note_target(*resource as This);
+            // Some compute-written textures are also read by the title CPU.
+            list.texture_written(*resource as This);
             // Unordered access to a depth texture is its colour twin's.
             if !list.twin_use(*resource as This, true, true) {
                 crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);

+ 89 - 10
crates/victory-gpu/src/host.rs

@@ -2223,6 +2223,11 @@ struct Deferred {
     /// memory they go to, the bytes of a row, the rows, the title's row
     /// pitch.
     backs: Vec<(ID3D12Resource, usize, [usize; 3])>,
+    /// Title textures of the kinds copied back ([`crate::texback`]) that
+    /// the list's shaders write, copied when the list closes.
+    back_wanted: Vec<crate::texback::Target>,
+    /// Those copies, whose texels go to title memory once the list has run.
+    texture_backs: Vec<crate::texback::Back>,
     /// Whether the indirect-work budget is zeroed for this recording (a
     /// step on the CPU, or in the list for the card's copy).
     budget_zeroed: bool,
@@ -2561,6 +2566,8 @@ struct Sent {
     back: Vec<Declared>,
     /// What was taken off it to be done on the card.
     own: Option<card_steps::Taken>,
+    /// Title-memory ranges written when its shader textures are copied back.
+    texture_back_ranges: Vec<(usize, usize)>,
     /// Its bottom-of-pipe writes.
     writes: Vec<(usize, crate::queue::Written, usize)>,
 }
@@ -2578,6 +2585,7 @@ struct Flight {
     back: Vec<Declared>,
     /// The list of ours that ran ahead of them ([`card_steps`]).
     own: Option<card_steps::Taken>,
+    texture_back_ranges: Vec<(usize, usize)>,
 }
 
 /// One thing in the line of what waits for the card, in order.
@@ -2591,8 +2599,8 @@ enum Late {
 
 struct Line {
     line: Vec<Late>,
-    /// The title memory the flights' shaders may write (address, end), in
-    /// order and joined.
+    /// The title memory the flights' shaders and texture readbacks may write
+    /// (address, end), in order and joined.
     written: Vec<(usize, usize)>,
     /// Host lists in the flights.
     lists: usize,
@@ -3754,6 +3762,11 @@ pub(crate) fn walls_trace() -> bool {
 /// without it, so the title read a buffer nobody wrote, as before read-backs
 /// were made (the exposure metering's two small float targets, every frame).
 fn read_backs(list: &HostList) {
+    // Textures shaders wrote that the title reads on the CPU
+    // ([`crate::texback`]).
+    for back in &list.deferred().texture_backs {
+        crate::texback::land(back);
+    }
     for (buffer, at, [row, rows, pitch]) in &list.deferred().backs {
         let mut data = std::ptr::null_mut();
         // SAFETY: a read-back buffer of ours, written by the list that has
@@ -4169,7 +4182,9 @@ impl Host {
             }
             None => 0,
         };
+        let gathering = crate::timeline::span("copies in the card's memory: what changed");
         let mut dirty = crate::shadow::card_dirty(sent_as);
+        gathering.end();
         if declared.is_empty() && dirty.is_empty() && looked.is_empty() {
             return None;
         }
@@ -4193,11 +4208,14 @@ impl Host {
         let mut used: Vec<(bool, Prelude)> = Vec::new();
         let mut looks = None;
         // The bytes as they are now, whatever later submissions put there.
+        let taking = crate::timeline::span("copies in the card's memory: taken");
         let own = if send::own() { send::take(self, &dirty) } else { None };
+        taking.end();
         if !dirty.is_empty() {
             let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else {
                 fail(format_args!("no host list to bring host copies in the card's memory up to date"));
             };
+            let _recording = crate::timeline::span("copies in the card's memory: the list");
             let (allocator, list) = &sync;
             // SAFETY: the list's last run finished (it ran ahead of a
             // submission that was waited for, and came back after that);
@@ -4220,12 +4238,13 @@ impl Host {
                         let Some((staging, before, _)) = shadow.card_sides() else {
                             continue;
                         };
-                        for &(a, b) in ranges {
-                            if own.is_none() {
+                        if own.is_none() {
+                            for &(a, b) in ranges {
                                 list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64);
                             }
-                            crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
                         }
+                        let bytes: u64 = ranges.iter().map(|&(a, b)| (b - a) as u64).sum();
+                        crate::shadow::CARD_STATS[0].fetch_add(bytes, Ordering::Relaxed);
                         crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
                         #[cfg(feature = "diagnostics")]
                         traffic::moved(traffic::UP, shadow.span(), ranges.iter().copied());
@@ -4255,13 +4274,23 @@ impl Host {
                         // pieces and flags those whose hash is another.
                         list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
                         list.SetComputeRootUnorderedAccessView(2, before.GetGPUVirtualAddress());
+                        let joins = rehash_runs() || own.is_some();
                         let runs: Vec<crate::shadow::CardSpan> = if whole.iter().any(|s| Arc::ptr_eq(s, shadow)) {
                             vec![shadow.card_run(0, usize::MAX)]
                         } else {
-                            ranges.iter().map(|&(a, b)| shadow.card_run(a, b)).collect()
+                            // (In order: the next of the same piece, of the
+                            // tens of thousands there are, says nothing.)
+                            let mut runs: Vec<crate::shadow::CardSpan> = Vec::new();
+                            for run in ranges.iter().map(|&(a, b)| shadow.card_run(a, b)) {
+                                match runs.last_mut() {
+                                    Some(last) if joins && (last.first, last.pieces) == (run.first, run.pieces) => last.to = last.to.max(run.to),
+                                    _ => runs.push(run),
+                                }
+                            }
+                            runs
                         };
                         // The same pieces in fewer passes (`rehash_runs`).
-                        let runs = if rehash_runs() || own.is_some() { crate::shadow::joined_piece_runs(runs) } else { runs };
+                        let runs = if joins { crate::shadow::joined_piece_runs(runs) } else { runs };
                         CARD_PASSES[0].fetch_add(runs.len() as u64, Ordering::Relaxed);
                         CARD_PASSES[1].fetch_add(runs.iter().map(|r| u64::from(r.pieces)).sum::<u64>(), Ordering::Relaxed);
                         for run in runs {
@@ -4851,6 +4880,7 @@ impl Host {
                 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());
                 }
             }
             join_ranges(written, ranges);
@@ -5058,7 +5088,13 @@ impl Host {
         let most = {
             let mut line = line();
             let Line { line: items, written, lists: flying, target, .. } = &mut *line;
-            join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
+            join_ranges(
+                written,
+                sent.back
+                    .iter()
+                    .flat_map(|(_, ranges)| ranges.iter().copied())
+                    .chain(sent.texture_back_ranges.iter().copied()),
+            );
             *flying += order.len();
             *target = *submitted;
             items.push(Late::Run(Flight {
@@ -5069,6 +5105,7 @@ impl Host {
                 card: sent.card,
                 back: sent.back,
                 own: sent.own,
+                texture_back_ranges: sent.texture_back_ranges,
             }));
             items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
             *flying >= late_most()
@@ -5106,7 +5143,13 @@ impl Host {
         {
             let mut line = line();
             let Line { line: items, written, lists: flying, target, .. } = &mut *line;
-            join_ranges(written, sent.back.iter().flat_map(|(_, ranges)| ranges.iter().copied()));
+            join_ranges(
+                written,
+                sent.back
+                    .iter()
+                    .flat_map(|(_, ranges)| ranges.iter().copied())
+                    .chain(sent.texture_back_ranges.iter().copied()),
+            );
             *flying += 1;
             *target = *submitted;
             items.push(Late::Run(Flight {
@@ -5117,6 +5160,7 @@ impl Host {
                 card: sent.card,
                 back: sent.back,
                 own: sent.own,
+                texture_back_ranges: sent.texture_back_ranges,
             }));
             items.extend(sent.writes.into_iter().map(|(at, what, bytes)| Late::Write(at, what, bytes)));
         }
@@ -5584,6 +5628,10 @@ impl Host {
             #[cfg(feature = "diagnostics")]
             split.part(5);
             let back = crate::picked::with(declared, &picked.written);
+            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 writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
             SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
             submitting(0, 0);
@@ -5594,6 +5642,7 @@ impl Host {
                 card,
                 back,
                 own,
+                texture_back_ranges,
                 writes,
             };
             working(was_working);
@@ -6048,6 +6097,7 @@ impl HostList {
     pub(crate) fn close(&self) {
         let _closing = crate::timeline::span("closing a host list");
         self.twins_to_depth();
+        self.textures_back();
         let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone();
         if let Some((scratch, _)) = scratch {
             self.indirect_common(&scratch);
@@ -6364,6 +6414,34 @@ impl HostList {
         }
     }
 
+    /// A draw or dispatch being prepared writes title texture `resource`
+    /// through unordered access: if it is of a kind copied back
+    /// ([`crate::texback`]), the list copies it when it closes.
+    pub(crate) fn texture_written(&self, resource: crate::object::This) {
+        if !crate::texback::wanted(resource) {
+            return;
+        }
+        let mut deferred = self.deferred();
+        if !deferred.back_wanted.iter().any(|target| target.owner() == resource as usize)
+            && let Some(target) = crate::texback::Target::new(resource)
+        {
+            deferred.back_wanted.push(target);
+        }
+    }
+
+    /// Before the list closes: the textures its shaders wrote that are copied
+    /// back go into read-back buffers ([`crate::texback::record`]).
+    fn textures_back(&self) {
+        const COPY_SOURCE: u32 = 0x800;
+        let wanted = std::mem::take(&mut self.deferred().back_wanted);
+        for target in wanted {
+            self.settle(&target.copy, COPY_SOURCE);
+            if let Some(back) = crate::texback::record(&self.list, target) {
+                self.deferred().texture_backs.push(back);
+            }
+        }
+    }
+
     /// The draw or dispatch just prepared is recorded: the twins it writes
     /// now hold what their depth textures lack.
     pub(crate) fn twins_written(&self) {
@@ -6531,7 +6609,8 @@ impl HostList {
                 && deferred.kept.is_empty()
                 && deferred.textures.is_empty()
                 && deferred.writes.is_empty()
-                && deferred.backs.is_empty())
+                && deferred.backs.is_empty()
+                && deferred.texture_backs.is_empty())
             {
                 return false;
             }

+ 31 - 21
crates/victory-gpu/src/host/card_steps.rs

@@ -674,11 +674,13 @@ impl Host {
     }
 
     fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result<Option<Taken>, &'static str> {
+        let mut spent = crate::timeline::span("steps on the card: chosen");
         let (does, steps) = does_of(written, runs);
         let chosen = plan(&does, stage(), placed_order(), &mut None)?;
         if chosen.is_empty() {
             return Ok(None);
         }
+        spent.next("steps on the card: what holds their bytes");
         let mut writers = {
             let line = line();
             let mut all = writers(&line.line);
@@ -765,6 +767,7 @@ impl Host {
                 to,
             });
         }
+        spent.next("steps on the card: the list");
         let Some(own) = self.own_list() else {
             return Err("no host list or buffer for it");
         };
@@ -817,24 +820,28 @@ impl Host {
         own.list.close();
         // SAFETY: a live buffer.
         let gpu = unsafe { own.between.GetGPUVirtualAddress() };
-        for op in &ops {
-            DONE[2].fetch_add(op.len as u64, Ordering::Relaxed);
-            match &op.to {
-                To::Slot(heap, index) => {
-                    DONE[0].fetch_add(1, Ordering::Relaxed);
+        spent.next("steps on the card: the slots");
+        // (11,000 slots a frame in a street, two descriptors each: on
+        // several threads, a slot always on the same one, in the steps'
+        // order.)
+        let parts = if ops.len() < 256 { 1 } else { 8 };
+        crate::land::each_under(parts, &|part| {
+            for op in &ops {
+                if let To::Slot(heap, index) = &op.to
+                    && *index as usize / 4 % parts == part
+                {
                     // (A heap that is gone: nothing can read the slot.)
                     crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32);
                 }
-                To::Buffer(_) => {
-                    DONE[0].fetch_add(1, Ordering::Relaxed);
-                }
-                To::Copy(..) => {
-                    DONE[1].fetch_add(1, Ordering::Relaxed);
-                }
             }
-            #[cfg(feature = "diagnostics")]
-            noted(op);
-        }
+        });
+        let copies = ops.iter().filter(|op| matches!(op.to, To::Copy(..))).count();
+        DONE[0].fetch_add((ops.len() - copies) as u64, Ordering::Relaxed);
+        DONE[1].fetch_add(copies as u64, Ordering::Relaxed);
+        DONE[2].fetch_add(ops.iter().map(|op| op.len as u64).sum(), Ordering::Relaxed);
+        #[cfg(feature = "diagnostics")]
+        noted(&ops);
+        spent.end();
         Ok(Some(Taken {
             own,
             steps: chosen.iter().map(|&(i, _)| steps[i]).collect(),
@@ -865,14 +872,17 @@ type Noted = std::collections::HashMap<(usize, (u64, u64), (u64, u64)), (u64, us
 static NOTED: Mutex<Option<Noted>> = Mutex::new(None);
 
 #[cfg(feature = "diagnostics")]
-fn noted(op: &Op) {
-    let (to, dst) = match &op.to {
-        To::Copy(to, dst) => (to.span(), *dst),
-        To::Slot(..) | To::Buffer(_) => ((0, 0), 0),
-    };
+fn noted(ops: &[Op]) {
     let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner());
-    let e = noted.get_or_insert_with(Default::default).entry((op.len, op.from.0.span(), to)).or_default();
-    *e = (e.0 + 1, op.from.1, dst);
+    let noted = noted.get_or_insert_with(Default::default);
+    for op in ops {
+        let (to, dst) = match &op.to {
+            To::Copy(to, dst) => (to.span(), *dst),
+            To::Slot(..) | To::Buffer(_) => ((0, 0), 0),
+        };
+        let e = noted.entry((op.len, op.from.0.span(), to)).or_default();
+        *e = (e.0 + 1, op.from.1, dst);
+    }
 }
 
 /// For the frame-rate line.

+ 2 - 0
crates/victory-gpu/src/lib.rs

@@ -87,6 +87,8 @@ pub mod titlewrite;
 mod upload;
 #[cfg(windows)]
 mod watch;
+#[cfg(windows)]
+mod texback;
 
 #[cfg(windows)]
 pub use host::on_failure;

+ 36 - 1
crates/victory-gpu/src/resource.rs

@@ -2690,6 +2690,7 @@ fn hand_out_resource(
     if desc.dimension != BUFFER {
         let at = std::ptr::from_ref::<Resource>(&resource) as usize;
         textures().insert(at);
+        crate::texback::replaced(resource.data() as usize);
         if !fills(&desc) {
             TARGETS_AT
                 .lock()
@@ -2714,7 +2715,9 @@ impl Drop for Resource {
         // Out of the table of textures first: the sweep looks at the ones
         // in it, under its lock.
         if self.desc.dimension != BUFFER {
-            textures().remove(&(std::ptr::from_ref::<Resource>(self) as usize));
+            let address = std::ptr::from_ref::<Resource>(self) as usize;
+            crate::texback::released(address);
+            textures().remove(&address);
             if !fills(&self.desc) {
                 let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner());
                 let at = self.data() as u64;
@@ -2946,6 +2949,38 @@ pub(crate) fn placed_filler_twins() -> u64 {
     PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed)
 }
 
+/// Width, height and format of texture `this` (`None` for a buffer), for
+/// `crate::texback`'s kinds.
+#[cfg(windows)]
+pub(crate) fn texture_kind(this: This) -> Option<(u64, u32, u32)> {
+    if this.is_null() {
+        return None;
+    }
+    let r = resource(this);
+    const TEXTURE_2D: u32 = 3;
+    (r.desc.dimension == TEXTURE_2D && r.desc.sample_count <= 1)
+        .then_some((r.desc.width, r.desc.height, r.desc.format))
+}
+
+/// Texture `this`'s console layout (one plane), where it lies in title
+/// memory and the bytes that layout takes, for `crate::texback`; `None` for
+/// a buffer or a texture with planes.
+#[cfg(windows)]
+pub(crate) fn title_texture(this: This) -> Option<(victory_formats::texture::Layout, usize, usize)> {
+    if this.is_null() {
+        return None;
+    }
+    let r = resource(this);
+    if r.desc.dimension == BUFFER {
+        return None;
+    }
+    let t = texture_layout(&r.desc)?;
+    let [plane] = &t.planes[..] else {
+        return None;
+    };
+    Some((plane.layout.clone(), r.data() as usize, t.size as usize))
+}
+
 /// The bytes of title memory a texture with the resource description
 /// `desc` (as words) takes where the title placed it; `None` for a buffer
 /// and for a description without a size.

+ 12 - 5
crates/victory-gpu/src/shadow.rs

@@ -549,11 +549,16 @@ fn window_room_for(size: u64) -> Option<ID3D12Resource> {
 struct SentRuns(Vec<(u64, Vec<(usize, usize)>)>);
 
 impl SentRuns {
+    #[cfg(test)]
     fn note(&mut self, number: u64, ranges: Vec<(usize, usize)>) {
+        self.note_joined(number, joined(ranges));
+    }
+
+    /// `ranges` are in order and joined.
+    fn note_joined(&mut self, number: u64, ranges: Vec<(usize, usize)>) {
         if ranges.is_empty() {
             return;
         }
-        let ranges = joined(ranges);
         match self.0.iter_mut().find(|s| s.0 == number) {
             Some((_, all)) => *all = joined([std::mem::take(all), ranges].concat()),
             None => self.0.push((number, ranges)),
@@ -608,17 +613,17 @@ pub(crate) fn card_dirty(sent_as: u64) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)
             .filter(|c| c.touched.swap(false, Ordering::AcqRel))
             .map(|c| {
                 let mut dirty = c.dirty.lock().unwrap_or_else(|e| e.into_inner());
-                let ranges = std::mem::take(&mut *dirty);
+                let ranges = joined(std::mem::take(&mut *dirty));
                 if relay() {
                     let mut sent = c.sent.lock().unwrap_or_else(|e| e.into_inner());
                     sent.forget(fetched);
-                    sent.note(sent_as, ranges.clone());
+                    sent.note_joined(sent_as, ranges.clone());
                 }
                 ranges
             })
             .unwrap_or_default();
         if !ranges.is_empty() {
-            out.push((shadow, joined(ranges)));
+            out.push((shadow, ranges));
         }
         true
     });
@@ -724,7 +729,9 @@ pub(crate) fn carded_copies() -> Vec<Arc<Shadow>> {
 
 /// Ranges in order, those that overlap or touch as one.
 fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
-    ranges.sort_unstable();
+    // (The sort that finds what is in order already: they come as a few
+    // stretches of tens of thousands in order, put behind one another.)
+    ranges.sort();
     let mut out: Vec<(usize, usize)> = Vec::with_capacity(ranges.len());
     for (from, to) in ranges {
         match out.last_mut() {

+ 273 - 0
crates/victory-gpu/src/texback.rs

@@ -0,0 +1,273 @@
+//! Textures shaders write that the title's own code then reads on the CPU.
+//! On the console the CPU and the GPU share memory, so what a compute pass
+//! stores into a texture is in title memory for the CPU to read. Here it stays
+//! in the texture's host copy. The title's ocean is one: its wave passes write
+//! a 256x256 height map (R32_FLOAT) and a displacement map (R32G32_FLOAT), and
+//! its CPU code samples both, which is what boats float on; it read memory
+//! nothing had written (run rw1, `VICTORY_READ_WATCH=1`: about 30 places in
+//! the title read those two kinds), and boats sank.
+//!
+//! For textures of the kinds in `VICTORY_TEXTURE_BACK` (comma-separated
+//! `<width>x<height>f<format>`; unset or `1`: the four water formats found by
+//! the upstream trace; `0`: none), a list in which shaders write one copies it
+//! into a read-back buffer of ours when it closes, and once the list has run
+//! the texels are tiled into the texture's title memory in the console's
+//! layout, as the console's GPU would have left them.
+//!
+//! shortcut: by kind, not by texture: textures of those kinds the title never
+//! reads are copied back too (about a megabyte per such list). The copy shows
+//! what the list's last write left; a title read in between sees the frame
+//! before, as it would before the console's GPU has run.
+
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex, OnceLock, Weak};
+
+use windows::Win32::Graphics::Direct3D12::*;
+
+use crate::object::This;
+
+/// The kinds copied back: (width, height, format).
+fn kinds() -> &'static [(u64, u32, u32)] {
+    static KINDS: OnceLock<Vec<(u64, u32, u32)>> = OnceLock::new();
+    KINDS.get_or_init(|| {
+        const DEFAULT: &str = "256x256f41,256x256f16,64x64f16,128x128f36";
+        let list = match std::env::var("VICTORY_TEXTURE_BACK").as_deref() {
+            Ok("1") | Err(_) => DEFAULT.to_owned(),
+            Ok(spec) => spec.to_owned(),
+        };
+        let kinds: Vec<(u64, u32, u32)> = list
+            .split(',')
+            .filter_map(|k| {
+                let (size, format) = k.trim().split_once('f')?;
+                let (w, h) = size.split_once('x')?;
+                Some((w.parse().ok()?, h.parse().ok()?, format.parse().ok()?))
+            })
+            .collect();
+        if !kinds.is_empty() {
+            tracing::info!(?kinds, "textures of these kinds that shaders write are copied back into title memory (VICTORY_TEXTURE_BACK)");
+        }
+        kinds
+    })
+}
+
+/// Whether title texture `resource` is of a kind copied back.
+pub(crate) fn wanted(resource: This) -> bool {
+    let kinds = kinds();
+    !kinds.is_empty()
+        && crate::resource::texture_kind(resource).is_some_and(|k| kinds.contains(&k))
+}
+
+/// An outstanding write to a specific allocation. Mapping and resource
+/// changes invalidate only the writes that could touch the replaced memory.
+struct Ticket {
+    owner: usize,
+    at: usize,
+    end: usize,
+    valid: AtomicBool,
+}
+
+static TICKETS: Mutex<Vec<Weak<Ticket>>> = Mutex::new(Vec::new());
+static TRACKING: AtomicBool = AtomicBool::new(false);
+
+fn track(owner: usize, at: usize, end: usize) -> Arc<Ticket> {
+    let ticket = Arc::new(Ticket { owner, at, end, valid: AtomicBool::new(true) });
+    let mut tickets = TICKETS.lock().unwrap_or_else(|e| e.into_inner());
+    tickets.retain(|weak| weak.strong_count() != 0);
+    tickets.push(Arc::downgrade(&ticket));
+    TRACKING.store(true, Ordering::Relaxed);
+    ticket
+}
+
+fn invalidate(matches: impl Fn(&Ticket) -> bool) {
+    if !TRACKING.load(Ordering::Relaxed) {
+        return;
+    }
+    TICKETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|weak| {
+        let Some(ticket) = weak.upgrade() else { return false };
+        if matches(&ticket) {
+            ticket.valid.store(false, Ordering::Release);
+        }
+        true
+    });
+}
+
+pub(crate) fn released(owner: usize) {
+    invalidate(|ticket| ticket.owner == owner);
+}
+
+pub(crate) fn replaced(at: usize) {
+    invalidate(|ticket| ticket.at == at);
+}
+
+pub(crate) fn remapped(at: usize, len: usize) {
+    let end = at.saturating_add(len);
+    invalidate(|ticket| at < ticket.end && ticket.at < end);
+}
+
+pub(crate) struct Target {
+    pub(crate) copy: Arc<crate::resource::HostTexture>,
+    layout: victory_formats::texture::Layout,
+    ticket: Arc<Ticket>,
+}
+
+impl Target {
+    pub(crate) fn new(resource: This) -> Option<Self> {
+        // Keep the host copy independently of the title's resource lifetime.
+        let copy = crate::resource::host_copy(resource)?;
+        let _mapping = crate::watch::title_memory_reading();
+        let (layout, at, size) = crate::resource::title_texture(resource)?;
+        let end = at.checked_add(size).filter(|&end| at != 0 && end > at)?;
+        let ticket = track(resource as usize, at, end);
+        Some(Self { copy, layout, ticket })
+    }
+
+    pub(crate) fn owner(&self) -> usize { self.ticket.owner }
+}
+
+/// The readback resources and the allocation the pixels belong to.
+pub(crate) struct Back {
+    buffer: ID3D12Resource,
+    footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
+    rows: Vec<u32>,
+    mips: u32,
+    layout: victory_formats::texture::Layout,
+    ticket: Arc<Ticket>,
+}
+
+impl Back {
+    pub(crate) fn range(&self) -> (usize, usize) {
+        (self.ticket.at, self.ticket.end)
+    }
+}
+
+/// Records a host copy from a texture already in COPY_SOURCE.
+pub(crate) fn record(list: &ID3D12GraphicsCommandList, target: Target) -> Option<Back> {
+    if !target.ticket.valid.load(Ordering::Acquire) {
+        return None;
+    }
+    let host = crate::host::host()?;
+    let texture = &target.copy.texture;
+    // SAFETY: a live texture kept through the command list's state tracking.
+    let desc = unsafe { texture.GetDesc() };
+    let mips = u32::from(desc.MipLevels.max(1));
+    let subresources = mips * u32::from(desc.DepthOrArraySize.max(1));
+    let n = subresources as usize;
+    let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n];
+    let mut rows = vec![0u32; n];
+    let mut total = 0u64;
+    // SAFETY: out arrays of `n` entries.
+    unsafe {
+        host.device.GetCopyableFootprints(
+            &desc,
+            0,
+            subresources,
+            0,
+            Some(footprints.as_mut_ptr()),
+            Some(rows.as_mut_ptr()),
+            None,
+            Some(&mut total),
+        )
+    };
+    // The last footprint's advertised extent can omit row-end padding.
+    // The tiler reads a pitched slice, so the mapped buffer must include it.
+    for (footprint, &rows) in footprints.iter().zip(&rows) {
+        let format = footprint.Footprint;
+        let pitched = u64::from(format.RowPitch)
+            .checked_mul(u64::from(rows))?
+            .checked_mul(u64::from(format.Depth))?;
+        total = total.max(footprint.Offset.checked_add(pitched)?);
+    }
+    let buffer = host.read_back_buffer(total)?;
+    for (i, footprint) in footprints.iter().enumerate() {
+        let to = D3D12_TEXTURE_COPY_LOCATION {
+            // SAFETY: a borrowed pointer the location never releases.
+            pResource: unsafe { std::mem::transmute_copy(&buffer) },
+            Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
+            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: *footprint },
+        };
+        let from = D3D12_TEXTURE_COPY_LOCATION {
+            // SAFETY: as above.
+            pResource: unsafe { std::mem::transmute_copy(texture) },
+            Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
+            Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: i as u32 },
+        };
+        // SAFETY: an open list; the texture is in the copy-source state.
+        unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
+    }
+    Some(Back { buffer, footprints, rows, mips, layout: target.layout, ticket: target.ticket })
+}
+
+/// Once the list has run, tile its texels back into the same title allocation.
+pub(crate) fn land(back: &Back) {
+    static COPIED: AtomicU64 = AtomicU64::new(0);
+    static STALE: AtomicU64 = AtomicU64::new(0);
+    let _mapping = crate::watch::title_memory_reading();
+    let _ticket_guard = TICKETS.lock().unwrap_or_else(|e| e.into_inner());
+    if !back.ticket.valid.load(Ordering::Acquire) {
+        let skipped = STALE.fetch_add(1, Ordering::Relaxed) + 1;
+        if skipped.is_power_of_two() {
+            tracing::info!(skipped, "skipping texture readbacks whose title allocation changed");
+        }
+        return;
+    }
+    let (at, end) = back.range();
+    let size = end - at;
+    let mut tiled = vec![0u8; size];
+    // Keep title bytes the subresources do not cover.
+    if !crate::host::read_into(at as *const u8, &mut tiled) {
+        return;
+    }
+    let mut data = std::ptr::null_mut();
+    // SAFETY: our read-back buffer, written by the list that has run.
+    unsafe {
+        if back.buffer.Map(0, None, Some(&mut data)).is_err() || data.is_null() {
+            return;
+        }
+    }
+    for (i, (footprint, &rows)) in back.footprints.iter().zip(&back.rows).enumerate() {
+        let (mip, slice) = (i as u32 % back.mips, i as u32 / back.mips);
+        let f = footprint.Footprint;
+        let pitch = f.RowPitch as usize;
+        let len = pitch * rows as usize * f.Depth as usize;
+        // SAFETY: the subresource's part of the mapped buffer.
+        let linear = unsafe { std::slice::from_raw_parts(data.cast::<u8>().add(footprint.Offset as usize), len) };
+        if let Err(e) = back.layout.tile(&mut tiled, mip, slice, linear, pitch, pitch * rows as usize) {
+            static ONCE: std::sync::Once = std::sync::Once::new();
+            ONCE.call_once(|| tracing::warn!(?e, mip, slice, "a texture copied back could not be tiled"));
+            // SAFETY: mapped above.
+            unsafe { back.buffer.Unmap(0, None) };
+            return;
+        }
+    }
+    // SAFETY: mapped above.
+    unsafe { back.buffer.Unmap(0, None) };
+    crate::host::copy_mapped(at as *mut u8, tiled.as_ptr(), size, true);
+    let copied = COPIED.fetch_add(1, Ordering::Relaxed) + 1;
+    if copied == 1 || copied.is_multiple_of(128) {
+        tracing::info!(copied, bytes = size, "texture readback landed");
+    }
+}
+
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn only_readbacks_for_changed_allocations_are_invalidated() {
+        let first = track(91, 0x1000, 0x2000);
+        let next = track(92, 0x2000, 0x3000);
+        let far = track(93, 0x4000, 0x5000);
+
+        remapped(0x0f00, 0x200);
+        assert!(!first.valid.load(Ordering::Acquire));
+        assert!(next.valid.load(Ordering::Acquire));
+        replaced(0x2000);
+        assert!(!next.valid.load(Ordering::Acquire));
+        assert!(far.valid.load(Ordering::Acquire));
+
+        released(93);
+        assert!(!far.valid.load(Ordering::Acquire));
+        assert!(track(94, 0x2000, 0x3000).valid.load(Ordering::Acquire));
+    }
+}

+ 37 - 13
crates/victory-gpu/src/watch.rs

@@ -1120,7 +1120,11 @@ pub(crate) fn guarded(start: usize, end: usize) -> bool {
 /// Whether nothing of `[start, end)` can have been written since an asking
 /// noted it in the journal ([`PUBLISHED`]).
 fn published(start: usize, end: usize) -> bool {
-    light() && PUBLISHED.all(start / BLOCK, end.div_ceil(BLOCK))
+    let (first, last) = (start / BLOCK, end.div_ceil(BLOCK));
+    // (In this order: who puts something in beside a guard sets the one bit,
+    // then clears the other, which an asking that is publishing the block may
+    // just be setting.)
+    light() && PUBLISHED.all(first, last) && !BESIDE.any(first, last)
 }
 
 /// Since the last frame line: what asking about title memory was. Kernel
@@ -1484,7 +1488,7 @@ pub(crate) fn landed_beside(pages: &[usize], spans: &[(usize, usize)]) -> (u64,
 /// Whether every write of the title's to 64 KiB block `block` so far is in
 /// the journal ([`PUBLISHED`]).
 pub(crate) fn block_published(block: usize) -> bool {
-    light() && PUBLISHED.all(block, block + 1)
+    published(block * BLOCK, (block + 1) * BLOCK)
 }
 
 /// Whether shaders' writes went into a page of `[at, at + len)` in the last
@@ -2066,20 +2070,22 @@ pub(crate) fn views_mapped(section: usize, offset: u64, len: usize) {
     if !view_guard() {
         return;
     }
-    let mut ranges = crate::inplace::views_of_section(section, offset, len);
+    let ranges = crate::inplace::views_of_section(section, offset, len);
     // (A block is noted in `PROTECTED` ahead of the look at its page's views
     // that did not find this one yet.)
-    ranges.retain(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK)));
-    if ranges.is_empty() {
+    if !ranges.iter().any(|&(at, n)| PROTECTED.any(at / BLOCK, (at + n).div_ceil(BLOCK))) {
         return;
     }
+    // All of them, once one is guarded: another may have been made clean
+    // since that look, relying on those that are opened here. And all
+    // together: none may be writable while another is clean (who asks about
+    // that one by its bits takes no lock).
     let mut g = guards();
-    for &(at, n) in &ranges {
-        let blocks: Vec<usize> = g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect();
-        #[cfg(feature = "diagnostics")]
-        ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed);
-        unguard(&mut g, &blocks);
-    }
+    let blocks: Vec<usize> =
+        ranges.iter().flat_map(|&(at, n)| g.protected.range(at / BLOCK..(at + n).div_ceil(BLOCK)).collect::<Vec<_>>()).collect();
+    #[cfg(feature = "diagnostics")]
+    ALIASES[2].fetch_add(blocks.len() as u64, std::sync::atomic::Ordering::Relaxed);
+    unguard(&mut g, &blocks);
 }
 
 /// The runtime is about to unmap a view of which it maps a part again at
@@ -2093,7 +2099,12 @@ pub fn title_memory_splitting(at: usize, len: usize) {
         return;
     }
     let mut g = guards();
-    // (The view itself too: the part that stays is read-only until then.)
+    // (The view itself too: the part that stays is read-only until then. And
+    // all of them told as written before the first is writable.)
+    for &other in &others {
+        g.clean.remove(other / BLOCK);
+        PUBLISHED.clear(other / BLOCK);
+    }
     open(&mut g, at, at.saturating_add(len));
     for other in others {
         open(&mut g, other, other + BLOCK);
@@ -2317,6 +2328,7 @@ pub fn title_memory_reading_now() -> Option<Reading> {
 /// neither guarded nor writable) and a kernel read into it fail, so the
 /// write access is given back.
 pub fn title_memory_remapped(at: usize, len: usize) {
+    crate::texback::remapped(at, len);
     open(&mut title_memory_changed(at, len), at, at.saturating_add(len));
 }
 
@@ -2326,6 +2338,7 @@ pub fn title_memory_remapped(at: usize, len: usize) {
 /// before the unmapping would leave the address guarded, clean and known by
 /// its bits ([`PUBLISHED`]) with no view behind it.
 pub fn title_memory_unmapping(at: usize, len: usize) {
+    crate::texback::remapped(at, len);
     let mut g = title_memory_changed(at, len);
     if CHANGING.get().0 && len != 0 {
         CHANGING.set((true, true));
@@ -3896,6 +3909,8 @@ mod many_askers_tests {
                         let to = page + 1 + next((PAGES - page).min(3));
                         // Written through one view, asked about at another.
                         let (through, asked) = (all[next(VIEWS)], next(VIEWS));
+                        #[allow(unused_assignments)]
+                        let mut how = 0;
                         let (at, last) = (all[asked], &mut last[asked]);
                         if next(4) != 0 {
                             // As in the test above, or after a word of ours,
@@ -3919,6 +3934,7 @@ mod many_askers_tests {
                                 continue;
                             }
                             let reading = (next(3) == 0).then(super::title_memory_reading);
+                            how = usize::from(reading.is_some());
                             let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8));
                             if let Some(to) = beside {
                                 unsafe { (to as *mut u64).write_volatile(2) };
@@ -3926,8 +3942,10 @@ mod many_askers_tests {
                                 past.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                                 assert_eq!(unsafe { (word as *const u64).read_volatile() }, 2, "put elsewhere");
                             } else {
+                                how += 2;
                                 if next(4) == 0 {
                                     super::writing(word, 8);
+                                    how += 4;
                                 }
                                 unsafe { (word as *mut u64).write_volatile(1) };
                             }
@@ -3945,7 +3963,13 @@ mod many_askers_tests {
                         }
                         let (now, written) = writes(at + from * PAGE, at + to * PAGE, true).expect("a view");
                         let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1);
-                        assert!(number > last[page], "page {page}: {number} is not after {}", last[page]);
+                        assert!(
+                            number > last[page],
+                            "{VIEWS} views, page {page}, through {:x} ({how}), asked at {:x}: {number} is not after {}",
+                            through / PAGE + page,
+                            at / PAGE + page,
+                            last[page]
+                        );
                         for l in &mut last[from..to] {
                             *l = now;
                         }