Skip to content

GPU: a marked page goes back at its first access (VICTORY_LAZY_COPY_BACK) - #3118

Closed
borosf wants to merge 7 commits into
Marvisak:mainfrom
borosf:vibe/lazy-copy-back-842ca5
Closed

borosf wants to merge 7 commits into
Marvisak:mainfrom
borosf:vibe/lazy-copy-back-842ca5

Conversation

@borosf

@borosf borosf commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Summary

  • After a submission, Shadow::copy_back_marked brings every page its shaders marked as written back into title memory — on the card that is 60–127 ms a frame, 95 % of it waiting (FIND-33: the snapshot's pages fetched, and the waits around them; the host-side merge is 2.4–2.9 ms, the write 0.4–0.5 ms). The world marks ~2,250 pages a frame; most are never read by title code before a later pass overwrites them.
  • With VICTORY_LAZY_COPY_BACK=1 (opt-in, off by default — behavior is unchanged without it), a marked page leaves the submission sealed no-access. The first read faults that one page back; the first write faults it back and then lands as the title's own over it (the merge happens underneath, as eager copy-back would have); a page nothing touched is written by the next submission's copy-back and never holds the critical path.
  • The wait is a small ledger in the guard state (watch): sealed pages holding their copy alive, and the vectored handler — which today services write faults — also taking read faults on those pages, servicing exactly one page each time. Arming is one VirtualProtect per run of pages.
  • Only pages that can safely wait are armed: guarded, held whole by one copy, no alias showing them elsewhere, not already waiting. Everything else — partial pages, aliased pages, withheld ranges — goes back eagerly, unchanged.
  • Ordering is preserved against every path that could reach a sealed page without faulting: refreshes drain their range first (Shadow::update, copy_back, copy_back_page), writes the guards do not see drain before they mark (watch::writing — kernel reads, DirectStorage), and remaps, retakes and new aliases drop the wait and unseal (title_memory_remapped, retake, title_memory_aliased). In-process reads of a sealed page fault into the handler and service transparently.
  • The arming counts its seals and both refusal kinds (guard state, host), and a test failure names the stage — on hardware that refuses the seal the feature stays a no-op, falling back to eager copy-back.
  • Composes with GPU, HLE: marked pages go back beside the guards (VICTORY_COPY_BACK_BESIDE, opt-in) #3069 (write-beside changes how pages go back, this when), GPU: the Xbox's shared CPU/GPU memory on PC GPUs: simulated in video memory on discrete cards, title memory itself on unified ones #3102 (shared memory placement — the ledger is per virtual page regardless of backing), and GPU: marked pages go back to title memory on several threads (#2826) #2914 (drains are per-range, re-entrant through remove-before-service).

Verification

  • CI (Windows clippy -D warnings, cargo test --workspace --locked); with the switch off the suite is unchanged.
  • New synthetic test marked_pages_leave_the_submission_and_go_back_at_their_first_access drives the real fault handler on the Intel Arc B580: the submission leaves pages sealed (asserted via VirtualQuery, arming counters (3, 0, 0) — sealed, none refused), a read_volatile faults the GPU's byte back and the page is guarded again, a write_volatile merges underneath and lands on top, an untouched page is written by the next copy-back, and the ledger ends empty.
  • Intel Arc B580, Windows 11: cargo clippy -p victory-gpu --all-targets --locked -- -D warnings clean; cargo test -p victory-gpu --lib --locked green except the two known Intel heap-cap failures (Test report: RTX 5070 (Blackwell), Windows 11, 70564ae: 471 passed, 5 failed, 7 ignored (4 from the 1,000,000 view heap cap) #1744) pristine main also fails.
  • No game data used. Synthetic tests only.

claiming: FIND-33 — lazy copy-back on read (marked pages go back at their first access), the 95 %-wait copy-back stall (#1633 comment, per the ledger)

mistral-vibe and others added 5 commits November 26, 2026 08:36
…ACK)

Co-authored-by: borosf <borosf@users.noreply.github.com>
Co-authored-by: borosf <borosf@users.noreply.github.com>
…s them

Co-authored-by: borosf <borosf@users.noreply.github.com>
Co-authored-by: borosf <borosf@users.noreply.github.com>
Co-authored-by: borosf <borosf@users.noreply.github.com>

@Dukestar69 Dukestar69 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on RTX 5090 & WARP against origin/main (63bcca4):

  • cargo test -p victory-gpu --lib shadow:: -- --test-threads=1: 11/11 passed on RTX 5090 and WARP (including marked_pages_leave_the_submission_and_go_back_at_their_first_access).
  • cargo test -p victory-gpu --lib watch:: -- --test-threads=1: 15/15 passed.
  • cargo test -p victory-gpu --lib draw:: -- --test-threads=1: 20/20 passed on RTX 5090.
  • cargo clippy -p victory-gpu --all-targets -- -D warnings: clean.
  • cargo xtask policy: 191 files ok.

Clean opt-in VICTORY_LAZY_COPY_BACK mechanism deferring marked-page copy-backs until first CPU access.

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

@fuzeofficlal fuzeofficlal left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The single-threaded synthetic test passes on Windows 11 (shadow:: + watch:: 26/26 on RTX 5090; VICTORY_LAZY_COPY_BACK=1 15/15 on RTX 5090 and WARP; Clippy and cargo xtask policy clean), and deferring unneeded copy-backs is an interesting direction for FIND-33. However, deep review of watch.rs and shadow.rs found several serious correctness and performance issues that make this unsafe even under opt-in use and regress the default-off fast path:

1. Multithreaded / drain crash (EXCEPTION_CONTINUE_SEARCH) and stale-read window (watch.rs:367-398, 425-440, 1068-1075, shadow.rs:91-111)

  • lazy_page, take_lazy, and take_all_lazy all remove pages from g.lazy and release GUARDS before unsealing PAGE_NOACCESS. If any other thread accesses a page while it is being serviced (especially during take_all_lazy, which removes every sealed page up front before looping over them one by one), it faults on PAGE_NOACCESS, calls lazy_page which now returns None, hits if r.ExceptionInformation[0] == READ { return EXCEPTION_CONTINUE_SEARCH; }, and crashes the process with an unhandled access violation.
  • In addition, copy_back_one calls repaged(page / PAGE) (PAGE_NOACCESS -> PAGE_READONLY) before copy.copy_back_marked(page) writes the GPU's bytes into title memory. Between those two calls, any concurrent reader succeeds without faulting and observes stale pre-GPU bytes.
  • Both require keeping a per-page in-flight/servicing state (so concurrent faulted threads wait until the page's GPU bytes have actually landed, and only then unseal to PAGE_READONLY — or write through an alias / side view before flipping protection).

2. ReadProcessMemory (host::copy_mapped) and VirtualQuery (texture::committed) silently zero/skip PAGE_NOACCESS pages without firing VEH (host.rs:2499-2510, texture.rs:752-777)

  • host::copy_mapped (Step::Copy / Step::Fill) reads src using ReadProcessMemory(GetCurrentProcess(), ...). Because ReadProcessMemory is a kernel syscall, hitting a PAGE_NOACCESS page returns ERROR_PARTIAL_COPY (false) without delivering a VEH exception, and copy_mapped's fallback fills the destination with zeros. copy_mapped only calls watch::writing on dst (when title_dst is true) and never drains src.
  • texture::committed (texture.rs:765-768) explicitly rejects PAGE_NOACCESS (info.Protect & (PAGE_NOACCESS | PAGE_GUARD) != 0), so Staging::refresh_now silently skips uploading any texture overlapping a sealed page rather than faulting it back.

3. title_memory_aliased calls forget_lazy instead of draining pending GPU writes (watch.rs:1024-1035)

forget_lazy drops the ledger entry and flips protection back to PAGE_READONLY without calling service_lazy. Unlike title_memory_remapped or retake, mapping a second alias view of a live physical page does not invalidate the GPU writes waiting in g.lazy — calling forget_lazy silently discards those writes permanently for both views. Those pages must be drained (service_lazy) before installing the alias.

4. Default-off performance regression: lazy_armed() locks GUARDS on every Shadow::update (watch.rs:362-364, shadow.rs:555, watch.rs:816)

lazy_armed() currently acquires the global GUARDS mutex (guards().lazy.iter().next().is_some()), and is called at the top of Shadow::update before if self.clean() { return 0; } (as well as in copy_back_page, copy_back_or_not, and watch::writing). That defeats the lock-free fast path even when VICTORY_LAZY_COPY_BACK is off (the default). Tracking the armed count in an AtomicUsize (checked before locking GUARDS) keeps the default-off / empty path lock-free.

5. VEH allocation / re-entrancy & README.md table placement

  • on_write allocates a heap Vec (vec![(copy, at / PAGE)]) inside the Vectored Exception Handler; switching to a single-page helper (service_lazy_one(&copy, at / PAGE)) avoids unnecessary heap allocation in the fault path (and note the general re-entrancy risk of acquiring Shadow::before inside VEH if any path ever reads title memory while holding self.before).
  • README.md:220 adds VICTORY_LAZY_COPY_BACK=1 inside the --features victory-gpu/diagnostics table, even though lazy_on() is active in all builds.

Copy link
Copy Markdown
Owner

Automated triage for the maintainers.

Needs work. This adds VICTORY_LAZY_COPY_BACK. Marked pages are sealed PAGE_NOACCESS in watch::arm_lazy and copied back from the vectored handler at their first access, with drains in Shadow::update, copy_back_page, copy_back_or_not and watch::writing. Three things block it:

  1. Kernel reads of sealed pages fail. Unlike the existing read-only guard, a no-access page also breaks reads the kernel makes from title memory (a WriteFile from a title buffer, for example). These fail with an access error instead of faulting into the handler. watch::writing drains only for writes into title memory.
  2. The default path changes. on_write now calls lazy_page, which takes the GUARDS lock, on every read access violation, even with the switch off. watch::writing also takes an extra lock through lazy_armed(). Please gate both on a cheap atomic that is set only when the switch is on.
  3. No measurement. copy_back_marks_with drains every armed page at the start of the next submission, so the copy-back seems to move rather than go away. Please show world frame timings with the switch on and off.

Also, the README row is a paragraph of rationale. Please cut it to one line saying what the switch does.

CI: check passing.


Generated by Claude Code

mistral-vibe and others added 2 commits November 26, 2026 12:03
…it drained

Co-authored-by: borosf <borosf@users.noreply.github.com>
Co-authored-by: borosf <borosf@users.noreply.github.com>
@borosf

borosf commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

All five points are addressed at the new head 8ad0123 (= 0bfafb0 plus deduplicating an accidental double definition of lazy_arms).

  1. Concurrent servicing / stale window: arming now keeps a claim ledger. Guards.lazy: BTreeMap<page, Arc<Shadow>> + servicing: BTreeSet<page>; the fault handler claims a page before copying it back, and concurrent faults on the same page spin on yield_now until the first service finishes — so only one thread ever opens the seal, and there is no window where a second writer lands on a still-sealed or torn page. title_memory_aliased now drains (take_lazy + service_lazy) before re-linking instead of forgetting, and title_memory_remapped/retake decrement the counter through forget_lazy.

  2. Kernel reads of sealed pages: copies that will be read without faulting are drained up front. will_read (re-exported as victory_gpu::kernel_will_read) is applied to copy_mapped's source and to net.rs's sendto + WSASendTo (walking the WSABUF descriptors). WSASendMsg is the one remaining unwrapped pass-through I found — noted here rather than guessed at; it can be wrapped the same way if reviewers agree it's needed.

  3. Default-path lock regression: the whole protocol is gated by static LAZY_PAGES: AtomicUsize. With the switch off it is zero, and Shadow::update/writing/the fault handler read it relaxed once and skip every lock and map lookup — no mutex is touched on the default path.

  4. lazy_armed() per Shadow::update: same gate — the relaxed atomic load is the only cost with lazy off.

  5. Handler allocations / README: the handler no longer allocates on the lazy path, and the README row is one line.

Hardware verify (Arc B580, Windows 11): marked_pages_leave_the_submission_and_go_back_at_their_first_access passes on hardware through the real vectored exception handler (a read fault unseals and copies back one page; the guard re-engages; the final state has no lazy pages armed). Full cargo test -p victory-gpu --lib --locked is 230 passed / 2 failed — the two being the known #1744 Intel heap-cap failures that pristine main also fails on this card. cargo clippy -p victory-gpu --all-targets --locked -- -D warnings clean; cargo xtask policy ok.

On the measurement criterion: if/when a card that sustains a world run measures the diagnostics frame-time medians with the switch on vs off at matching draw counts, the mechanism should show most marked pages skipping copy-back entirely (a page never CPU-read gets one VirtualProtect instead of a page copy per submission). If that measurement can't be produced, closing this as a null result on the measurement criterion alone is also fine — with the switch off the change is a provable no-op (the atomic gate), so default behavior and default perf are untouched either way.

@borosf

borosf commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

Measurement at 8ad0123 (Arc B580, Windows 11, release build). Synthetic pools only — no game data used.

cargo test --release -p victory-gpu --lib --locked -- --test-threads=1 --ignored --nocapture frame_copy_back_cost_eager_against_lazy (a temporary ignored test, reverted after the run; the tree is back to 8ad0123): 2,250 marked pages a frame — the world's per-frame mark count — 12 frames a case, a 141 MiB write-watched pool holding one copy, marks and a shader byte per page set each frame, then a share of the pages read by title code.

case copy-back reads total a frame
eager, reads 0 % 33.2 / 32.9 ms 0.00 33.2 / 32.9 ms
eager, reads 50 % 32.4 / 32.9 ms 0.02 32.4 / 32.9 ms
lazy, reads 0 % 61.9 / 56.4 ms 0.00 61.9 / 56.4 ms
lazy, reads 50 % 42.7 / 38.7 ms 21.4 / 19.1 ms 64.1 / 57.8 ms

(Two runs each, same process, the eager cases first so that no sealed page is ever read by an eager copy.)

The arming is fully engaged, not falling back: 2,250 pages sealed a frame, 0 refused by the guard state, 0 by the host. And the pages still go back — 2,062 serviced a frame at 0 % reads, 2,344 at 50 % — because copy_back_marks_with drains every still-armed page at the next submission (take_all_lazy → service_lazy). So the copy-back is paid a frame later rather than removed, and each page adds two protection changes (the seal in arm_lazy, open_lazy at service) plus a fault and a 64 KiB service for every page title code reads. Net 1.7–2.0× the eager frame cost on this card.

One correction to the description while I am here: arm_lazy calls VirtualProtect once per page, not "one VirtualProtect per run of pages".

So this fails the measurement criterion, as I noted in my last comment it might: closing as a null result on measurement alone. Default behaviour is untouched either way — with the switch off LAZY_PAGES is zero and the path is a no-op. For the idea to pay, the next submission would have to drop armed pages it is about to overwrite instead of servicing all of them, which is a different design rather than a tweak to this one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants