Răsfoiți Sursa

Merge branch 'main' into fix/windows10-import-directory

ifBars 3 zile în urmă
părinte
comite
0e5953d1dd

+ 3 - 3
README.md

@@ -19,7 +19,7 @@ loads the world, where rendering fails.
 | Intro video with sound | works |
 | Start screen, profile and saves | works |
 | Loading into the world (about 50 s) | works |
-| The world (first mission's intro) | reached and runs (two minutes without a GPU failure); the picture is black, 1.5-3 s per frame |
+| The world (first mission's intro) | reached and runs with indirect draws; its title card renders, the scene after it is still dark; 0.5-1.8 s per frame |
 
 Tested on one machine: Windows 11, AMD RX 6700 XT.
 
@@ -39,7 +39,7 @@ What each part does today and what it still needs:
 | Input | XInput pads, keyboard, keyboard stand-in pad | Trigger rumble |
 | Audio | Menu, video and loading sound; XMA voices and Opus streams decode | Reverb is silent; Opus results unverified against the title |
 | GPU: menus | Draws, compute and presentation on host D3D12; only changed title memory is copied | Frame pacing drifts on one screen in release builds |
-| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped) are in | Frames are black (most geometry is drawn indirectly; untranslated shaders drop the rest); frames take seconds; real queries, depth bounds, HDR and scaling are missing |
+| GPU: world | Mesh pipelines, shader-written buffers, descriptor lifetimes, indirect execution (arguments clamped), pipelines made by worker threads and kept on disk | Most of the scene is still missing (untranslated shaders drop draws); frames take seconds; real queries, depth bounds, HDR and scaling are missing |
 | Shaders | Console GPU code recompiled to DXIL at first use, cached on disk. Menus: all. World: mesh 8,191 of 8,506, vertex/pixel 10,617 of 12,346, compute 1,643 of 2,539 | 64-bit image atomics, merged geometry stages, the ray-tracing builder's shaders; some compute programs need a GPU with 64-lane waves |
 | Textures | Console tiled layouts and detiling for the modes the title uses | Render-target metadata planes |
 | Series S mode | Runs through the menus to the loading screen | The world, as above |
@@ -114,9 +114,9 @@ cargo build --profile diag -p victory --features diagnostics   # target\diag\vic
 | `VICTORY_CAPTURE=<dir>` | saves presented frames (powers of two, or `VICTORY_CAPTURE_FRAMES=<list>`) |
 | `VICTORY_DUMP_TARGETS=1` | with the two above, saves every render target of those frames |
 | `VICTORY_D3D12_DEBUG=1` | host debug layer |
-| `VICTORY_INDIRECT=1` | runs the title's indirect draws and dispatches (off: the world's first frame stalls with it) |
 | `VICTORY_D3D12_GBV=1` | with the above, GPU-based validation (bad descriptor use reported, not faulted; slow) |
 | `VICTORY_D3D12_DRED=1` | on a GPU failure, the allocation hit and the commands in flight |
+| `VICTORY_GPU_TIMING=1` | with the above, each list of a submission run and timed on its own; slow lists logged with their slowest commands |
 | `VICTORY_D3D12_WARP=1` | host device on the software adapter (slow; cannot reset the driver) |
 | `VICTORY_AUDIO_CAPTURE=<file.wav>` | records what the title plays (our process only) |
 | `VICTORY_XMA_DUMP=<dir>` | saves the first 32 XMA voices' context and input |

+ 31 - 3
crates/victory-formats/src/texture.rs

