HLE: keep KernelWrite leases across pending overlapped and scatter reads #3231

Open
github-bot wants to merge 1 commit from github-bot/gh-3231 into main AGit
Owner

@⁠kilvynsilveira-tech on GitHub · 2026-11-26 13:53 UTC · original
kilvynsilveira-tech:overlapped-scatter-kernel-reads → main · +1608 −15 · 2 files · 1 commits · open

Refs #723
Coordination task: NEW-345 (#1633)

What's wrong

Tracked title GPU memory and physical-page views are marked PAGE_READONLY (watch::Guards) so CPU writes fault into the vectored handler. Kernel writes into read-only pages do not trigger user-mode exception handlers—they fail with ERROR_NOACCESS (998) unless opened ahead of time with victory_gpu::kernel_will_write.

On main (63bcca4), three gaps remain on the Win32 file-read path in crates/victory-hle/src/modules/files.rs:

  1. ReadFileScatter and ReadFileEx are not wrapped at all: title imports from api-ms-win-core-file-* / kernel32.dll / kernelbase.dll go straight to the host, so scatter/gather pack reads (FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING) or APC reads into guarded 64 KiB physical-page views fail with ERROR_NOACCESS.
  2. Pending overlapped ReadFile (ERROR_IO_PENDING) drops its KernelWrite lease on return (noted on #723): as soon as ReadFile returns 0 with ERROR_IO_PENDING, _writing drops before the driver's read lands. Any concurrent GPU refresh (Tracked::take) can re-guard the destination pages (PAGE_READONLY) mid-flight—failing the async read—or copy zeros before completion without seeing a dirty mark once the bytes arrive.
  3. LastError clobbering on KernelWrite drop: Writing::drop calls VirtualProtect after the host ReadFile / fread call returns, which can overwrite GetLastError() (such as ERROR_IO_PENDING or ERROR_HANDLE_EOF) before returning to title code.

What this change does

Adds crates/victory-hle/src/modules/files/reads.rs and wires the file, I/O, handle, and wait API-set exports in files::module():

  • ReadFile, ReadFileEx, and ReadFileScatter:
    • Synchronous ReadFile (lpOverlapped == null) and fread skip zero-length/null ranges and preserve thread LastError across KernelWrite drop.
    • ReadFileScatter walks the FILE_SEGMENT_ELEMENT array (sized by GetSystemInfo().dwPageSize, stopping early on the terminating null element) and coalesces adjacent/overlapping 64 KiB tracked page spans so multi-segment reads acquire minimal KernelWrite leases.
    • Overlapped ReadFile / ReadFileScatter (ERROR_IO_PENDING) and queued ReadFileEx keep their KernelWrite leases in PENDING (inserted with a unique monotonic ID before the host call so a fast IOCP worker waking on another core before the submitting thread returns still harvests cleanly).
  • Completion and cancellation harvesting (lock-free AtomicUsize fast path when no overlapped KernelWrite is active; raw volatile reads of OVERLAPPED::Internal avoid forming &Overlapped while the kernel owns the IRP):
    • GetOverlappedResult and GetOverlappedResultEx: release leases once OVERLAPPED::Internal != STATUS_PENDING (covering both TRUE completions and terminal errors like ERROR_HANDLE_EOF / ERROR_OPERATION_ABORTED, while keeping ERROR_IO_INCOMPLETE / WAIT_TIMEOUT leases open).
    • GetQueuedCompletionStatus and GetQueuedCompletionStatusEx: release leases for dequeued OVERLAPPED packets (including failed packets dequeued with ok == 0 and *lpOverlapped != null).
    • ReadFileEx completion routine trampoline: releases the KernelWrite lease before invoking the title's LPOVERLAPPED_COMPLETION_ROUTINE (and leaves OVERLAPPED::hEvent untouched for caller context, per Win32 ReadFileEx rules).
    • WaitForSingleObject(Ex) and WaitForMultipleObjects(Ex): when a wait succeeds on the completion event (with low-order IOCP-skip bit (uintptr_t)hEvent & ~1 stripped) or file handle, harvest completed entries (Internal != STATUS_PENDING) so callers that wait on the event without calling GetOverlappedResult never leak busy pages.
    • CancelIo and CancelIoEx: release only entries whose IRP has already left STATUS_PENDING, keeping leases alive while the storage driver finishes aborting in-flight DMA.
    • OVERLAPPED reuse and CloseHandle: reusing an OVERLAPPED after HasOverlappedIoCompleted polling releases the prior lease after acquiring the new one; CloseHandle clears matching wait_handle slots (preventing recycled-handle collisions) and releases remaining leases on closed file handles.

Tests

Synthetic Windows tests in modules::files::reads::tests (no game files used), driving real watch::Guards PAGE_READONLY page protection through a placed shader-visible descriptor heap (GuardRig):

  1. io_handle_and_wait_api_sets_resolve_to_hle — verifies api-ms-win-core-file-*, api-ms-win-core-io-*, api-ms-win-core-handle-*, and api-ms-win-core-synch-* bind to HLE.
  2. pending_overlapped_read_keeps_guarded_view_open_across_refresh — pending overlapped ReadFile (ERROR_IO_PENDING), mid-flight GPU refresh (PAGE_READWRITE retained), GetOverlappedResult(..., 0) (ERROR_IO_INCOMPLETE), GetOverlappedResultEx harvest, post-harvest refresh re-guarding to PAGE_READONLY, plus negative control showing raw host ReadFile fails with ERROR_NOACCESS (998).
  3. read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait — unbuffered overlapped ReadFileScatter (FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING) across scattered 4 KiB segments in two guarded views with a low-bit-tagged event (hEvent | 1) harvested via WaitForSingleObject, plus negative control showing raw host ReadFileScatter fails with ERROR_NOACCESS (998).
  4. iocp_read_file_ex_cancellation_and_eof_preserve_semantics — GetQueuedCompletionStatus, GetQueuedCompletionStatusEx, ReadFileEx alertable APC with non-handle user context in OVERLAPPED::hEvent, CancelIoEx + GetOverlappedResult, and ERROR_HANDLE_EOF preservation.
  5. multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases — WaitForMultipleObjects, HasOverlappedIoCompleted polling + OVERLAPPED reuse on a guarded view, and CloseHandle cleanup.

Verified on Windows 10 x64 (19045), Ryzen 7 5700X, Radeon RX 580 2048SP:

  • cargo test -p victory-hle --locked (single-threaded and parallel): 159 passed, 0 failed
  • cargo test -p victory-gpu --locked watch::: 15 passed, 0 failed
  • cargo clippy --workspace --all-targets --locked -- -D warnings: clean
  • cargo clippy --workspace --all-targets --all-features --locked -- -D warnings: clean
  • cargo run -p xtask --locked -- policy: 192 files ok

Not tested: a retail title run. AI-assisted (Gemini).

**@⁠kilvynsilveira-tech** on GitHub · 2026-11-26 13:53 UTC · [original](https://github.com/Marvisak/VIctory/pull/3231) `kilvynsilveira-tech:overlapped-scatter-kernel-reads` → `main` · +1608 −15 · 2 files · 1 commits · open Refs #723 Coordination task: `NEW-345` (#1633) ## What's wrong Tracked title GPU memory and physical-page views are marked `PAGE_READONLY` (`watch::Guards`) so CPU writes fault into the vectored handler. Kernel writes into read-only pages do not trigger user-mode exception handlers—they fail with `ERROR_NOACCESS` (`998`) unless opened ahead of time with `victory_gpu::kernel_will_write`. On `main` (`63bcca4`), three gaps remain on the Win32 file-read path in `crates/victory-hle/src/modules/files.rs`: 1. **`ReadFileScatter` and `ReadFileEx` are not wrapped at all**: title imports from `api-ms-win-core-file-*` / `kernel32.dll` / `kernelbase.dll` go straight to the host, so scatter/gather pack reads (`FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING`) or APC reads into guarded 64 KiB physical-page views fail with `ERROR_NOACCESS`. 2. **Pending overlapped `ReadFile` (`ERROR_IO_PENDING`) drops its `KernelWrite` lease on return** (noted on #723): as soon as `ReadFile` returns `0` with `ERROR_IO_PENDING`, `_writing` drops before the driver's read lands. Any concurrent GPU refresh (`Tracked::take`) can re-guard the destination pages (`PAGE_READONLY`) mid-flight—failing the async read—or copy zeros before completion without seeing a dirty mark once the bytes arrive. 3. **`LastError` clobbering on `KernelWrite` drop**: `Writing::drop` calls `VirtualProtect` after the host `ReadFile` / `fread` call returns, which can overwrite `GetLastError()` (such as `ERROR_IO_PENDING` or `ERROR_HANDLE_EOF`) before returning to title code. ## What this change does Adds `crates/victory-hle/src/modules/files/reads.rs` and wires the file, I/O, handle, and wait API-set exports in `files::module()`: - **`ReadFile`, `ReadFileEx`, and `ReadFileScatter`**: - Synchronous `ReadFile` (`lpOverlapped == null`) and `fread` skip zero-length/null ranges and preserve thread `LastError` across `KernelWrite` drop. - `ReadFileScatter` walks the `FILE_SEGMENT_ELEMENT` array (sized by `GetSystemInfo().dwPageSize`, stopping early on the terminating null element) and coalesces adjacent/overlapping 64 KiB tracked page spans so multi-segment reads acquire minimal `KernelWrite` leases. - Overlapped `ReadFile` / `ReadFileScatter` (`ERROR_IO_PENDING`) and queued `ReadFileEx` keep their `KernelWrite` leases in `PENDING` (inserted with a unique monotonic ID *before* the host call so a fast IOCP worker waking on another core before the submitting thread returns still harvests cleanly). - **Completion and cancellation harvesting** (lock-free `AtomicUsize` fast path when no overlapped `KernelWrite` is active; raw volatile reads of `OVERLAPPED::Internal` avoid forming `&Overlapped` while the kernel owns the IRP): - `GetOverlappedResult` and `GetOverlappedResultEx`: release leases once `OVERLAPPED::Internal != STATUS_PENDING` (covering both `TRUE` completions and terminal errors like `ERROR_HANDLE_EOF` / `ERROR_OPERATION_ABORTED`, while keeping `ERROR_IO_INCOMPLETE` / `WAIT_TIMEOUT` leases open). - `GetQueuedCompletionStatus` and `GetQueuedCompletionStatusEx`: release leases for dequeued `OVERLAPPED` packets (including failed packets dequeued with `ok == 0` and `*lpOverlapped != null`). - `ReadFileEx` completion routine trampoline: releases the `KernelWrite` lease *before* invoking the title's `LPOVERLAPPED_COMPLETION_ROUTINE` (and leaves `OVERLAPPED::hEvent` untouched for caller context, per Win32 `ReadFileEx` rules). - `WaitForSingleObject`(`Ex`) and `WaitForMultipleObjects`(`Ex`): when a wait succeeds on the completion event (with low-order IOCP-skip bit `(uintptr_t)hEvent & ~1` stripped) or file handle, harvest completed entries (`Internal != STATUS_PENDING`) so callers that wait on the event without calling `GetOverlappedResult` never leak busy pages. - `CancelIo` and `CancelIoEx`: release only entries whose IRP has already left `STATUS_PENDING`, keeping leases alive while the storage driver finishes aborting in-flight DMA. - `OVERLAPPED` reuse and `CloseHandle`: reusing an `OVERLAPPED` after `HasOverlappedIoCompleted` polling releases the prior lease after acquiring the new one; `CloseHandle` clears matching `wait_handle` slots (preventing recycled-handle collisions) and releases remaining leases on closed file handles. ## Tests Synthetic Windows tests in `modules::files::reads::tests` (no game files used), driving real `watch::Guards` `PAGE_READONLY` page protection through a placed shader-visible descriptor heap (`GuardRig`): 1. `io_handle_and_wait_api_sets_resolve_to_hle` — verifies `api-ms-win-core-file-*`, `api-ms-win-core-io-*`, `api-ms-win-core-handle-*`, and `api-ms-win-core-synch-*` bind to HLE. 2. `pending_overlapped_read_keeps_guarded_view_open_across_refresh` — pending overlapped `ReadFile` (`ERROR_IO_PENDING`), mid-flight GPU refresh (`PAGE_READWRITE` retained), `GetOverlappedResult(..., 0)` (`ERROR_IO_INCOMPLETE`), `GetOverlappedResultEx` harvest, post-harvest refresh re-guarding to `PAGE_READONLY`, plus negative control showing raw host `ReadFile` fails with `ERROR_NOACCESS` (`998`). 3. `read_file_scatter_opens_guarded_segments_and_harvests_on_event_wait` — unbuffered overlapped `ReadFileScatter` (`FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING`) across scattered 4 KiB segments in two guarded views with a low-bit-tagged event (`hEvent | 1`) harvested via `WaitForSingleObject`, plus negative control showing raw host `ReadFileScatter` fails with `ERROR_NOACCESS` (`998`). 4. `iocp_read_file_ex_cancellation_and_eof_preserve_semantics` — `GetQueuedCompletionStatus`, `GetQueuedCompletionStatusEx`, `ReadFileEx` alertable APC with non-handle user context in `OVERLAPPED::hEvent`, `CancelIoEx` + `GetOverlappedResult`, and `ERROR_HANDLE_EOF` preservation. 5. `multi_wait_overlapped_reuse_and_close_handle_leave_no_stale_leases` — `WaitForMultipleObjects`, `HasOverlappedIoCompleted` polling + `OVERLAPPED` reuse on a guarded view, and `CloseHandle` cleanup. Verified on Windows 10 x64 (19045), Ryzen 7 5700X, Radeon RX 580 2048SP: - `cargo test -p victory-hle --locked` (single-threaded and parallel): 159 passed, 0 failed - `cargo test -p victory-gpu --locked watch::`: 15 passed, 0 failed - `cargo clippy --workspace --all-targets --locked -- -D warnings`: clean - `cargo clippy --workspace --all-targets --all-features --locked -- -D warnings`: clean - `cargo run -p xtask --locked -- policy`: 192 files ok Not tested: a retail title run. AI-assisted (Gemini).
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 13:59:24 +00:00
Author
Owner

@⁠Dukestar69 on GitHub · 2026-11-26 14:11 UTC · original · approved these changes

Verified against origin/main (63bcca4):

  • cargo test -p victory-hle --lib modules::files:: -- --test-threads=1: 11/11 passed (all 5 new overlapped/scatter KernelWrite lease tests pass).
  • cargo clippy -p victory-hle --all-targets -- -D warnings: clean.
  • cargo xtask policy: 192 files ok.

Cleanly keeps KernelWrite leases alive across pending overlapped and scatter reads and harvests them on completion/cancellation/close.

Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).

**@⁠Dukestar69** on GitHub · 2026-11-26 14:11 UTC · [original](https://github.com/Marvisak/VIctory/pull/3231#pullrequestreview-6075566770) · **approved these changes** Verified against `origin/main` (`63bcca4`): - `cargo test -p victory-hle --lib modules::files:: -- --test-threads=1`: 11/11 passed (all 5 new overlapped/scatter `KernelWrite` lease tests pass). - `cargo clippy -p victory-hle --all-targets -- -D warnings`: clean. - `cargo xtask policy`: 192 files ok. Cleanly keeps `KernelWrite` leases alive across pending overlapped and scatter reads and harvests them on completion/cancellation/close. Synthetic tests only (no game files used). AI-assisted (Gemini 4 Neon).
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/3231/head:github-bot/gh-3231'
git switch 'github-bot/gh-3231'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-3231'
git switch 'github-bot/gh-3231'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-3231'
git switch 'github-bot/gh-3231'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-3231'
git switch 'main'
git merge --squash 'github-bot/gh-3231'
git switch 'main'
git merge --ff-only 'github-bot/gh-3231'
git switch 'main'
git merge 'github-bot/gh-3231'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No reviewers
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!3231
No description provided.