GPU: an announced kernel read (kernel_will_write) can be re-guarded before it lands, so ReadFile and DirectStorage fail #723

Open
opened 2026-11-26 04:13:53 +00:00 by github-bot · 5 comments
Owner

@⁠Dufftwt on GitHub · 2026-11-24 08:26 UTC · original

What's wrong

View memory (xmem's physical-page views) is tracked by making 64 KiB blocks read-only (guard, crates/victory-gpu/src/watch.rs:125). A system call can't write into a read-only block: ReadFile fails with ERROR_NOACCESS instead of faulting into our handler. So the HLE announces kernel writes first, with victory_gpu::kernel_will_write:

  • files.rs:531 and :539 (ReadFile, fread);
  • dstorage.rs:954 (DirectStorage reads).

kernel_will_write (writing, watch.rs:212) only opens the blocks. The next guard() call covering them, from any thread, sees them as written and makes them read-only again. The submitting thread calls it on every refresh. If that happens between the announcement and the kernel's write, the read fails.

Example

  • A title thread calls ReadFile into view memory. kernel_will_write opens the block.
  • Before the kernel writes, the render thread refreshes a buffer covering that block, and guard() protects it again.
  • ReadFile fails with ERROR_NOACCESS. DirectStorage returns the error to the title, and fread returns short.

The window is as long as the read: an overlapped read, or the whole DirectStorage read loop.

Evidence

A single-thread replay of the two threads' order, using a real pagefile view and a real file read:

  1. Guard the view.
  2. Call writing(view + 100, 13) (the title thread's announcement).
  3. Call writes(view, view + 2 * BLOCK, true) (the render thread's refresh).
  4. read 13 bytes from a temp file into view + 100.

On main (dd54de2), on GitHub's windows-latest, the read fails:

the announced kernel read failed: the refresh guarded the block again
Test (inside crates/victory-gpu/src/watch.rs's mod tests)
    /// An announced kernel read stays open until it lands.
    #[test]
    fn an_announced_kernel_read_survives_a_refresh_before_it() {
        use std::io::{Read, Seek, Write};
        use windows_sys::Win32::System::Memory::{
            CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile,
        };
        // SAFETY: a pagefile section of two blocks, mapped read-write.
        let view = unsafe {
            let section = CreateFileMappingW(
                -1isize as _,
                std::ptr::null(),
                PAGE_READWRITE,
                0,
                (2 * BLOCK) as u32,
                std::ptr::null(),
            );
            assert!(!section.is_null());
            MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize
        };
        assert_ne!(view, 0);
        assert!(guard(view, view + 2 * BLOCK).is_some());
        let mut file = tempfile::tempfile().unwrap();
        file.write_all(b"from the disk").unwrap();
        file.rewind().unwrap();
        writing(view + 100, 13); // the title thread, in `ReadFile`
        let _ = writes(view, view + 2 * BLOCK, true); // the submitting thread
        // SAFETY: 13 bytes of our view, nothing else refers to them.
        let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) };
        let read = file.read(into).is_ok_and(|n| n == 13);
        // SAFETY: our view.
        unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) };
        title_memory_remapped(view, 2 * BLOCK);
        assert!(read, "the announced kernel read failed: the refresh guarded the block again");
    }

Suggested fix

Count in-flight kernel writes per block in Guards:

  • kernel_will_write increments the count.
  • A new kernel_wrote(at, len) decrements it. The HLE calls it once the read returns.
  • guard() reports a block with a nonzero count as written but doesn't protect it.

A cruder alternative on the HLE side: on ERROR_NOACCESS, announce again and retry.

#393, #413, #464 and #490 change guard / title_memory_remapped, but none keeps an announced block open.