@@ -249,6 +249,13 @@ fn spread(bits: &[u32]) -> Vec<u32> {
 
 const MAX_MIPS: u32 = 16;
 
+/// The largest width, height and depth (or array size) accepted, in texels.
+/// GFX10's image descriptors hold at most 16384 texels per side, so no
+/// texture the GPU can use is refused. The bound also keeps every size
+/// computed below within `u64` (and its `u32` steps), which unchecked
+/// values from a title would otherwise overflow.
+const MAX_EXTENT: u32 = 1 << 14;
+
 /// 256-byte micro tile dimensions by log2 element size, 2D and 3D.
 const BLOCK_256_2D: [[u32; 2]; 5] = [[16, 16], [16, 8], [8, 8], [8, 4], [4, 4]];
 const BLOCK_256_3D: [[u32; 3]; 5] = [[8, 4, 8], [4, 4, 8], [4, 4, 4], [4, 2, 4], [2, 2, 4]];
@@ -258,9 +265,9 @@ impl Layout {
     pub fn new(desc: &Desc) -> Result<Layout, Error> {
         let d = *desc;
         let block_log2 = d.swizzle.block_log2().ok_or(Error::Invalid)?;
-        let valid = d.width > 0
-            && d.height > 0
-            && d.depth > 0
+        let valid = (1..=MAX_EXTENT).contains(&d.width)
+            && (1..=MAX_EXTENT).contains(&d.height)
+            && (1..=MAX_EXTENT).contains(&d.depth)
             && (1..=MAX_MIPS).contains(&d.mips)
             && d.element_bytes.is_power_of_two()
             && d.element_bytes <= 16
@@ -838,6 +845,27 @@ mod tests {
         }
     }
 
+    /// Sizes past the hardware's 16384 texels per side are refused instead
+    /// of overflowing the size arithmetic (found by random-input testing).
+    #[test]
+    fn extents_past_the_hardware_limit_are_invalid() {
+        for swizzle in [Swizzle::LINEAR, Swizzle::SW_64KB_D_X] {
+            let largest = Layout::new(&desc(MAX_EXTENT, MAX_EXTENT, 15, 16, swizzle)).unwrap();
+            assert!(largest.size >= u64::from(MAX_EXTENT) * u64::from(MAX_EXTENT) * 16);
+            for (w, h) in [
+                (MAX_EXTENT + 1, 1),
+                (1, MAX_EXTENT + 1),
+                (u32::MAX, u32::MAX),
+            ] {
+                let result = Layout::new(&desc(w, h, 1, 16, swizzle));
+                assert_eq!(result, Err(Error::Invalid), "{w}x{h}");
+            }
+            let mut deep = desc(1, 1, 1, 16, swizzle);
+            deep.depth = u32::MAX;
+            assert_eq!(Layout::new(&deep), Err(Error::Invalid));
+        }
+    }
+
     #[test]
     fn blocks_hold_their_size_in_elements() {
         for log2 in [8u32, 12, 16] {

+ 20 - 0
crates/victory-gpu/src/descriptor/host.rs

@@ -234,6 +234,12 @@ impl HostHeap {
         Some(self.count + first as u32)
     }
 
+    /// The title slots this heap has host slots for; fewer than the title's
+    /// when the host caps its size.
+    pub(crate) fn count(&self) -> u32 {
+        self.count
+    }
+
     /// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
     /// returned).
     ///
@@ -305,6 +311,17 @@ impl HostHeap {
     /// data: a host copy of a buffer is made on first use.
     pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
         if index >= self.count {
+            // Diagnostic (NVIDIA heap cap): the highest title slot past the
+            // host heap seen so far.
+            static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+            if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index {
+                tracing::warn!(
+                    index,
+                    count = self.count,
+                    for_draw,
+                    "title slot past the host heap"
+                );
+            }
             return None;
         }
         // SAFETY: the handle is a descriptor slot in title memory.
@@ -810,6 +827,9 @@ fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) {
 }
 
 /// A view that reads zeros, for slots whose view the host cannot make.
+/// shortcut: slots with no view at all (kind unknown) get this null 2D
+/// view; null buffer views there did not stop the world's low-address
+/// page faults (2026-11-24, run w10), so they are not the cause.
 fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
     let Some(host) = host() else { return };
     let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {

+ 44 - 5
crates/victory-gpu/src/draw.rs

@@ -115,7 +115,8 @@ static DROPPED: AtomicU64 = AtomicU64::new(0);
 
 /// Marks the last traced draw as not run on the host.
 #[cfg(feature = "diagnostics")]
-fn dropped() {
+fn dropped(pipeline: usize) {
+    crate::pipeline::note_drop(pipeline as This);
     if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
         last.push_str(" DROPPED");
     }
@@ -494,6 +495,8 @@ impl State {
                 "a dispatch without a host pipeline dropped"
             );
             DROPPED.fetch_add(1, Ordering::Relaxed);
+            #[cfg(feature = "diagnostics")]
+            crate::pipeline::note_drop(self.pipeline as This);
             return;
         };
         if !p.compute {
@@ -565,7 +568,7 @@ impl State {
         if !ran {
             DROPPED.fetch_add(1, Ordering::Relaxed);
             #[cfg(feature = "diagnostics")]
-            dropped();
+            dropped(self.pipeline);
         }
     }
 
@@ -612,6 +615,27 @@ impl State {
             .filter(|u| u.kind == ResourceType::Cbv)
             .map(|u| u.slot)
             .collect();
+        // Tables reaching past a host heap smaller than the title's (the
+        // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
+        // title's slots there have no host slot of their own.
+        for u in used.iter().filter(tables) {
+            if fresh.contains(&u.slot) {
+                continue;
+            }
+            let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
+                continue;
+            };
+            let end = table + u64::from(u.table_offset_dwords) * 4;
+            let Some(heap) = self.heap_of(table) else {
+                continue;
+            };
+            let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else {
+                continue;
+            };
+            if index >= host.count() {
+                fresh.push(u.slot);
+            }
+        }
         fresh.sort_unstable();
         fresh.dedup();
         for u in used.iter().filter(tables) {
@@ -797,7 +821,7 @@ impl State {
         if !ran {
             DROPPED.fetch_add(1, Ordering::Relaxed);
             #[cfg(feature = "diagnostics")]
-            dropped();
+            dropped(self.pipeline);
         }
     }
 
@@ -884,7 +908,7 @@ impl State {
         if !ran {
             DROPPED.fetch_add(1, Ordering::Relaxed);
             #[cfg(feature = "diagnostics")]
-            dropped();
+            dropped(self.pipeline);
         }
     }
 }
@@ -907,14 +931,22 @@ impl State {
         const INDEXED: u32 = 1;
         const DISPATCH: u32 = 2;
         const MESH: u32 = 10;
+        #[cfg(feature = "diagnostics")]
+        let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
+        #[cfg(not(feature = "diagnostics"))]
+        let why = |_: &str| {};
         let len = u64::from(stride) * u64::from(max.max(1));
         let Some(args) = crate::shadow::find(arguments, len) else {
+            why("arguments outside title buffers");
             return false;
         };
         let counter = match count {
             Some(at) => match crate::shadow::find(at, 4) {
                 Some(s) => Some((s, at)),
-                None => return false,
+                None => {
+                    why("count outside title buffers");
+                    return false;
+                }
             },
             None => None,
         };
@@ -922,6 +954,7 @@ impl State {
             .then(|| host_signature(kind, stride))
             .flatten()
         else {
+            why("no host signature");
             return false;
         };
         args.refresh(list, arguments, len);
@@ -930,6 +963,7 @@ impl State {
         }
         // Bounded first: the clamp binds a compute pipeline of its own.
         if !crate::indirect::bound(list, &args.buffer, args.gpu(arguments), (kind, stride, max)) {
+            why("not bounded (no clamp, or arguments not 4-byte aligned)");
             return false;
         }
         self.host_pipeline = 0;
@@ -948,6 +982,11 @@ impl State {
         };
         if !ran {
             crate::indirect::done(list, &args.buffer);
+            #[cfg(feature = "diagnostics")]
+            match crate::pipeline::host_pipeline(self.pipeline as This) {
+                None => crate::pipeline::note_drop(self.pipeline as This),
+                Some(p) => why(&format!("prepare failed (compute {}, mesh {})", p.compute, p.mesh)),
+            }
             return false;
         }
         #[cfg(feature = "diagnostics")]

+ 170 - 15
crates/victory-gpu/src/host.rs

@@ -254,8 +254,16 @@ pub(crate) struct HostList {
     /// data without marker texts), with the host GPU range a copy reads.
     #[cfg(feature = "diagnostics")]
     notes: Mutex<Vec<Note>>,
+    /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
+    /// and at the end, and where they are read back.
+    #[cfg(feature = "diagnostics")]
+    stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
 }
 
+/// Timestamps per list (diagnostics); commands past them are not timed.
+#[cfg(feature = "diagnostics")]
+const STAMPS: u32 = 4096;
+
 /// A marker's text and the host range its command reads (diagnostics).
 #[cfg(feature = "diagnostics")]
 type Note = (String, Option<(u64, u64)>);
@@ -274,6 +282,15 @@ pub(crate) fn dred_on() -> bool {
     })
 }
 
+/// Whether each list of a submission runs and is timed on its own, slow
+/// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
+/// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
+#[cfg(feature = "diagnostics")]
+fn timing() -> bool {
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
+}
+
 /// Names a host object for the device-removed report, which names the
 /// allocations a page fault hit (only with device-removed data on).
 pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
@@ -412,42 +429,77 @@ impl Host {
                 budget: OnceLock::new(),
                 #[cfg(feature = "diagnostics")]
                 notes: Mutex::default(),
+                #[cfg(feature = "diagnostics")]
+                stamps: OnceLock::new(),
             })
         }
     }
 
     /// Runs closed lists and waits for them.
     pub(crate) fn execute(&self, runs: &[&HostList]) {
+        // One submission at a time from preparation to copy-back: snapshots
+        // and the ranges shaders write are per host copy, not per submission.
+        let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
         let started = std::time::Instant::now();
         #[cfg(feature = "diagnostics")]
         crate::copystat::add(crate::copystat::C::Submissions, 1);
         let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
+        // Where each run's lists start in `lists`.
+        let mut firsts = Vec::with_capacity(runs.len());
         let mut batch = Batch::default();
         for list in runs {
             list.run_deferred(&mut batch);
+            firsts.push(lists.len());
             if let Some(prelude) = list.prelude() {
                 lists.push(Some(prelude));
             }
             lists.push(list.list.cast().ok());
         }
         batch.flush();
-        let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
-        *submitted += 1;
         let prepared = std::time::Instant::now();
-        // SAFETY: closed lists; the fence and event are ours.
-        unsafe {
-            self.queue.ExecuteCommandLists(&lists);
-            let waited = self
-                .queue
-                .Signal(&self.fence, *submitted)
-                .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
-            match waited {
-                Ok(()) => {
-                    WaitForSingleObject(self.event, INFINITE);
+        // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
+        #[cfg(feature = "diagnostics")]
+        let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
+            firsts
+                .iter()
+                .zip(firsts.iter().skip(1).chain([&lists.len()]))
+                .map(|(&a, &b)| &lists[a..b])
+                .collect()
+        } else {
+            vec![&lists[..]]
+        };
+        #[cfg(not(feature = "diagnostics"))]
+        let groups = [&lists[..]];
+        for (i, group) in groups.iter().enumerate() {
+            *submitted += 1;
+            let started = std::time::Instant::now();
+            // SAFETY: closed lists; the fence and event are ours.
+            unsafe {
+                self.queue.ExecuteCommandLists(group);
+                let waited = self
+                    .queue
+                    .Signal(&self.fence, *submitted)
+                    .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
+                match waited {
+                    Ok(()) => {
+                        WaitForSingleObject(self.event, INFINITE);
+                    }
+                    Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
+                }
+            }
+            #[cfg(feature = "diagnostics")]
+            if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) {
+                // SAFETY: a plain query.
+                let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
+                let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
+                tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
+                for (ms, op) in runs[i].slowest(frequency, 6) {
+                    tracing::warn!("slow list command, {ms:.1} ms: {op}");
                 }
-                Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
             }
+            let _ = (i, started);
         }
+        let _ = &firsts;
         let gpu = prepared.elapsed();
         SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
         SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
@@ -677,7 +729,92 @@ impl Host {
 }
 
 impl HostList {
+    /// The timestamp heap and its read-back buffer (diagnostics, timing on).
+    #[cfg(feature = "diagnostics")]
+    fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
+        if !timing() {
+            return None;
+        }
+        self.stamps
+            .get_or_init(|| {
+                let device = &host()?.device;
+                let mut heap: Option<ID3D12QueryHeap> = None;
+                let mut back: Option<ID3D12Resource> = None;
+                let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
+                let desc = D3D12_RESOURCE_DESC {
+                    Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
+                    Width: u64::from(STAMPS) * 8,
+                    Height: 1,
+                    DepthOrArraySize: 1,
+                    MipLevels: 1,
+                    SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
+                    Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
+                    ..Default::default()
+                };
+                // SAFETY: plain object creation.
+                unsafe {
+                    device
+                        .CreateQueryHeap(
+                            &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
+                            &mut heap,
+                        )
+                        .ok()?;
+                    device
+                        .CreateCommittedResource(
+                            &readback,
+                            D3D12_HEAP_FLAG_NONE,
+                            &desc,
+                            D3D12_RESOURCE_STATE_COPY_DEST,
+                            None,
+                            &mut back,
+                        )
+                        .ok()?;
+                }
+                Some((heap?, back?))
+            })
+            .as_ref()
+    }
+
+    /// The noted commands that took longest on the GPU, longest first, as
+    /// (milliseconds, text) (diagnostics, timing on, after the list ran).
+    #[cfg(feature = "diagnostics")]
+    fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
+        let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
+        let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
+            return Vec::new();
+        };
+        let mut data = std::ptr::null_mut();
+        let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
+        // SAFETY: a read-back buffer the finished list resolved into.
+        let stamps: Vec<u64> = unsafe {
+            if back.Map(0, Some(&range), Some(&mut data)).is_err() {
+                return Vec::new();
+            }
+            let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
+            back.Unmap(0, None);
+            s
+        };
+        let mut times: Vec<(f64, String)> = (0..count)
+            .map(|i| {
+                let ticks = stamps[i + 1].saturating_sub(stamps[i]);
+                (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
+            })
+            .collect();
+        times.sort_by(|a, b| b.0.total_cmp(&a.0));
+        times.truncate(n);
+        times
+    }
+
     pub(crate) fn close(&self) {
+        #[cfg(feature = "diagnostics")]
+        if let Some((heap, back)) = self.stamps() {
+            let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
+            // SAFETY: an open list, our heap and read-back buffer.
+            unsafe {
+                self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
+                self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
+            }
+        }
         // SAFETY: our list.
         if let Err(e) = unsafe { self.list.Close() } {
             fail(format_args!(
@@ -790,6 +927,11 @@ impl HostList {
     #[cfg(feature = "diagnostics")]
     fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
         if dred_on() {
+            let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
+            if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
+                // SAFETY: an open list and our query heap.
+                unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
+            }
             let what = what();
             let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
             const UNICODE: u32 = 0;
@@ -1280,16 +1422,29 @@ impl Meter {
         });
         let dropped = crate::draw::take_dropped() as f64 / frames;
         let indirect = crate::list::take_indirect() as f64 / frames;
+        // Over the same frames as the counts above.
+        #[cfg(feature = "diagnostics")]
+        let drops = crate::pipeline::take_drops();
         if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
             self.logged = std::time::Instant::now();
             tracing::info!(
                 "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
                  {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
                  GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
-                 dropped {dropped:.0} without a host pipeline and {indirect:.0} indirect"
+                 dropped {dropped:.0} without a host pipeline ({making} being made) and \
+                 {indirect:.0} indirect",
+                making = crate::pipeline::making()
             );
             #[cfg(feature = "diagnostics")]
-            crate::copystat::log(frames);
+            {
+                crate::copystat::log(frames);
+                for (why, n) in drops.iter().take(40) {
+                    tracing::info!(
+                        "dropped {:.1}/frame without a host pipeline: {why}",
+                        *n as f64 / frames
+                    );
+                }
+            }
         }
         if self.caption.is_none() {
             // The window's own text, read without a message.

+ 15 - 7
crates/victory-gpu/src/indirect.rs

@@ -6,13 +6,15 @@
 //! just before its execution, by a compute shader of ours (HLSL compiled by
 //! the system's compiler; a 5.1 shader with its root signature inside).
 //!
-//! Each list also has a budget (2^28 vertex instances or threads, mesh
-//! groups counted as 128): records past it run empty, so a list of
-//! thousands of garbage records cannot run for seconds either.
+//! Each list also has a budget (2^27 vertex instances or threads, groups
+//! counted as 64 threads, mesh groups as 128): records past it run empty,
+//! so a list of thousands of garbage records cannot run for seconds
+//! either.
 //!
 //! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
-//! groups per dimension, one-dimensional mesh dispatches, the budget) cut
-//! legitimate work beyond them; raise them if the title needs more.
+//! groups per dimension and 2^20 per dispatch, one-dimensional mesh
+//! dispatches, the budget) cut legitimate work beyond them; raise them if
+//! the title needs more.
 
 use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
 use windows::Win32::Graphics::Direct3D::ID3DBlob;
@@ -28,7 +30,9 @@ RWByteAddressBuffer args : register(u0);
 // The list's work so far (vertex instances, threads): past the budget,
 // records run empty.
 RWByteAddressBuffer budget : register(u1);
-static const uint BUDGET = 1u << 28;
+static const uint BUDGET = 1u << 27;
+// Groups of one dispatch; more run empty.
+static const uint GROUPS = 1u << 20;
 [RootSignature(RS)]
 [numthreads(64, 1, 1)]
 void main(uint3 id : SV_DispatchThreadID) {
@@ -43,7 +47,11 @@ void main(uint3 id : SV_DispatchThreadID) {
         args.Store2(at, uint2(count, instances));
     } else if (kind == 2) {
         uint3 g = min(args.Load3(at), uint3(65535, 65535, 65535));
-        cost = min(g.x * g.y * g.z, 1u << 20) * 64;
+        // x * y fits 32 bits; the whole count may not.
+        if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
+            g = uint3(0, 0, 0);
+        }
+        cost = g.x * g.y * g.z * 64;
         args.Store3(at, g);
     } else {
         // Mesh dispatches: the console's are one-dimensional.

+ 19 - 18
crates/victory-gpu/src/list.rs

@@ -1129,14 +1129,14 @@ extern "system" fn draw(_: This) {
 }
 
 /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
-/// offset)`. Grand Theft Auto VI's signatures (2026-11-23) hold one
-/// argument each: draw (stride 16), indexed draw (20), dispatch (12), mesh
-/// dispatch (12), and a console type 105 (stride 12, fields 0, 60000, 0,
-/// over its 174 MB buffer) whose meaning is unknown. Those of PC types run
+/// offset)`. Grand Theft Auto VI's signatures (title+0x2479466, 2026-11-24)
+/// hold one argument each: draw (stride 16), indexed draw (20), dispatch
+/// (12), mesh dispatch (12), and the console's single-pass dispatch, type
+/// 105 (stride 12: the three group counts; its flags live in the
+/// signature, the title passes none), run as a plain dispatch. They run
 /// through the host's indirect execution (`State::execute_indirect`).
-/// shortcut: type 105 and signatures that change root arguments are
-/// dropped (logged once per signature); decode 105 when its draws are
-/// missed.
+/// shortcut: signatures that change root arguments are dropped (logged
+/// once per signature).
 extern "system" fn execute_indirect(
     this: This,
     signature: This,
@@ -1153,22 +1153,23 @@ extern "system" fn execute_indirect(
     let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
     let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
     let mut ran = false;
-    // shortcut: off unless `VICTORY_INDIRECT` is set (diagnostics builds):
-    // with it the world presented no frame for 30 s and the title's own
-    // GPU watchdog ended it (2026-11-24, cause not found); without it the
-    // world runs, with most geometry missing.
-    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
-    let on = *ON.get_or_init(|| {
-        cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_INDIRECT").is_some()
-    });
     #[cfg(windows)]
-    if on
-        && let ([[kind, ..]], Some(address)) = (args, address)
+    if let ([[kind, ..]], Some(address)) = (args, address)
         && (count.is_null() || counter.is_some())
     {
+        const DISPATCH: u32 = 2;
+        const DISPATCH_SINGLE: u32 = 105;
+        let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind };
         with_state(this, |list, s| {
-            ran = s.execute_indirect(list, (*kind, stride, max), address, counter);
+            ran = s.execute_indirect(list, (kind, stride, max), address, counter);
         });
+    } else {
+        #[cfg(all(windows, feature = "diagnostics"))]
+        crate::pipeline::note_why(format!(
+            "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}",
+            address.is_some(),
+            count.is_null() || counter.is_some()
+        ));
     }
     if ran {
         return;

+ 72 - 15
crates/victory-gpu/src/pipeline.rs

@@ -159,11 +159,10 @@ struct Pipeline {
     shaders: Vec<Arc<Shader>>,
     /// Whether a list has bound it yet (its shaders are logged then).
     bound: std::sync::atomic::AtomicBool,
-    /// The rest of a stream's graphics state, for the host pipeline.
+    /// What its host pipeline is made from, and the host pipeline once made
+    /// (by a worker: the title may release the pipeline meanwhile).
     #[cfg(windows)]
-    graphics: Option<Box<host::GraphicsState>>,
-    #[cfg(windows)]
-    host: OnceLock<Option<host::HostPipeline>>,
+    host: Arc<make::Pending>,
 }
 const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
 
@@ -191,17 +190,56 @@ pub(crate) fn bound(this: This) {
     }
 }
 
-/// The host pipeline of a title pipeline, made on first use; `None` if one
-/// of its shaders does not translate or the host refuses it.
+/// The host pipeline of a title pipeline; `None` if one of its shaders does
+/// not translate, the host refuses it, or it is still being made (its first
+/// use starts that, see [`make`]).
 #[cfg(windows)]
 pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> {
     if this.is_null() {
         return None;
     }
-    let p = pipeline(this);
-    p.host
-        .get_or_init(|| host::HostPipeline::new(&p.shaders, p.graphics.as_deref()))
-        .as_ref()
+    make::ready(&pipeline(this).host)
+}
+
+/// Host pipelines queued and not made yet.
+#[cfg(windows)]
+pub(crate) fn making() -> u64 {
+    make::waiting()
+}
+
+/// Draws and dispatches dropped since the last [`take_drops`], by why their
+/// pipeline has no host pipeline (diagnostics).
+#[cfg(all(windows, feature = "diagnostics"))]
+static DROPS: Mutex<Option<HashMap<String, u64>>> = Mutex::new(None);
+
+/// Counts a draw or dispatch of `this` dropped for want of a host pipeline
+/// (diagnostics).
+#[cfg(all(windows, feature = "diagnostics"))]
+pub(crate) fn note_drop(this: This) {
+    let why = if this.is_null() {
+        Some("no pipeline set".to_owned())
+    } else {
+        make::missing(&pipeline(this).host)
+    };
+    if let Some(why) = why {
+        note_why(why);
+    }
+}
+
+/// Counts a draw or dispatch dropped for `why` (diagnostics).
+#[cfg(all(windows, feature = "diagnostics"))]
+pub(crate) fn note_why(why: String) {
+    let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner());
+    *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1;
+}
+
+/// The drops counted since the last call, most first (diagnostics).
+#[cfg(all(windows, feature = "diagnostics"))]
+pub(crate) fn take_drops() -> Vec<(String, u64)> {
+    let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take();
+    let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect();
+    drops.sort_by_key(|d| std::cmp::Reverse(d.1));
+    drops
 }
 
 /// The stage's container, if it has one.
@@ -222,15 +260,17 @@ fn hand_out(
     out: *mut This,
 ) -> HRESULT {
     tracing::trace!(?shaders, "pipeline state");
+    #[cfg(windows)]
+    let host = Arc::new(make::Pending::new(shaders.clone(), graphics));
+    #[cfg(windows)]
+    make::early(&host);
     let pipeline = Box::new(Pipeline {
         object: Object::new(&FUNCTIONS),
         packet: [0; 8],
+        #[cfg(windows)]
+        host,
         shaders,
         bound: std::sync::atomic::AtomicBool::new(false),
-        #[cfg(windows)]
-        graphics,
-        #[cfg(windows)]
-        host: OnceLock::new(),
     });
     object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out)
 }
@@ -398,6 +438,23 @@ static FUNCTIONS: Table<24> = {
 
 #[cfg(windows)]
 pub(crate) mod host;
+#[cfg(windows)]
+mod library;
+#[cfg(windows)]
+mod make;
+
+/// Keeps compiled host pipelines, and the list of title pipelines to start
+/// early, in `dir` (a folder of the cache) across runs.
+#[cfg(windows)]
+pub fn use_pipeline_cache(dir: std::path::PathBuf) {
+    library::use_pipeline_cache(dir);
+}
+
+/// Saves the pipeline cache now if anything was added (at the end of a run).
+#[cfg(windows)]
+pub fn save_pipeline_cache() {
+    library::save(true);
+}
 
 #[cfg(test)]
 mod tests {
@@ -499,7 +556,7 @@ mod tests {
         assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]);
         #[cfg(windows)]
         {
-            let g = pipeline(p).graphics.as_deref().unwrap();
+            let g = pipeline(p).host.graphics.as_deref().unwrap();
             assert_eq!(g.topology.0, 3);
             assert_eq!(
                 (g.targets.NumRenderTargets, g.targets.RTFormats[0].0),

+ 80 - 10
crates/victory-gpu/src/pipeline/host.rs

@@ -169,6 +169,34 @@ impl GraphicsState {
         }
     }
 
+    /// Everything the state holds, as text: part of a pipeline's name in
+    /// the library and of the key a title pipeline is started early by.
+    pub(crate) fn describe(&self) -> String {
+        let inputs: Vec<String> = self
+            .inputs
+            .iter()
+            .zip(&self.names)
+            .map(|(e, name)| {
+                format!(
+                    "{name:?} {} {} {} {} {} {}",
+                    e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate
+                )
+            })
+            .collect();
+        format!(
+            "{:?} {} {:?} {:?} {inputs:?} {} {} {:?} {} {:?}",
+            self.blend,
+            self.sample_mask,
+            self.rasterizer,
+            self.depth,
+            self.strip_cut.0,
+            self.topology.0,
+            self.targets,
+            self.depth_format.0,
+            self.samples
+        )
+    }
+
     /// The vertex buffer slots the input layout reads.
     fn slots(&self) -> u32 {
         self.inputs
@@ -373,7 +401,7 @@ impl HostPipeline {
             }
             bound.push(stage);
         }
-        let root = match root_signature(&host.device, &params, &samplers, compute.is_some()) {
+        let (root, root_blob) = match root_signature(&host.device, &params, &samplers, compute.is_some()) {
             Ok(root) => root,
             Err(e) => {
                 tracing::warn!(error = %e, ?shaders, "host root signature refused");
@@ -396,8 +424,15 @@ impl HostPipeline {
                 CS: code(0),
                 ..Default::default()
             };
-            // SAFETY: the description points at live data.
-            let pso = match unsafe { host.device.CreateComputePipelineState(&desc) } {
+            let name = super::library::name("compute", &root_blob, &[&code_bytes(&code(0))], "");
+            let made = super::library::pipeline(
+                &name,
+                // SAFETY: the description points at live data.
+                |library, name| unsafe { library.LoadComputePipeline(name, &desc) },
+                // SAFETY: as above.
+                || unsafe { host.device.CreateComputePipelineState(&desc) },
+            );
+            let pso = match made {
                 Ok(pso) => pso,
                 Err(e) => {
                     tracing::warn!(error = %e, ?shaders, "host pipeline refused");
@@ -421,8 +456,15 @@ impl HostPipeline {
         let Some(g) = g else {
             return refuse("graphics state not kept (plain description)", shaders);
         };
+        let state = g.describe();
         if mesh.is_some() {
-            let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g) {
+            let name = super::library::name(
+                "mesh",
+                &root_blob,
+                &[&code_bytes(&code(0)), &code_bytes(&code(1))],
+                &state,
+            );
+            let pso = match mesh_pipeline(&host.device, &root, code(0), code(1), g, &name) {
                 Ok(pso) => pso,
                 Err(e) => {
                     tracing::warn!(error = %e, ?shaders, "host mesh pipeline refused");
@@ -470,8 +512,20 @@ impl HostPipeline {
             SampleDesc: g.samples,
             ..Default::default()
         };
-        // SAFETY: the description points at live data.
-        let pso = match unsafe { host.device.CreateGraphicsPipelineState(&desc) } {
+        let name = super::library::name(
+            "graphics",
+            &root_blob,
+            &[&code_bytes(&code(0)), &code_bytes(&code(1))],
+            &state,
+        );
+        let made = super::library::pipeline(
+            &name,
+            // SAFETY: the description points at live data.
+            |library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) },
+            // SAFETY: as above.
+            || unsafe { host.device.CreateGraphicsPipelineState(&desc) },
+        );
+        let pso = match made {
             Ok(pso) => pso,
             Err(e) => {
                 tracing::warn!(error = %e, ?shaders, "host pipeline refused");
@@ -511,6 +565,7 @@ fn mesh_pipeline(
     ms: D3D12_SHADER_BYTECODE,
     ps: D3D12_SHADER_BYTECODE,
     g: &GraphicsState,
+    name: &str,
 ) -> windows::core::Result<ID3D12PipelineState> {
     use windows::core::Interface;
     /// A stream subobject: its type, then its description, pointer-aligned.
@@ -545,8 +600,23 @@ fn mesh_pipeline(
         SizeInBytes: size_of::<Stream>(),
         pPipelineStateSubobjectStream: (&raw mut stream).cast(),
     };
-    // SAFETY: the stream holds whole subobjects pointing at live data.
-    unsafe { device.cast::<ID3D12Device2>()?.CreatePipelineState(&desc) }
+    let device = device.cast::<ID3D12Device2>()?;
+    super::library::pipeline(
+        name,
+        // SAFETY: the stream holds whole subobjects pointing at live data.
+        |library, name| unsafe { library.LoadPipeline(name, &desc) },
+        // SAFETY: as above.
+        || unsafe { device.CreatePipelineState(&desc) },
+    )
+}
+
+/// The bytes of shader code (none for an absent stage).
+fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec<u8> {
+    if code.pShaderBytecode.is_null() {
+        return Vec::new();
+    }
+    // SAFETY: a translation's own bytes, alive while its shader is.
+    unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::<u8>(), code.BytecodeLength) }.to_vec()
 }
 
 fn root_signature(
@@ -554,7 +624,7 @@ fn root_signature(
     params: &[D3D12_ROOT_PARAMETER1],
     samplers: &[D3D12_STATIC_SAMPLER_DESC],
     compute: bool,
-) -> windows::core::Result<ID3D12RootSignature> {
+) -> windows::core::Result<(ID3D12RootSignature, Vec<u8>)> {
     let input = if compute {
         D3D12_ROOT_SIGNATURE_FLAG_NONE
     } else {
@@ -592,6 +662,6 @@ fn root_signature(
         let blob = blob.ok_or_else(windows::core::Error::empty)?;
         let bytes =
             std::slice::from_raw_parts(blob.GetBufferPointer().cast::<u8>(), blob.GetBufferSize());
-        device.CreateRootSignature(0, bytes)
+        Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec()))
     }
 }

+ 254 - 0
crates/victory-gpu/src/pipeline/library.rs

@@ -0,0 +1,254 @@
+//! Compiled host pipelines kept on disk, and the title pipelines worth
+//! starting early (decision 0007, "Pipeline cache").
+//!
+//! 1. Every host pipeline goes into the host's pipeline library, named by
+//!    a hash of all that its host description holds (the translated
+//!    shaders' code, which changes when a translation does, our root
+//!    signature, the graphics state). The library is saved under the cache
+//!    folder; the host refuses a library of another adapter or driver, and
+//!    an entry whose description differs, so neither is ever used.
+//! 2. The title pipelines a run drew or dispatched with are listed by a key
+//!    known when the title creates them (their shader containers and
+//!    graphics state); the next run hands those to the workers at
+//!    creation, during loading.
+//!
+//! All library calls are serialised: the interface does not promise that
+//! stores, loads and serialising may overlap.
+
+use std::collections::HashSet;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Mutex, OnceLock};
+
+use windows::Win32::Graphics::Direct3D12::*;
+use windows::core::{HSTRING, Interface, PCWSTR};
+
+static DIR: OnceLock<PathBuf> = OnceLock::new();
+
+/// Keeps the pipeline library and the early list in `dir` from now on.
+pub fn use_pipeline_cache(dir: PathBuf) {
+    let _ = DIR.set(dir);
+}
+
+/// Host pipelines created, loaded from the library, and title pipelines
+/// started at creation, since the start.
+pub(crate) static MADE: AtomicU64 = AtomicU64::new(0);
+pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0);
+pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0);
+
+struct Library {
+    library: ID3D12PipelineLibrary1,
+    /// The blob the library was made from: it must outlive the library.
+    _blob: Vec<u8>,
+    /// Pipelines stored since the last save.
+    added: u64,
+}
+
+// SAFETY: D3D12 objects are free-threaded; every call is made under the
+// mutex that holds the library.
+unsafe impl Send for Library {}
+
+const LIBRARY_FILE: &str = "host-pipelines.bin";
+const EARLY_FILE: &str = "early-pipelines.txt";
+/// Title pipelines listed for an early start, at most.
+const EARLY_MAX: usize = 8192;
+
+fn library() -> Option<&'static Mutex<Library>> {
+    static LIBRARY: OnceLock<Option<Mutex<Library>>> = OnceLock::new();
+    LIBRARY
+        .get_or_init(|| {
+            let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?;
+            let blob = DIR
+                .get()
+                .and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok())
+                .unwrap_or_default();
+            let library = open(&device, blob);
+            if library.is_none() {
+                tracing::warn!("no host pipeline library: pipelines are not kept");
+            }
+            library.map(Mutex::new)
+        })
+        .as_ref()
+}
+
+/// The library in `blob`, or an empty one if the host rejects the blob (an
+/// adapter or driver change, damage).
+fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
+    let make = |bytes: &[u8]| -> windows::core::Result<ID3D12PipelineLibrary1> {
+        // SAFETY: the bytes outlive the library (kept beside it).
+        unsafe {
+            device.CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)?.cast()
+        }
+    };
+    if !blob.is_empty() {
+        match make(&blob) {
+            Ok(library) => {
+                tracing::info!(bytes = blob.len(), "host pipeline library loaded");
+                return Some(Library { library, _blob: blob, added: 0 });
+            }
+            Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"),
+        }
+    } else {
+        tracing::info!("no host pipeline library yet; starting an empty one");
+    }
+    let library = make(&[]).ok()?;
+    Some(Library { library, _blob: Vec::new(), added: 0 })
+}
+
+/// A pipeline's name in the library: the hash of what its host
+/// description holds.
+pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String {
+    let mut h = blake3::Hasher::new();
+    for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) {
+        h.update(&(part.len() as u64).to_le_bytes());
+        h.update(part);
+    }
+    h.finalize().to_hex()[..32].to_owned()
+}
+
+/// The pipeline named `name`: loaded from the library by `load` if it is
+/// there with the same description, else made by `create` and stored.
+pub(crate) fn pipeline(
+    name: &str,
+    load: impl FnOnce(&ID3D12PipelineLibrary1, PCWSTR) -> windows::core::Result<ID3D12PipelineState>,
+    create: impl FnOnce() -> windows::core::Result<ID3D12PipelineState>,
+) -> windows::core::Result<ID3D12PipelineState> {
+    let wide = HSTRING::from(name);
+    let Some(library) = library() else {
+        MADE.fetch_add(1, Ordering::Relaxed);
+        return create();
+    };
+    if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) {
+        LOADED.fetch_add(1, Ordering::Relaxed);
+        return Ok(pso);
+    }
+    // Compiled outside the lock: compiles take up to seconds.
+    let pso = create()?;
+    MADE.fetch_add(1, Ordering::Relaxed);
+    let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
+    // SAFETY: a live pipeline; a name already stored (a description that
+    // differs) is refused, which leaves the library as it was.
+    if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
+        l.added += 1;
+    }
+    Ok(pso)
+}
+
+/// Writes the library and the early list if pipelines were added since the
+/// last save and `SAVE_EVERY` has passed (or `now`).
+pub(crate) fn save(now: bool) {
+    static LAST: Mutex<Option<std::time::Instant>> = Mutex::new(None);
+    const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20);
+    let (Some(dir), Some(library)) = (DIR.get(), library()) else { return };
+    {
+        let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
+        if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) {
+            return;
+        }
+        *last = Some(std::time::Instant::now());
+    }
+    let blob = {
+        let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
+        if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) {
+            return;
+        }
+        // SAFETY: a buffer of the size the library asks for.
+        let bytes = unsafe {
+            let mut bytes = vec![0u8; l.library.GetSerializedSize()];
+            l.library.Serialize(&mut bytes).map(|()| bytes)
+        };
+        match bytes {
+            Ok(bytes) => {
+                l.added = 0;
+                bytes
+            }
+            Err(e) => {
+                tracing::warn!(error = %e, "host pipeline library not serialised");
+                return;
+            }
+        }
+    };
+    let used: Vec<String> = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect();
+    let written = std::fs::create_dir_all(dir)
+        .and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob))
+        .and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()));
+    match written {
+        Ok(()) => tracing::info!(
+            bytes = blob.len(),
+            early = used.len(),
+            made = MADE.load(Ordering::Relaxed),
+            loaded = LOADED.load(Ordering::Relaxed),
+            started_early = EARLY.load(Ordering::Relaxed),
+            "host pipeline library saved"
+        ),
+        Err(e) => tracing::warn!(error = %e, "host pipeline library not saved"),
+    }
+}
+
+/// Writes `bytes` to a temporary file beside `path`, then renames it over
+/// `path`: a reader never sees a part.
+fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
+    let tmp = path.with_extension("tmp");
+    std::fs::write(&tmp, bytes)?;
+    std::fs::rename(&tmp, path)
+}
+
+/// Title pipeline keys drawn or dispatched with (this run and the last).
+static USED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
+static USED_CHANGED: AtomicBool = AtomicBool::new(false);
+
+fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> {
+    let mut used = USED.lock().unwrap_or_else(|e| e.into_inner());
+    if used.is_none() {
+        let listed = DIR
+            .get()
+            .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok())
+            .unwrap_or_default();
+        let set: HashSet<String> = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect();
+        tracing::info!(pipelines = set.len(), "title pipelines to start early");
+        *used = Some(set);
+    }
+    used
+}
+
+/// Whether the title pipeline with `key` was drawn with in an earlier run.
+pub(crate) fn wanted_early(key: &str) -> bool {
+    used().as_ref().is_some_and(|s| s.contains(key))
+}
+
+/// The title pipeline with `key` was drawn or dispatched with.
+pub(crate) fn note_used(key: &str) {
+    let mut used = used();
+    let set = used.get_or_insert_with(HashSet::new);
+    if set.len() < EARLY_MAX && set.insert(key.to_owned()) {
+        USED_CHANGED.store(true, Ordering::Relaxed);
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn names_change_with_what_goes_into_the_pipeline() {
+        let a = name("graphics", b"root", &[b"vs", b"ps"], "state");
+        assert_eq!(a, name("graphics", b"root", &[b"vs", b"ps"], "state"));
+        assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps2"], "state"));
+        assert_ne!(a, name("graphics", b"root", &[b"vs", b"ps"], "state2"));
+        assert_ne!(a, name("graphics", b"root2", &[b"vs", b"ps"], "state"));
+        assert_ne!(a, name("mesh", b"root", &[b"vs", b"ps"], "state"));
+        // Parts do not run into each other.
+        assert_ne!(a, name("graphics", b"root", &[b"vsp", b"s"], "state"));
+    }
+
+    #[test]
+    fn a_rejected_blob_gives_an_empty_library() {
+        let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else {
+            return; // no host GPU here
+        };
+        let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library");
+        // SAFETY: a plain query on a live library.
+        assert!(unsafe { library.library.GetSerializedSize() } > 0);
+        assert!(library._blob.is_empty());
+    }
+}

+ 238 - 0
crates/victory-gpu/src/pipeline/make.rs

@@ -0,0 +1,238 @@
+//! Host pipelines are made by workers, not by the title thread that first
+//! records a draw with them. Translating a shader and the host driver's
+//! compile take from milliseconds to seconds each (structurisation of the
+//! biggest compute programs ~0.4 s, some driver compiles 3.4 s), and Grand
+//! Theft Auto VI's first world frame wants over 1,200 new pipelines: made
+//! on its recording threads, that frame took more than 30 s and the
+//! title's GPU watchdog ended the run (decision 0007, "Pipelines made off
+//! the title's threads").
+//!
+//! A first use queues the pipeline and waits for it within a budget per
+//! frame, so the cheap ones (menus, one-off passes such as a colour-grading
+//! bake) are there at once as before; past the budget a draw or dispatch
+//! whose pipeline is not ready is dropped, as an untranslated one is.
+//!
+//! shortcut: the budget (half a second of waiting per title frame) is a
+//! guess; a pass the title runs only once and whose pipeline takes longer
+//! is lost.
+
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Condvar, Mutex, OnceLock};
+use std::time::{Duration, Instant};
+
+use super::Shader;
+use super::host::{GraphicsState, HostPipeline};
+
+/// What a host pipeline is made from, and the host pipeline once made.
+pub(crate) struct Pending {
+    shaders: Vec<Arc<Shader>>,
+    pub(crate) graphics: Option<Box<GraphicsState>>,
+    queued: AtomicBool,
+    made: OnceLock<Option<HostPipeline>>,
+    /// What identifies it across runs (shader containers and state), and
+    /// whether a draw has used it yet.
+    key: String,
+    used: AtomicBool,
+}
+
+// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
+// elements point into its own names) is only read after creation.
+unsafe impl Send for Pending {}
+// SAFETY: as above.
+unsafe impl Sync for Pending {}
+
+impl Pending {
+    pub(crate) fn new(shaders: Vec<Arc<Shader>>, graphics: Option<Box<GraphicsState>>) -> Pending {
+        let mut key = blake3::Hasher::new();
+        for s in &shaders {
+            key.update(s.stage.as_bytes());
+            key.update(s.hash.as_bytes());
+        }
+        key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
+        Pending {
+            shaders,
+            graphics,
+            queued: AtomicBool::new(false),
+            made: OnceLock::new(),
+            key: key.finalize().to_hex()[..32].to_owned(),
+            used: AtomicBool::new(false),
+        }
+    }
+
+    fn make(&self) {
+        self.made
+            .get_or_init(|| HostPipeline::new(&self.shaders, self.graphics.as_deref()));
+        let (lock, done) = &DONE;
+        let _held = lock.lock().unwrap_or_else(|e| e.into_inner());
+        done.notify_all();
+    }
+}
+
+/// Why a pipeline has no host pipeline (diagnostics): its shaders that do
+/// not translate, else "refused" or "being made"; `None` if it has one.
+#[cfg(feature = "diagnostics")]
+pub(crate) fn missing(p: &Pending) -> Option<String> {
+    match p.made.get() {
+        Some(Some(_)) => None,
+        None => Some("being made".into()),
+        Some(None) => {
+            let failed: Vec<String> = p
+                .shaders
+                .iter()
+                .filter(|s| matches!(s.translated.get(), Some(None)))
+                .map(|s| format!("{} {}", s.stage, s.hash))
+                .collect();
+            Some(if failed.is_empty() {
+                format!("refused {:?}", p.shaders)
+            } else {
+                failed.join(" + ")
+            })
+        }
+    }
+}
+
+/// Signalled whenever a worker has made a pipeline.
+static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new());
+
+/// Waiting allowed per title frame, over all threads.
+const BUDGET: Duration = Duration::from_millis(500);
+
+/// Pipelines queued and not made yet.
+static WAITING: AtomicU64 = AtomicU64::new(0);
+
+/// Pipelines queued and not made yet (for the frame line).
+pub(crate) fn waiting() -> u64 {
+    WAITING.load(Ordering::Relaxed)
+}
+
+/// The host pipeline if it is made (or is made within the frame's budget);
+/// queues it on first use.
+pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
+    if p.made.get().is_none() {
+        start(p);
+        wait(p, crate::frame::current());
+    }
+    let made = p.made.get()?.as_ref();
+    if made.is_some() && !p.used.swap(true, Ordering::Relaxed) {
+        super::library::note_used(&p.key);
+    }
+    made
+}
+
+/// Queues `p` for the workers, once.
+fn start(p: &Arc<Pending>) {
+    if !p.queued.swap(true, Ordering::Relaxed) {
+        PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
+        queue(p.clone());
+    }
+}
+
+/// At the title's creation of a pipeline: starts it at once if an earlier
+/// run drew with it (during loading, so the world's first frames find it).
+pub(crate) fn early(p: &Arc<Pending>) {
+    if !p.shaders.is_empty() && super::library::wanted_early(&p.key) {
+        super::library::EARLY.fetch_add(1, Ordering::Relaxed);
+        start(p);
+    }
+}
+
+/// Waits for `p` while frame `frame` has budget left.
+fn wait(p: &Pending, frame: u64) {
+    static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
+    static WAITED_US: AtomicU64 = AtomicU64::new(0);
+    if FRAME.swap(frame, Ordering::Relaxed) != frame {
+        WAITED_US.store(0, Ordering::Relaxed);
+    }
+    let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed)));
+    let started = Instant::now();
+    let (lock, done) = &DONE;
+    let mut held = lock.lock().unwrap_or_else(|e| e.into_inner());
+    while p.made.get().is_none() {
+        let rest = left.saturating_sub(started.elapsed());
+        if rest.is_zero() {
+            break;
+        }
+        held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0;
+    }
+    WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
+}
+
+/// Hands `p` to the workers (half the logical processors, 2 to 8), started
+/// on first use.
+fn queue(p: Arc<Pending>) {
+    static SENDER: OnceLock<std::sync::mpsc::Sender<Arc<Pending>>> = OnceLock::new();
+    let sender = SENDER.get_or_init(|| {
+        let (sender, receiver) = std::sync::mpsc::channel::<Arc<Pending>>();
+        let receiver = Arc::new(Mutex::new(receiver));
+        let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8));
+        for i in 0..workers {
+            let receiver = receiver.clone();
+            let spawned = std::thread::Builder::new()
+                .name(format!("victory-pipelines-{i}"))
+                .spawn(move || {
+                    // Below the title's own threads (loading, recording).
+                    // SAFETY: a plain call on our own thread.
+                    unsafe {
+                        use windows::Win32::System::Threading::*;
+                        let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
+                    }
+                    loop {
+                        let next = receiver.lock().unwrap_or_else(|e| e.into_inner()).recv();
+                        let Ok(p) = next else { return };
+                        p.make();
+                        if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
+                            drained();
+                        } else {
+                            super::library::save(false);
+                        }
+                    }
+                });
+            if let Err(e) = spawned {
+                tracing::warn!(error = %e, "no pipeline worker");
+            }
+        }
+        sender
+    });
+    if let Err(e) = sender.send(p) {
+        // No worker: made here instead.
+        e.0.make();
+        WAITING.fetch_sub(1, Ordering::Relaxed);
+    }
+}
+
+/// The most pipelines waiting at once since the workers last ran out.
+static PEAK: AtomicU64 = AtomicU64::new(0);
+
+/// The workers ran out of work: logged after a batch of 10 or more, and
+/// the cache saved (at most every 20 s).
+fn drained() {
+    use super::library::{EARLY, LOADED, MADE};
+    if PEAK.swap(0, Ordering::Relaxed) >= 10 {
+        tracing::info!(
+            made = MADE.load(Ordering::Relaxed),
+            loaded = LOADED.load(Ordering::Relaxed),
+            started_early = EARLY.load(Ordering::Relaxed),
+            "host pipelines all made"
+        );
+    }
+    super::library::save(false);
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    /// A first use queues the pipeline and, within the budget, gets the
+    /// worker's answer (here: no host pipeline for no shaders).
+    #[test]
+    fn first_use_is_made_by_a_worker() {
+        let p = Arc::new(Pending::new(Vec::new(), None));
+        assert!(ready(&p).is_none());
+        assert!(p.queued.load(Ordering::Relaxed));
+        let started = Instant::now();
+        while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) {
+            std::thread::yield_now();
+        }
+        assert!(matches!(p.made.get(), Some(None)));
+    }
+}

+ 132 - 26
crates/victory-gpu/src/shadow.rs

@@ -40,6 +40,39 @@ pub(crate) struct Shadow {
     /// Ranges shaders of a submission not yet copied back may be writing:
     /// title memory there is older than the copy.
     pending: Mutex<Vec<(usize, usize)>>,
+    /// The copy's bytes before the submission ran, from an offset on,
+    /// covering the ranges its shaders write: what the GPU wrote differs.
+    before: Mutex<Option<(usize, Vec<u8>)>>,
+}
+
+/// Snapshot memory kept for reuse (already touched, so no page faults).
+static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
+
+/// An empty buffer with room for `n` bytes, from the pool if it has one.
+fn pooled(n: usize) -> Vec<u8> {
+    let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
+    let fit = pool
+        .iter()
+        .enumerate()
+        .filter(|(_, v)| v.capacity() >= n)
+        .min_by_key(|(_, v)| v.capacity())
+        .map(|(i, _)| i);
+    let mut v = match fit {
+        Some(i) => pool.swap_remove(i),
+        None => Vec::with_capacity(n),
+    };
+    v.clear();
+    v
+}
+
+/// Returns a snapshot buffer to the pool (at most 8 kept, the largest).
+fn give_back(v: Vec<u8>) {
+    let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
+    pool.push(v);
+    if pool.len() > 8 {
+        pool.sort_by_key(|v| std::cmp::Reverse(v.capacity()));
+        pool.truncate(8);
+    }
 }
 
 const NOT_WATCHED: u8 = 2;