**@⁠Dufftwt** on GitHub · 2026-11-24 08:26 UTC · [original](https://github.com/Marvisak/VIctory/issues/723) ## What's wrong View memory (xmem's physical-page views) is tracked by making 64 KiB blocks read-only (`guard`, `crates/victory-gpu/src/watch.rs:125`). A system call can't write into a read-only block: `ReadFile` fails with `ERROR_NOACCESS` instead of faulting into our handler. So the HLE announces kernel writes first, with `victory_gpu::kernel_will_write`: - `files.rs:531` and `:539` (`ReadFile`, `fread`); - `dstorage.rs:954` (DirectStorage reads). `kernel_will_write` (`writing`, `watch.rs:212`) only opens the blocks. The next `guard()` call covering them, from **any** thread, sees them as written and makes them read-only again. The submitting thread calls it on every refresh. If that happens between the announcement and the kernel's write, the read fails. ## Example - A title thread calls `ReadFile` into view memory. `kernel_will_write` opens the block. - Before the kernel writes, the render thread refreshes a buffer covering that block, and `guard()` protects it again. - `ReadFile` fails with `ERROR_NOACCESS`. DirectStorage returns the error to the title, and `fread` returns short. The window is as long as the read: an overlapped read, or the whole DirectStorage read loop. ## Evidence A single-thread replay of the two threads' order, using a real pagefile view and a real file read: 1. Guard the view. 2. Call `writing(view + 100, 13)` (the title thread's announcement). 3. Call `writes(view, view + 2 * BLOCK, true)` (the render thread's refresh). 4. `read` 13 bytes from a temp file into `view + 100`. On `main` (dd54de2), on GitHub's `windows-latest`, the read fails: ``` the announced kernel read failed: the refresh guarded the block again ``` <details><summary>Test (inside <code>crates/victory-gpu/src/watch.rs</code>'s <code>mod tests</code>)</summary> ```rust /// An announced kernel read stays open until it lands. #[test] fn an_announced_kernel_read_survives_a_refresh_before_it() { use std::io::{Read, Seek, Write}; use windows_sys::Win32::System::Memory::{ CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile, }; // SAFETY: a pagefile section of two blocks, mapped read-write. let view = unsafe { let section = CreateFileMappingW( -1isize as _, std::ptr::null(), PAGE_READWRITE, 0, (2 * BLOCK) as u32, std::ptr::null(), ); assert!(!section.is_null()); MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK).Value as usize }; assert_ne!(view, 0); assert!(guard(view, view + 2 * BLOCK).is_some()); let mut file = tempfile::tempfile().unwrap(); file.write_all(b"from the disk").unwrap(); file.rewind().unwrap(); writing(view + 100, 13); // the title thread, in `ReadFile` let _ = writes(view, view + 2 * BLOCK, true); // the submitting thread // SAFETY: 13 bytes of our view, nothing else refers to them. let into = unsafe { std::slice::from_raw_parts_mut((view + 100) as *mut u8, 13) }; let read = file.read(into).is_ok_and(|n| n == 13); // SAFETY: our view. unsafe { UnmapViewOfFile(windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS { Value: view as *mut _ }) }; title_memory_remapped(view, 2 * BLOCK); assert!(read, "the announced kernel read failed: the refresh guarded the block again"); } ``` </details> ## Suggested fix Count in-flight kernel writes per block in `Guards`: - `kernel_will_write` increments the count. - A new `kernel_wrote(at, len)` decrements it. The HLE calls it once the read returns. - `guard()` reports a block with a nonzero count as written but doesn't protect it. A cruder alternative on the HLE side: on `ERROR_NOACCESS`, announce again and retry. ## Related #393, #413, #464 and #490 change `guard` / `title_memory_remapped`, but none keeps an announced block open.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 04:13:53 +00:00
Author
Owner

@⁠Hiiva on GitHub · 2026-11-24 09:05 UTC · original

I implemented a scoped kernel-write lease for this race, including overlapping ranges, synchronous ReadFile/fread/DirectStorage writes, and conservative treatment of pending overlapped reads. Synthetic Windows view tests pass (4/4), and the MSVC workspace tests passed before the latest shader change. Branch: https://github.com/Hiiva/VIctory/tree/hiiva/kernel-write-lease (commit 73429ef). Original game files were not changed. AI-assisted implementation and testing. External PR creation is currently collaborators-only.

**@⁠Hiiva** on GitHub · 2026-11-24 09:05 UTC · [original](https://github.com/Marvisak/VIctory/issues/723#issuecomment-7126942563) I implemented a scoped kernel-write lease for this race, including overlapping ranges, synchronous ReadFile/fread/DirectStorage writes, and conservative treatment of pending overlapped reads. Synthetic Windows view tests pass (4/4), and the MSVC workspace tests passed before the latest shader change. Branch: https://github.com/Hiiva/VIctory/tree/hiiva/kernel-write-lease (commit 73429ef). Original game files were not changed. AI-assisted implementation and testing. External PR creation is currently collaborators-only.
Author
Owner

@⁠vladbondarenko97 on GitHub · 2026-11-24 09:46 UTC · original

Independent reproduction on another config — the symptom is "no request ever completes"

RTX 3080 Ti, Windows 11 26300, retail 1.0.2.1, VIctory main 58fed3704 (diag build, cargo build --profile diag -p victory --features diagnostics, our local queue-assert skip present but inert — it never fires here).

  • 20 dstorage workers, 17 queues (capacity 4159), 262 dstorage: submit lines, the last at 09:26:28.601.
  • Zero completions: no dstorage: last stats lines at all in 17 minutes, zero process file-read, dstorage: request failed also 0 — the requests simply never land.
  • The title sits in its Sleep(1) status poll and issues 3 clear-draws/frame at a steady 30 fps; all 18 captures (frames 1–24576) are 100% 0xff000000, 6121-byte PNGs.
  • It never reaches the legal-terms / "Confirm setup and start the game" screen, so the new victory-formats BCPack decoder never runs: zero bcpack/unpack lines.
  • No asserts, no crashes, no device removal, no no swap chain — only a black frame after a frame that was not frame=1 (black_frames=1), host view heap capped at 1000000 (0x80070057, count 1245184) and view the host does not allow unordered=true format=53 flags=2, all in the first two seconds.

That is consistent with this issue's race: the guest is waiting on reads that never satisfy, rather than on anything the title itself reports. For contrast, our earlier builds on 97c78d1 / PR #346 head did complete dstorage work on the same box (files opened, zlib requests finished, 46–55 draws/frame, full first-run flow).

AI-assisted investigation (Claude Code); values are from our own retail run, package unmodified.

**@⁠vladbondarenko97** on GitHub · 2026-11-24 09:46 UTC · [original](https://github.com/Marvisak/VIctory/issues/723#issuecomment-7127877828) **Independent reproduction on another config — the symptom is "no request ever completes"** RTX 3080 Ti, Windows 11 26300, retail 1.0.2.1, VIctory **main `58fed3704`** (diag build, `cargo build --profile diag -p victory --features diagnostics`, our local queue-assert skip present but inert — it never fires here). - 20 dstorage workers, 17 queues (capacity 4159), **262 `dstorage: submit` lines**, the last at 09:26:28.601. - **Zero completions**: no `dstorage: last` stats lines at all in 17 minutes, zero process file-read, `dstorage: request failed` also 0 — the requests simply never land. - The title sits in its `Sleep(1)` status poll and issues **3 clear-draws/frame at a steady 30 fps**; all 18 captures (frames 1–24576) are **100% `0xff000000`**, 6121-byte PNGs. - It never reaches the legal-terms / "Confirm setup and start the game" screen, so the new `victory-formats` BCPack decoder never runs: zero `bcpack`/`unpack` lines. - No asserts, no crashes, no device removal, no `no swap chain` — only `a black frame after a frame that was not frame=1 (black_frames=1)`, `host view heap capped at 1000000 (0x80070057, count 1245184)` and `view the host does not allow unordered=true format=53 flags=2`, all in the first two seconds. That is consistent with this issue's race: the guest is waiting on reads that never satisfy, rather than on anything the title itself reports. For contrast, our earlier builds on `97c78d1` / PR #346 head *did* complete dstorage work on the same box (files opened, zlib requests finished, 46–55 draws/frame, full first-run flow). AI-assisted investigation (Claude Code); values are from our own retail run, package unmodified.
Author
Owner

@⁠Dufftwt on GitHub · 2026-11-24 15:10 UTC · original

Fixed in #1025: kernel_will_write counts the announced reads per block, guard() leaves a counted block open, and the new kernel_wrote uncounts it once ReadFile, fread or the DirectStorage fill returns.

**@⁠Dufftwt** on GitHub · 2026-11-24 15:10 UTC · [original](https://github.com/Marvisak/VIctory/issues/723#issuecomment-7135571175) Fixed in #1025: `kernel_will_write` counts the announced reads per block, `guard()` leaves a counted block open, and the new `kernel_wrote` uncounts it once `ReadFile`, `fread` or the DirectStorage fill returns.
Author
Owner

@⁠Marvisak on GitHub · 2026-11-25 01:48 UTC · original · edited 2026-11-26 06:42 UTC

Automated triage for the maintainers.

This is fixed on main. #1025 was closed without merging; the tracking described here was replaced by a per-read lease instead:

  • watch::writing (exported to the runtime as kernel_will_write, in crates/victory-gpu/src/watch.rs) returns a Writing value. While it lives, its pages stay in Guards::busy, and protect() skips busy pages, so no refresh on another thread can guard them again. Dropping it removes the range and marks the pages changed, so the next refresh copies what the kernel wrote.
  • The callers hold it across the kernel's write: ReadFile and fread in crates/victory-hle/src/modules/files.rs (let _writing = … before the host call), and the raw DirectStorage fill in crates/victory-hle/src/modules/dstorage.rs.

One remaining edge: an overlapped ReadFile that returns ERROR_IO_PENDING drops its lease when the call returns, before the read lands. If that case matters, a new issue for it would be the place.

The latest comment agrees the race is real and reports that the lease does not change a separate world-load stop on a GTX 1660 SUPER; that stop is discussed in #1063, not here. Disassembly of the title's own code (its function names and internal offsets) must not be posted in this repository.

This issue will be closed in 48 hours unless the reporter replies or a maintainer removes the triage: proposed close label.


Generated by Claude Code

**@⁠Marvisak** on GitHub · 2026-11-25 01:48 UTC · [original](https://github.com/Marvisak/VIctory/issues/723#issuecomment-7149978281) · edited 2026-11-26 06:42 UTC <!-- victory-issue-triage v1 verdict=proposed-close seen=2026-11-26T05:51:13Z at=2026-11-26T06:43:00Z --> Automated triage for the maintainers. This is fixed on `main`. #1025 was closed without merging; the tracking described here was replaced by a per-read lease instead: - `watch::writing` (exported to the runtime as `kernel_will_write`, in `crates/victory-gpu/src/watch.rs`) returns a `Writing` value. While it lives, its pages stay in `Guards::busy`, and `protect()` skips busy pages, so no refresh on another thread can guard them again. Dropping it removes the range and marks the pages changed, so the next refresh copies what the kernel wrote. - The callers hold it across the kernel's write: `ReadFile` and `fread` in `crates/victory-hle/src/modules/files.rs` (`let _writing = …` before the host call), and the raw DirectStorage fill in `crates/victory-hle/src/modules/dstorage.rs`. One remaining edge: an overlapped `ReadFile` that returns `ERROR_IO_PENDING` drops its lease when the call returns, before the read lands. If that case matters, a new issue for it would be the place. The latest comment agrees the race is real and reports that the lease does not change a separate world-load stop on a GTX 1660 SUPER; that stop is discussed in #1063, not here. Disassembly of the title's own code (its function names and internal offsets) must not be posted in this repository. This issue will be closed in 48 hours unless the reporter replies or a maintainer removes the `triage: proposed close` label. --- _Generated by [Claude Code](https://claude.ai/code)_
Author
Owner

@⁠roon9e on GitHub · 2026-11-26 05:51 UTC · original

Related measurement, in case it saves someone time: the announced-kernel-write race this issue describes is real but is not the cause of the GTX 1660 SUPER world-load stop (+0x1330a44, codec 0x817).

I implemented the minimal lease on top of the affected revision (a #[must_use] Writing lease in victory-gpu/src/watch.rs: a per-block count that guard() skips while held, released on drop; held across the write in ReadFile/fread, both into_destination branches in dstorage.rs, and the host.rs/shadow.rs writes). It builds and the reads still work, but it did not change the failing decode's input (still 128 zero bytes), so the .zmt producer is on a different path.

For the record, the runtime's own decode plumbing is healthy on this card:

  • dstorage options=0x1 (ZLIB): 6,532 requests, all size=65536, all completed, 0 failures; the inflated output is valid (wrote=65536).
  • ReadFile: 24,278 calls, all real data (one got=0).

The stop is instead the title's own guard in FUN_141330cd0 ([inst+0x40]+8 (46586) < [inst+8] (65536) → fallback → return 0 → the streamer loops). Full write-up on #1063.

AI-assisted; measured on the physical GTX 1660 SUPER.

**@⁠roon9e** on GitHub · 2026-11-26 05:51 UTC · [original](https://github.com/Marvisak/VIctory/issues/723#issuecomment-7183864527) Related measurement, in case it saves someone time: the announced-kernel-write race this issue describes is **real but is not the cause of the GTX 1660 SUPER world-load stop** (`+0x1330a44`, codec `0x817`). I implemented the minimal lease on top of the affected revision (a `#[must_use]` `Writing` lease in `victory-gpu/src/watch.rs`: a per-block count that `guard()` skips while held, released on drop; held across the write in `ReadFile`/`fread`, both `into_destination` branches in `dstorage.rs`, and the `host.rs`/`shadow.rs` writes). It builds and the reads still work, but it did **not** change the failing decode's input (still 128 zero bytes), so the `.zmt` producer is on a different path. For the record, the runtime's own decode plumbing is healthy on this card: - `dstorage` `options=0x1` (ZLIB): 6,532 requests, all `size=65536`, all completed, 0 failures; the inflated output is valid (`wrote=65536`). - `ReadFile`: 24,278 calls, all real data (one `got=0`). The stop is instead the title's own guard in `FUN_141330cd0` (`[inst+0x40]+8 (46586) < [inst+8] (65536)` → fallback → `return 0` → the streamer loops). Full write-up on #1063. AI-assisted; measured on the physical GTX 1660 SUPER.
This discussion has been locked. Commenting is limited to contributors.
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
github/Marvisak--VIctory#723
No description provided.