@@ -84,72 +117,145 @@ impl Shadow {
             copied: Mutex::new(vec![0; pages as usize]),
             watched: AtomicU8::new(0),
             pending: Mutex::default(),
+            before: Mutex::default(),
         }
     }
 
+    /// `[address, address + len)` cut to the buffer, as offsets in the copy.
+    fn inside(&self, address: usize, len: usize) -> (usize, usize) {
+        let (start, end) = (self.start as usize, (self.start + self.len) as usize);
+        let from = address.clamp(start, end);
+        (from - start, (address + len).clamp(from, end) - start)
+    }
+
     /// Shaders of `list` may write `[address, address + len)` of the copy
     /// (unordered access): after the list's submission has run, the range
     /// is copied back into title memory, where the title reads it; until
     /// then no refresh copies title memory over it. Call after the
     /// [`Shadow::refresh`] that gives the shaders the title's data.
     ///
-    /// shortcut: the whole range goes back after every submission that
-    /// declares it; copy back only what shaders wrote (a GPU-side dirty
-    /// mask) if big unordered-access buffers make it slow.
+    /// shortcut: what shaders wrote is found by keeping the range's bytes
+    /// before the submission (a copy per declared range and submission);
+    /// a GPU-side dirty mask would save that if big ranges make it slow.
     pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
         let len = len.min(self.left(address));
         list.defer_gpu_write(self, address as usize, len as usize);
     }
 
-    /// At submission: a submitted list's shaders write this range.
+    /// At submission, after the range's refresh: a submitted list's shaders
+    /// write this range. Its bytes are kept to tell later what the GPU wrote:
+    /// one snapshot per copy and submission, grown to cover every range the
+    /// submission declares (the world declares overlapping views of its
+    /// 174 MB heap dozens of times), in reused memory (fresh snapshots cost
+    /// ~2.3 million page faults per world frame).
     pub(crate) fn writing(&self, address: usize, len: usize) {
         self.pending
             .lock()
             .unwrap_or_else(|e| e.into_inner())
             .push((address, address + len));
+        let (from, to) = self.inside(address, len);
+        // SAFETY: inside the mapping.
+        let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) };
+        let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
+        let (start, end) = match &*before {
+            Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)),
+            None => (from, to),
+        };
+        if let Some((at, bytes)) = &*before
+            && (*at, at + bytes.len()) == (start, end)
+        {
+            return;
+        }
+        // Parts newly covered from the copy, the rest as it was taken.
+        let mut grown = pooled(end - start);
+        match before.take() {
+            Some((at, bytes)) => {
+                grown.extend_from_slice(host(start, at));
+                grown.extend_from_slice(&bytes);
+                grown.extend_from_slice(host(at + bytes.len(), end));
+                give_back(bytes);
+            }
+            None => grown.extend_from_slice(host(start, end)),
+        }
+        *before = Some((start, grown));
     }
 
-    /// After the submission ran: copies what its shaders may have written
-    /// back into title memory (unmapped pages left alone). Pages wholly
-    /// written are current in this copy, so our own write is not taken for
-    /// the title's.
-    /// Returns the bytes written.
+    /// After the submission ran: copies the bytes its shaders wrote back
+    /// into title memory (unmapped pages left alone), and only those: the
+    /// title's threads write the same buffers while the GPU runs (its
+    /// command memory shares the big GPU heap with what shaders write), and
+    /// putting back the copy's older bytes there broke the title's own
+    /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes
+    /// written.
     pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize {
+        let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner());
         let mut written = 0;
-        let (start, end) = (self.start as usize, (self.start + self.len) as usize);
-        let (from, to) = (address.max(start), (address + len).min(end));
-        if from < to {
-            // Only the pieces that differ: shaders rewrite part of what they
-            // may write, and writing title memory through the kernel (and
-            // opening guarded blocks) was the world's biggest cost (~1 s per
-            // frame for 450 MB).
+        let (from, to) = self.inside(address, len);
+        let start = self.start as usize;
+        if let Some((taken, before)) = &*snapshot
+            && *taken <= from
+            && to <= taken + before.len()
+            && from < to
+        {
+            let before = &before[from - taken..to - taken];
+            // By 64 KiB piece: the copy compared with its bytes before the
+            // submission, title memory read only where the GPU wrote.
             const PIECE: usize = 64 << 10;
             let mut title = vec![0u8; PIECE];
+            let mut synced = Vec::new();
             let mut at = from;
             while at < to {
-                let n = (PIECE - at % PIECE).min(to - at);
-                // SAFETY: inside the mapping.
-                let host = unsafe { std::slice::from_raw_parts(self.data.add(at - start), n) };
-                if !crate::host::read_into(at as *const u8, &mut title[..n]) || title[..n] != *host {
-                    crate::watch::writing(at, n);
-                    crate::host::write_mapped(at as *mut u8, host.as_ptr(), n);
-                    written += n;
+                let n = (PIECE - (start + at) % PIECE).min(to - at);
+                // SAFETY: inside the mapping; only the submitting thread
+                // writes it.
+                let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
+                let old = &before[at - from..at - from + n];
+                let title = &mut title[..n];
+                if host != old && crate::host::read_into((start + at) as *const u8, title) {
+                    // Title memory with the GPU's bytes put in; the copy
+                    // takes the title's bytes in turn.
+                    let mut changed = false;
+                    for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) {
+                        if *h != *o && *t != *h {
+                            *t = *h;
+                            changed = true;
+                        }
+                        *h = *t;
+                    }
+                    if changed {
+                        crate::watch::writing(start + at, n);
+                        crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
+                        written += n;
+                    }
+                    synced.push((start + at) / PAGE);
                 }
                 at += n;
             }
-            let (first, last) = (from.div_ceil(PAGE), to / PAGE);
+            // Pages made equal to title memory are current in the copy, so
+            // our own write is not taken for the title's; others keep what
+            // they had (a title write there shows at the next refresh).
+            let (first, last) = ((start + from).div_ceil(PAGE), (start + to) / PAGE);
             if first < last
+                && !synced.is_empty()
                 && self.watched.load(Ordering::Relaxed) != NOT_WATCHED
                 && let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true)
             {
                 let base = start / PAGE;
                 let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
-                copied[first - base..last - base].fill(now);
+                for page in synced.into_iter().filter(|p| (first..last).contains(p)) {
+                    copied[page - base] = now;
+                }
             }
         }
-        // Every submitted step that declared the range is done with it.
+        // Every submitted step that declared the range is done with it (one
+        // submission runs at a time), and the snapshot with the last range.
         let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
         pending.retain(|&r| r != (address, address + len));
+        if pending.is_empty()
+            && let Some((_, bytes)) = snapshot.take()
+        {
+            give_back(bytes);
+        }
         written
     }
 

+ 6 - 2
crates/victory-hle/src/modules/d3d12x.rs

@@ -37,10 +37,14 @@ fn host_gpu_failed(what: &str) -> ! {
 }
 
 /// Keeps the host's translations of the title's shaders in `dir` (a
-/// folder of the cache) across runs.
+/// folder of the cache) across runs, and its compiled pipelines beside it
+/// (`pipelines`).
 pub fn use_shader_cache(dir: std::path::PathBuf) {
     #[cfg(windows)]
-    victory_gpu::shader_cache::use_shader_cache(dir);
+    {
+        victory_gpu::pipeline::use_pipeline_cache(dir.with_file_name("pipelines"));
+        victory_gpu::shader_cache::use_shader_cache(dir);
+    }
     #[cfg(not(windows))]
     let _ = dir;
 }

+ 3 - 0
crates/victory-hle/src/modules/lifecycle.rs

@@ -277,6 +277,9 @@ pub fn wait_for_previous() {
 }
 
 fn end() {
+    // Compiled host pipelines kept for the next run.
+    #[cfg(windows)]
+    victory_gpu::pipeline::save_pipeline_cache();
     // SAFETY: ends this process, as the console ends a suspended title.
     unsafe { TerminateProcess(GetCurrentProcess(), 0) };
 }

+ 96 - 37
crates/victory-loader/src/threads.rs

@@ -6,9 +6,9 @@
 //! callbacks, then a DLL's `DllMain`.
 
 use std::ffi::c_void;
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
 use std::sync::{Arc, Mutex};
-use std::time::Duration;
+use std::time::{Duration, Instant};
 
 use crate::{DLL_PROCESS_DETACH, LoadedImage};
 
@@ -99,20 +99,35 @@ extern "C" fn detach_all() {
         "process exit: ending other threads, detaching title images"
     );
     EXITING.store(true, Ordering::SeqCst);
-    end_other_threads();
     // As on Windows, a lock a thread held when it ended stays taken; detach
-    // code that waits for one would hang the exit.
-    std::thread::spawn(|| {
+    // code that waits for one would hang the exit. The watchdog runs before
+    // the other threads end: a thread that ends can hold the heap lock or
+    // the loader lock, and a new thread needs both to start. After the
+    // deadline it only ends the process; it does not log, because logging
+    // needs the heap and the log writer's lock.
+    // Its thread id, set when it runs its own code; 0 until then.
+    static WATCHDOG: AtomicU32 = AtomicU32::new(0);
+    drop(std::thread::spawn(|| {
+        // SAFETY: a plain query of the calling thread.
+        let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+        WATCHDOG.store(id, Ordering::SeqCst);
         std::thread::sleep(DETACH_DEADLINE);
-        tracing::warn!("process exit: title images did not detach in time; ending");
-        // SAFETY: ends this process, which is exiting anyway.
-        unsafe {
-            windows_sys::Win32::System::Threading::TerminateProcess(
-                windows_sys::Win32::System::Threading::GetCurrentProcess(),
-                1,
-            )
-        };
-    });
+        end_process();
+    }));
+    // Its start (loader notices, Rust's thread set-up) is done only when
+    // it runs its own code. The loader notices need the loader lock. This
+    // thread can hold it, or a thread that waits for this thread can hold
+    // it. Then the watchdog does not start, so this wait has the same
+    // deadline.
+    let waiting = Instant::now();
+    let watchdog = loop {
+        match WATCHDOG.load(Ordering::SeqCst) {
+            0 if waiting.elapsed() >= DETACH_DEADLINE => end_process(),
+            0 => std::thread::yield_now(),
+            id => break id,
+        }
+    };
+    end_other_threads(&[watchdog]);
     for image in dlls.iter().chain(&exes) {
         // SAFETY: attached images are bound. A non-null third argument
         // tells the entry points the process is ending.
@@ -126,11 +141,24 @@ extern "C" fn detach_all() {
     }
 }
 
-/// Ends every thread of the process but this one (and the ones started
-/// while doing so), as `ExitProcess` does first; except the system's
-/// thread-pool workers, which `TerminateThread` refuses (the process fails
-/// fast) and which run no title code (no title image uses that pool).
-fn end_other_threads() {
+/// Ends this process when the title images do not detach in time. It does
+/// not use the heap or any lock: a thread that ended can hold them.
+fn end_process() {
+    // SAFETY: ends this process, which is exiting anyway.
+    unsafe {
+        windows_sys::Win32::System::Threading::TerminateProcess(
+            windows_sys::Win32::System::Threading::GetCurrentProcess(),
+            1,
+        )
+    };
+}
+
+/// Ends every thread of the process but this one and those in `keep` (and
+/// the ones started while doing so), as `ExitProcess` does first; except
+/// the system's thread-pool workers, which `TerminateThread` refuses (the
+/// process fails fast) and which run no title code (no title image uses
+/// that pool).
+fn end_other_threads(keep: &[u32]) {
     use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
     use windows_sys::Win32::System::Diagnostics::ToolHelp::{
         CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
@@ -156,7 +184,10 @@ fn end_other_threads() {
             let mut ids = Vec::new();
             let mut more = Thread32First(snapshot, &mut entry) != 0;
             while more {
-                if entry.th32OwnerProcessID == process && entry.th32ThreadID != me {
+                if entry.th32OwnerProcessID == process
+                    && entry.th32ThreadID != me
+                    && !keep.contains(&entry.th32ThreadID)
+                {
                     ids.push(entry.th32ThreadID);
                 }
                 more = Thread32Next(snapshot, &mut entry) != 0;
@@ -338,32 +369,57 @@ fn starts_in(thread: windows_sys::Win32::Foundation::HANDLE, module: &std::ffi::
 
 #[cfg(test)]
 mod tests {
-    use std::sync::atomic::{AtomicU64, Ordering};
+    use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
     use std::time::Duration;
 
-    /// In a child process of the next test: ends the other threads and
-    /// checks that a busy one stopped.
-    #[test]
-    fn exit_child() {
-        if std::env::var_os("VICTORY_EXIT_CHILD").is_none() {
-            return;
-        }
-        static TICKS: AtomicU64 = AtomicU64::new(0);
-        std::thread::spawn(|| {
+    /// A thread that counts in `ticks` until it ends; returns its thread id
+    /// when it has counted once.
+    fn busy(ticks: &'static AtomicU64) -> u32 {
+        static ID: AtomicU32 = AtomicU32::new(0);
+        ID.store(0, Ordering::SeqCst);
+        std::thread::spawn(move || {
+            // SAFETY: a plain query of the calling thread.
+            let id = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
+            ID.store(id, Ordering::SeqCst);
             loop {
-                TICKS.fetch_add(1, Ordering::SeqCst);
+                ticks.fetch_add(1, Ordering::SeqCst);
                 std::thread::yield_now();
             }
         });
-        while TICKS.load(Ordering::SeqCst) == 0 {
+        while ticks.load(Ordering::SeqCst) == 0 {
             std::thread::yield_now();
         }
-        super::end_other_threads();
-        let at = TICKS.load(Ordering::SeqCst);
+        ID.load(Ordering::SeqCst)
+    }
+
+    /// Whether `ticks` stays the same for a short time.
+    fn stopped(ticks: &AtomicU64) -> bool {
+        let at = ticks.load(Ordering::SeqCst);
         std::thread::sleep(Duration::from_millis(50));
-        let ended = TICKS.load(Ordering::SeqCst) == at;
+        ticks.load(Ordering::SeqCst) == at
+    }
+
+    /// In a child process of the next test: ends the other threads but one
+    /// kept thread, and checks that a busy thread stopped and the kept one
+    /// did not.
+    #[test]
+    fn exit_child() {
+        if std::env::var_os("VICTORY_EXIT_CHILD").is_none() {
+            return;
+        }
+        static ENDS: AtomicU64 = AtomicU64::new(0);
+        static KEPT: AtomicU64 = AtomicU64::new(0);
+        busy(&ENDS);
+        let kept = busy(&KEPT);
+        super::end_other_threads(&[kept]);
+        let ended = stopped(&ENDS);
+        let still_running = !stopped(&KEPT);
         // The test harness's threads are gone too: leave at once.
-        println!("{}", if ended { "ENDED" } else { "STILL RUNNING" });
+        println!(
+            "{} {}",
+            if ended { "ENDED" } else { "STILL RUNNING" },
+            if still_running { "KEPT" } else { "NOT KEPT" }
+        );
         std::process::exit(0);
     }
 
@@ -375,6 +431,9 @@ mod tests {
             .output()
             .unwrap();
         let text = String::from_utf8_lossy(&out.stdout);
-        assert!(out.status.success() && text.contains("ENDED"), "{text}");
+        assert!(
+            out.status.success() && text.contains("ENDED KEPT"),
+            "{text}"
+        );
     }
 }