Skip to content

fix(agc): publish a host write's whole units first so a unit shadow cannot land over it - #17787

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
Mouhand-Kaddo:fix/agc-host-write-crash
Nov 14, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
Mouhand-Kaddo:fix/agc-host-write-crash

Conversation

@Mouhand-Kaddo

@Mouhand-Kaddo Mouhand-Kaddo commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

What

Since #6926, Demon's Souls (PPSA01342) crashes on Linux most times it loads into the world. It segfaults in its own code while loading (DemonsSouls.elf+0x1788ede). Reverting #6926 or setting APS5_NO_UNIT_SHADOW=1 stops the crash.

Why. A file read can lose its bytes to a unit shadow's GPU results.

  • PrepareHostWrite flushes with ReadSite::Store, so FlushForAccess uses PublishScope::PartialUnits. The units the host write covers wholly stay fresh in their slab. Per UnitShadow.hpp, that is right only if the writer then stamps them, and a host write does not stamp: the tracker only learns about it when a collect walks the written pages.
  • While the read is still copying, another thread can publish those units. In Demon's Souls this is the address-based heaps publish in GuestBufferMemory::UploadFinish. Its collect runs before the pages are written, so it judges the units fresh and its slab → import copy lands over the file bytes.
  • fix(agc): land GPU writes over guest memory before a host write into it #6926 shadows the results over the range right before every host write into image memory, and Demon's Souls reuses image memory as file read buffers.

The fix, as proposed by @JJenkx (co-author):

  1. PrepareHostWrite flushes under its own ReadSite::HostWrite, so FlushForAccess publishes every unit over the range (PublishScope::Whole) before the write. Nothing is left fresh for a later publish to copy over the file bytes, and a short read keeps the GPU's results in the bytes it does not write. Driver stores (ReadSite::Store) keep PartialUnits. WritesGuestMemory(site) keeps host writes counted as stores in the hook sync profile.
  2. A publish on another thread can be caught midway: publishUnits marks its units published before it notes its copy as a pending write, so the host write finds nothing to publish and nothing pending yet. publishUnits now counts itself in progress for its whole body (AnyPublishInProgress), and a host write that sees one in progress takes the GPU mutex and waits for pending writes over its range. With none in progress it stays lock-free.

Tested

Linux 7.2.15, RX 6900 XT (RADV, Mesa 26.2.7), GCC, Release.

  • New test agc_driver_host_write_shadowed_unit. It shadows units of memfd-backed (dma-buf) guest memory and opens a HostWrite over them.

    • A publish while the host write is open, and one between its flush and its write: the host write's bytes survive. Both fail on main.
    • A host write started on another thread from inside a publish, after the publish marks the unit and before it notes its copy: the host write's bytes survive. It fails 5 of 5 runs without the in-progress check and passes 5 of 5 with it.
    • Short writes of 0, 1, 4096, 65535 and 65536 of 64 KiB, two-unit and unaligned ranges: the written bytes and the GPU's results past them survive.

    It skips without /dev/udmabuf or unit shadows.

  • agc_driver_host_write_shadowed_unit, agc_driver_host_write_pending_storage, agc_driver_host_write_hook and agc_driver_gcn_display_present_trigger pass, with and without APS5_PROFILE_DRAW=1.

  • Validation layers (VK_LAYER_KHRONOS_validation 1.4.363): ctest --test-dir build -R 'agc_driver_host_write|agc_driver_gcn_display_present_trigger' -V with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer, on this PR and on main 1414f2c, with and without APS5_PROFILE_DRAW=1. Every log shows Insert instance layer "VK_LAYER_KHRONOS_validation" for each test instance and none has the layer-not-found message. Neither tree logs a VUID- line. Rerun on this head after each rebase onto main: same result.

  • Demon's Souls PPSA01342 v1.004, output 1920x1080, warm shader caches. Each run presses through the menus and keeps running 45 s after loading starts, past the point where main crashes. Runs on main 1414f2c, before that rebase, interleaved one by one in one session, with nothing else running:

    tree runs crashed
    main 3 3, all while loading (+0x1788ede)
    this PR 8 1, in the menus: a call through a null pointer
    the earlier stamp head, rebased 5 0

    Earlier runs on main faea44f: the Whole fix without the in-progress check crashed 2 of 20 times, both in the first 10 while another build was running on the machine (+0x10da241 in the menus, through the same game call path as the null call above, and null or misaligned index base after loading). The stamp head survived 20 of 20.

  • Host write cost: agc_driver_host_write_pending_storage_tests --cost 20000, pinned to one core, 5 runs: 73 to 90 ns per 64 KiB host write, the same as the 72 ns measured on main before. A host write takes the GPU mutex only while a publish is in progress anywhere, so it can wait out another thread's publish then; that cost was not measured.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: PPSA01342 Demon's Souls (PPSA01341) #1283
  • GPUs tested: AMD Radeon RX 6900 XT, RADV (Mesa 26.2.7), Arch Linux (kernel 7.2.15)
  • AI-assisted: yes

@github-actions github-actions Bot added unblocks title Names a title ID on the Unblocks line docs agc libSceAgc* labels Nov 9, 2026
@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 18010 core/libs/prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp L105

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 4448 core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 5609 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 6186 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 6188 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 6192 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 6209 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 7464 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 7642 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 9356 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 9387 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 9712 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 10193 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 10249 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 10442 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 11444 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 13809 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 13863 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 13920 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 13928 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 13929 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/UnitShadow.cpp
PR 15136 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 15548 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 15570 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 16115 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 16372 core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 17611 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 17786 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 17796 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 18078 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 18102 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
PR 18173 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 18185 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 18293 core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 18390 core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 19071 core/libs/prx/libSceAgcDriver/Execution/include/GuestMemory.hpp
core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp
PR 19100 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp
PR 19697 core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp

@maskym

maskym commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Windows + NVIDIA result for head 443a0dd898, merged alone into main 697b66b1e4 (the PR's Tested section names no Windows run).

Host: Windows 11 26300, Intel i7-12700K, NVIDIA GeForce RTX 2070 SUPER, WinLibs GCC 15.2.0 (x86_64-ucrt-posix-seh, r6), Release, BUILD_TESTING=ON, Ninja. Build clean.

Validation-layer protocol on main and on this PR (ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1, VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation, ctest -R '^(agc|guest_video_out|video_out|pad_sdl)' --parallel 4 -V):

Tree Passed Layer inserted was not found but was requested VUID- set
main 1617/1621 1428 0 none
this PR 1618/1622 1428 0 identical

No new validation errors and no new failures. The 4 failures on both trees (agc_driver_msaa_dcc_clear_2, agc_driver_msaa_dcc_clear_4, agc_driver_msaa_dcc_clear_8, agc_driver_native_depth_publication) are pre-existing on main here; they also fail 0 of 3 when rerun alone on this PR's tree.

The tests this PR adds or changes (agc_driver_host_write_shadowed_unit) pass in the full validation-layer run. Not run on a PS5.

AI-assisted: yes (Claude Code), the runs and the numbers above are from this machine.

@JJenkx

JJenkx commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Windows GPU note for head 443a0dd898 (merged onto main 8fbe687d16, AMD Radeon RX 6700 XT, ANYPS5_REQUIRE_VULKAN=1).

  • agc_driver_host_write_shadowed_unit reports Skipped in 3 of 3 runs. It prints "skipped, udmabuf imports are Linux only", as its source intends.

So this PR's test has no Windows coverage; a Linux GPU run is the one that exercises it.

AI-assisted: yes.

@JJenkx

JJenkx commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Additional Linux validation on an RX 6650 XT, RADV, kernel 7.2.14-arch1-1.

Baseline AGC is main 164ac9b078cd; candidate is your 443a0dd898b0, privately composed on that base at 48cd6eade982. Only patched/unpatched AGC libraries differ between the frozen SDK banks. Both retain the same HTTP2 overlay from #11630; these fixtures link AGC and libc, with library paths verified using ldd.

Check Baseline Candidate
host_write_hook, host_write_pending_storage, host_import_proofs, host_import_teardown, three repetitions each 12/12 pass 12/12 pass
Same new host_write_shadowed_unit fixture binary Expected failure, 0/1 3/3 pass

The baseline reproduces both overwrite cases: publication while the host write is open, and publication between its flush and write. In each, byte 0 contains the shadow's GPU results. Both cases preserve the host bytes on the candidate.

All 28 physical GPU executions had zero skips, zero VUIDs and no missing validation layer. Loader logs confirm 104 Khronos layer insertions across the three arms and selection of the RX 6650 XT. Fixture/library hashes remained unchanged. Unit shadows were enabled for these tests. This report makes no new title, Windows or performance claim.

Commands, exact pins, library/fixture hashes, linkage and complete synthetic-test logs. SHA-256: 7952fd240b610d528db094b99b5935b2936e506c6a93bebdaf78858430df615e. Downloaded archive and all 24 manifest members verified. No game assets, captures or binaries included.

AI-assisted: yes (Codex).

@EagleBearerYS

Copy link
Copy Markdown
Contributor

I wrote #6926, so thanks for tracking this down, @Mouhand-Kaddo. Your reading matches the rule in UnitShadow.hpp: every import writer stamps its blocks, but a CPU store stamps only when a collect walks its page. PrepareHostWrite, which #6926 added, flushes with PartialUnits and never stamps. So a publish on another thread before that collect still finds the wholly covered units fresh, and its slab copy lands over the host write's bytes. Stamping after the flush, as the driver's own stores do, closes that, and the second flush waits for any publish recorded in between.

A second title: JJenkx sees a load crash from #6926 in Dusk Diver 2 (PPSA06565), where about half the runs segfault in the title's own code while loading. With this PR 0 of 12 runs crashed, the same as with #6926 reverted (D#10081).

@Kannorhart

Copy link
Copy Markdown

Windows result on a title for head 443a0dd898. Only its GuestMemory.cpp change is applied, on main 016db0480e49.

Host: Windows 11 26300, Ryzen 7 5800X, NVIDIA GeForce RTX 4070 Ti (driver 610.47), WinLibs GCC 15.2.0, Release.

The Pathless (PPSA01825, 02.000.000) crashes intermittently while it loads on main, on Windows. The crashes are access violations in FAsyncLoadingThread, inside Unreal's unversioned property loop, or a LowLevelFatalError; one was in Navmesh Tile Build Thread.

In one crash, the read buffer the loader was parsing held the previous APR read's bytes in its second 64 KiB block, while the first block was fresh. That matches this PR's race on Windows: APR's _readFile copies each read into guest memory in 64 KiB pieces, outside the GPU mutex.

Every run used the same save and pad route and ran for 240 s with APS5_PLAYGO_UNLISTED_CHUNKS=absent. Only libSceAgcDriver.prx differs between the rows.

Driver Runs Crashed while loading APR reads reached (no crash) fps after 120 s (no crash)
main 016db04 16 6 29518-29620 12.2-12.8
main + this PR 16 0 29534-29797 11.6-12.6

On an older main (1c28827), APS5_NO_UNIT_SHADOW=1 and APS5_NO_WRITE_WATCH=1 each gave 0 crashes in 8 runs, against 3 in 12 without them.

Windows coverage for the test. agc_driver_host_write_shadowed_unit skips on Windows, as JJenkx noted. The same case fits into unitShadowTests in tests/Recorder.cpp, which runs on Windows host-pointer imports (agc_unit_shadow, agc_driver_unit_shadow, agc_driver_unit_shadow_budget). On this machine, with ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1 and VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation:

  • it fails on main with a publish made inside a host write copied a unit the write covers;
  • it passes with this PR;
  • neither log has a VUID- line or the layer-not-found message.

It goes after the stale-unit check and releases the GPU mutex that the test's main holds, as a loading thread would:

    retile(*four, unit4, unit, 0x45, false);
    Require(AnyShadowedOverlaps(unit4, unit), "the re-marked unit 4 is not shadowed");
    {
        const auto depth = GpuMutex().DepthOnThisThread();
        for (std::uint32_t level = 0; level < depth; ++level) GpuMutex().unlock();
        PrepareHostWrite(unit4, unit);
        for (std::uint32_t level = 0; level < depth; ++level) GpuMutex().lock();
    }
    {
        std::lock_guard gpu(GpuMutex());
        Require(PublishShadow(unit4, unit, PublishScope::Whole, PublishReason::Evict) == 0, "a publish made inside a host write copied a unit the write covers");
    }
    std::memset(static_cast<std::uint8_t*>(block) + 4 * unit, 0x56, unit);
    recorder.Sync();
    Require(words[4 * unit] == 0x56 && words[4 * unit + 4096] == 0x56 && words[5 * unit - 1] == 0x56 && words[5 * unit] == 0x11, "a publish recorded inside a host write landed over its bytes");

For reference, I also tried a different fix before I found this PR. In FlushForAccess, PartialUnits stayed only for stores whose thread holds the GPU mutex; every other store got Whole, so a host write publishes the units it covers and waits for the copy before it writes. It also gave 0 crashes in 16 runs (fps 11.4-12.6). That variant has no short-read gap, but it waits for a GPU copy whenever a host write covers a live unit. Your stamp is cheaper, so I am not proposing it as a replacement.

AI-assisted: yes.

@dantdmdarealguy

Copy link
Copy Markdown
Contributor

Windows confirmation on a title, since the new test skips on Windows. Demon's Souls PPSA01341 v01.007.000, Windows 11 Pro, i9-14900K, RTX 5080 (driver 32.0.16.1742), WinLibs GCC 15.2.0 Release. Same relinked app.exe and warm shader cache throughout; only the libraries change. Each boot runs 75 s.

libraries boots that crash ~30 s in
main 14bff3fc4a 3 of 6 (5 of 11 overall)
main, APS5_NO_UNIT_SHADOW=1 0 of 6
main + this PR (443a0dd898) 0 of 6
d4060ca168 (before #6926) 0 of 6
9ff8f0b92b (after #6926) 4 of 6

On Windows the crash is the title's own loader reading a table entry that isn't there:

FATAL: unhandled exception 0xc0000005 on thread ... 'BPE JobWorkerThread CPU12'
  rip 0x0000000001a63bbe app.exe+0x1673bbe
  read of 0x0000000000000008
  [rsi] "hkaAnimationContainer"

Once it was a divide by zero while loading $/parts/heads/c_/mn/fc_f_0000_head.cmsh. With this PR, character-creation dialogs that were drawn without text on main render their text, and the intro movie frame that had garbage in its bottom third is clean.

@gabichuuuuu

Copy link
Copy Markdown
Contributor

Windows check of head 443a0dd898, merged onto main 28237a8567 (clean merge, built together with other open PRs that touch different files).

Setup: Windows 11 x64, WinLibs GCC 15.2.0 (r7), Ninja, Release, BUILD_TESTING=ON, Python 3.15.

  • Tests built from this PR's test files: agc_driver_host_write_shadowed_unit.
  • All of them pass in 3 of 3 runs.
  • Negative control: with this PR's code reverted to main (files it adds removed) and rebuilt, the same tests still pass in 2 of 2 runs, so they do not detect the change on this machine.

AI-assisted: yes.

@JJenkx

JJenkx commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Additional Linux/RADV validation on RX 6650 XT, including a second title: OCTOPATH TRAVELER II (PPSA09809), v01.000.000.

Exact versions: main e7c327500d557756732101803c73d470c9ec5fcc; this PR 443a0dd898b01479f232fe6f6f2fa243fbebbcb9; private integration b16c57f9c79e1029945e6959ff40c7a584091694. No other PRs. Production changed lines are identical to this PR; the only integration conflict was additive debt text, with both entries retained. Both SDK/relinker builds completed, with 824 outputs frozen per arm.

Focused tests: identical fixture source against each arm's frozen libraries, ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer, validation 1.4.363:

Test main main + this PR
agc_driver_host_write_hook pass pass
agc_driver_host_write_pending_storage pass pass
agc_driver_host_write_shadowed_unit fails both publication scenarios: byte 0 contains shadow results both scenarios pass

No skips, 0 VUID errors. Full numbered verbose output confirms layer insertion separately in all three fixtures on both arms. Passing-case JUnit output truncates the loader startup, so coverage was verified from the full logs rather than the original JUnit-derived boolean.

Native matched pair: separate writable runtimes copied from the same startup-settings and warm-cache seed, same scripted Cross inputs at 30/45/60/75/90 s, default unit shadows enabled on both arms:

  • main: title visible at 40 s; SIGSEGV, exit 139 at 43.7 s, app.elf+0x4dfa291, fault address 0x205ae5000a.
  • main + this PR: passes that point and reaches the traveler-selection map (reviewed screenshots at 100/127 s). Scheduled close at 150 s gives exit 0 at 152.9 s. Two additional operator inputs after 123 s are retained in the report; no gameplay or character-selection acceptance claim.

All asset/input/provider/seed hash guards passed, kernel setting restored, overlays unmounted and no native processes left. Both native runs and each focused GPU arm used the host FIFO. The candidate still logs transient WAIT_REG_MEM timeouts before progressing, so this is not a claim that all queue warnings are fixed. This is one native pair, supporting progress past the earlier title-screen crash, not a crash-rate study or full-game stability result. No by-ear audio, PS5 pixel-fidelity or FPS improvement claim.

Commands, exact pins, build results, source-preservation proof, GPU logs/JUnit, native logs/reports, cleanup receipts and reviewed screenshots. SHA-256 839f775e625e4d17e567dee80b7b231428cfcace345cc6ed1c4478d2018484a1; downloaded again and all 48 members verified. No game binaries, assets, saves, shader caches or SDK binaries included.

The initial fresh-settings setup run is excluded from this pair: it needed Options to confirm settings, reached the title and required final harness SIGTERM. Its retained settings/cache supplied the common seed; it is not counted as a passing control.

Longer follow-up on the same frozen integration: a corrected bounded run selected Agnea, confirmed her start, passed the opening text and displayed her theatre-stage scene. Scheduled close completed normally: native exit 0, observer exit 0, 339.6 s. All asset/input/provider/cache-seed hash and cleanup guards passed. This is chapter-opening verification; interactive gameplay and character movement remain unverified. The stage capture is dark and may be a fade; no rendering-fidelity or brightness-fix claim. Earlier interrupted longer harness attempts are excluded.

Follow-up commands, report, full log, reviewed captures and limits, SHA-256 1821db5bb62a2b0f4ceaa9e2365fd0097cb56602b73f158f85b568a9a8e46079; archive and all 12 members downloaded/hash-verified. This follow-up uses a warmed cache and has no paired FPS comparison or by-ear audio claim.

AI-assisted: yes

@JJenkx

JJenkx commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Current-main candidate-only check of this host-write fix on Asterigos: Curse of the Stars, PPSA08194 v01.004.001, Linux/RADV RX 6650 XT.

Exact pins: main a221a742da421fc7b3b3f7c139346fe1b8642058, PR head 443a0dd898b01479f232fe6f6f2fa243fbebbcb9, private integration 9765b76bce4458f0e058d56246ab2b23f20d75a1. No other unmerged PRs; additive debt conflict retained both entries. Default unit shadows, without APS5_NO_UNIT_f8f9e521054d5a4b33172aa300f1e3ede13f3c247209466d838953490f7c01a7DOW. Independent writable runtime, private copy of inactive pristine settings/save, fresh shader caches.

Observed: native GPU frames show the title/main menu, New Game selected, Adventure difficulty, and the opening Begin loading illustration after holding Cross. The bounded 360 s run closed normally: native and observer exit 0, elapsed 365.9 s. All original asset/input/save, frozen-provider, kernel-restoration and unmount guards passed; no native process remained. This establishes startup and new-game loading only: no gameplay or Continue/save-reload verification.

Four focused physical Vulkan checks passed: agc_driver_host_write_hook, agc_driver_host_write_pending_storage, agc_driver_host_write_shadowed_unit, agc_driver_gcn_display_present_trigger. Validation 1.4.363 inserted separately in each case, no skips or VUID errors. These are candidate-only sanity checks; the earlier Octopath report provides the paired main/change regression result.

Limits: one candidate native run, no current-main native control, no crash-rate reduction or FPS gain claim, no by-ear audio or PS5 pixel-fidelity claim. Native capture requests affect timing. Initial native-r1 failed only a relinker duplicate-module-directory preflight; it never launched the title and is excluded.

Evidentiary pins, reviewed GPU frames, focused test commands/log/JUnit and cleanup summary. f8f9e521054d5a4b33172aa300f1e3ede13f3c247209466d838953490f7c01a7-256 f8f9e521054d5a4b33172aa300f1e3ede13f3c247209466d838953490f7c01a7; downloaded and all 12 archive members verified. No game/SDK binaries, saves or shader caches.

AI-assisted: yes

Longer gameplay follow-up on the same frozen pins: the second actual native run reaches Outerrim, dismisses the Exploration and Interaction tutorial, and displays the health/mana HUD and “Check surroundings for anything unusual” objective. Native GPU captures before/after a forward-stick pulse show the changed position/viewpoint. Ordinary scheduled close gives native/observer exit 0 at 423.6 s, all original-input/save/provider/kernel/unmount guards pass and no native process remains.

A single official seconds 5:5 trace after reaching the scene captures 55 presents at 1920×1080: frame p50 91.431 ms, p90 100.686, p99 115.904; GPU busy 48.152 ms/present, trace_dropped=false. Inclusive phases include Driver.Draw.shader_compile_and_link 26.213 ms/frame and Driver.Packet.memory_wait 83.785 ms/frame; these overlap other work and must not be added together or called independent CPU bottlenecks. No optional GPU-draw profiling was enabled. Native screenshots were captured near this interval, so this is diagnostic data rather than an uninstrumented benchmark.

Cold startup created roughly 3,849 shader-cache entries before the level settled. The new private autosave and warm caches are retained to shorten the next iteration, but checkpoint reload is not yet verified. The scene has strong bright haze; no PS5 visual-fidelity or by-ear audio comparison was made.

This remains one candidate integration, pinned main a221a742da42 + #17787, not the newer upstream tip or a fresh main/control pair. It does not establish a crash-rate reduction, full-game stability or an FPS gain.

Reviewed native GPU frames, exact pins, full official trace/summary, trace digest, input receipts and cleanup review — SHA-256 1fb6147b1c4b4cf4aae84dd6670e686639d587bf36ebc200d980f83c4605cb55; downloaded and all 10 members verified. No game/SDK binaries, saves or shader caches are in this archive.

@JJenkx

JJenkx commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

I reproduced the documented short-write gap and tested an alternative to the stamp + second flush. This is support for this PR; I have not opened a competing PR.

PrepareHostWrite receives a requested extent. ReadSite::Store currently selects PartialUnits, which can skip an entire dirty shadow unit before a host operation writes fewer bytes (including zero). Stamping the requested extent then discards the GPU-produced unwritten tail. In the regression, a 64 KiB requested write returning 0/1/4096/65535 bytes preserves stale import bytes after the actual written prefix; a full 65536-byte write passes.

The alternative tracks host-write preparation with a thread-local flag scoped by the existing RAII guard and selects PublishScope::Whole during that preparation. Ordinary driver stores retain PartialUnits. The PrepareHostWrite body is identical to pinned main, with no extra stamp or second flush. This passes both original publication-race cases from your fixture and nine additional zero/short/full, two-unit and unaligned guarded cases.

Alternative diff against tested main. Your original test remains credited through the branch history; the archive also includes a standalone diff.

Linux/RADV RX 6650 XT, physical watched dma-buf Vulkan memory, validation 1.4.363:

Arm Passed case-runs Expected failures
main 15f20bb9425d 7 original publication race + short write, both profiling modes
this PR 443a0dd898b0 plus expanded fixture 9 short write, both profiling modes
this PR plus Whole publication 11 none
standalone alternative 7e9b5642054f 11 none
final cleanup/debt head 92623aa7ec60 4 none; rerun original race + short write, both modes

The 11 runs cover five groups with default / APS5_PROFILE_DRAW=1, plus HostWritePendingStorage --cost 20000. No skips or validation VUIDs; per-case GPU/layer insertion and binary immutability checked, kernel setting restored. Conventions and public-header audit pass.

Synthetic idle preparation cost (best of 5 × 20000, same pinned CPU): main 48.5/46.4 ns, this PR 115.8/118.2 ns, standalone alternative 53.7/52.5 ns, for unrelated-image-pending / nothing-pending respectively. These are not title performance results. Whole publication may copy prior contents even when a later host write is full; dirty-unit/title timing and Windows/other GPUs remain unmeasured.

Your refreshed head 3b0aa272dec1 still has the same PrepareHostWrite body calling landBeforeHostWrite. I inspected that refresh but did not build or test it; the table is restricted to the exact earlier pins. The previously posted native title checks are not rerun or attributed to this alternative.

Commands, source pins, patch, environment, verbose tests/JUnit and hash guards, SHA-256 a44fa33c59464831969849c06eed74e880d7976681f92b508ebc5d30e82c2fc1. Downloaded again and all 37 manifest members verified. No game/SDK binaries, assets, caches, saves or native-title stacks included.

AI-assisted: yes

@JJenkx

JJenkx commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Native qualification of the Whole-publication alternative on Asterigos, PPSA08194 v01.004.001, Linux/RADV RX 6650 XT:

  • Main e41883767570e11a83227e7ceaab2ea35ce5015b versus the same main plus the alternative, integration 8fbd1a27639fee13014ab6d296daf3f5ccd9dd24. Only three production files differ; no host-write stamp or second flush. No other unmerged production change.
  • Both native runs reach Continue → Outerrim, with the same stationary checkpoint/camera, character, objective and HUD directly reviewed in native GPU captures. Scheduled close gives native/observer exit 0: main 382.7 s, alternative 382.2 s. These elapsed values include the deliberately fixed run duration; they are not load-time measurements.
  • Separate immutable 418-file library banks and writable runtimes, same private save/cache seed and scripted input. Every original-input/save/cache/provider, kernel-restoration and unmount guard passes; no native process remains. Whole GPU/native harnesses queued separately under the shared host FIFO.
  • Five focused GPU groups × default/draw-profile modes: main 6 pass + 4 expected failures (original shadow race and short-write, both modes), alternative 10 pass. Physical RX 6650 XT and validation 1.4.363 inserted per case; no skips or VUIDs. Conventions pass.

Limits: one native pair, not a crash-rate study; the passing main control does not contradict earlier intermittent startup failures. The previous cache seed is identical and hash-checked, but both builds record 0 shader-cache hits / 3913 misses, so loading is effectively cold. No FPS gain, movement, by-ear audio, or PS5 pixel/lighting-fidelity claim. Strong bright haze is visible in both arms; transient WAIT_REG_MEM timeouts remain.

Exact pins, source scope, commands, preservation/cleanup results, reviewed native frames, observer reports and paired GPU logs/JUnit. SHA-256 d63d6e8771b44a5770c876a2ab0728d5503f55dcb5d24f656ea7fdbf1e1d7894; downloaded again and all 25 manifest members verified. No game/SDK binaries, assets, saves, caches or native stacks included.

AI-assisted: yes

@Mouhand-Kaddo
Mouhand-Kaddo force-pushed the fix/agc-host-write-crash branch from 3b0aa27 to 2c40ed8 Compare November 13, 2026 09:40
@Mouhand-Kaddo Mouhand-Kaddo changed the title fix(agc): stamp a host write's range so a unit shadow publish cannot land over it fix(agc): publish a host write's whole units first so a unit shadow cannot land over it Nov 13, 2026
@Mouhand-Kaddo

Copy link
Copy Markdown
Contributor Author

Note

🤖 Claude Opus 5.5 responding on behalf of @Mouhand-Kaddo

@JJenkx, your Whole-publication approach is now this PR's fix, with you as co-author (head 2c40ed8115). The short-write gap it closes was real, and it costs about what main does: 72 to 85 ns per 64 KiB host write, against 193 ns for the stamp and second flush.

Changes from your branch:

  • PrepareHostWrite names itself with a new ReadSite::HostWrite instead of a thread-local flag next to ReadSite::Store. FlushForAccess then picks Whole from the site alone. Nested stores during the flush (completion write-backs set their own ReadSite::Store) keep PartialUnits, while the flag covered them too. WritesGuestMemory(site) keeps host writes counted as stores in the hook sync profile.
  • Your short-write cases run in the same process as the two race cases, so the test needs no argument or extra CMake fragment.
  • No debt entry: the gap it recorded is closed.

Demon's Souls PPSA01342 on Linux/RADV RX 6900 XT, base faea44f22c: main crashed while loading 3 of 3 runs. This change ran 20 times with 2 crashes in the first 10, while another build was running on the machine (+0x10da241 in the menus, null or misaligned index base after loading). The 10 later runs, interleaved one by one with the stamp version, all survived. Details are in the PR body.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

I read the new design against the stamp head. It is simpler and the ReadSite::HostWrite enumerator is added consistently (name table, Count-sized arrays, the three WritesGuestMemory uses in Recorder.cpp). Two things I would like you to look at; neither blocks.

  1. FlushForAccess checks for pending GPU writes under the GPU mutex, releases it, and PublishShadowsOnly then calls AnyShadowedOverlaps before taking the mutex again (Texture.cpp:5335-5337). If another thread publishes the same units in that gap, they are no longer live, so this thread publishes nothing and does not sync, and the other thread's recorded copy can still run after the host write. The stamp head's second flush covered that. A pending-write check and sync after the publish when the site is HostWrite would close it, and the second race case in the test (publish after the flush) now passes trivially, so it does not cover this window.
  2. Of the 20 Demon's Souls runs, 2 crashed at other sites (+0x10da241 in the menus, and null or misaligned index base after loading). That second message reads like a stale or torn guest read, so please post both logs and, if you can, matched runs of main, the stamp head and this head on the same load, so we can tell whether it is the same family.

@Mouhand-Kaddo
Mouhand-Kaddo force-pushed the fix/agc-host-write-crash branch from 2c40ed8 to f5df02a Compare November 13, 2026 11:33
@Mouhand-Kaddo

Copy link
Copy Markdown
Contributor Author

Note

🤖 Claude Opus 5.5 responding on behalf of @Mouhand-Kaddo

@oneandonlydean, both points are addressed in f5df02af10.

1. The publish gap: real, and now closed. A publish that finishes entirely between the pending-write check and PublishShadowsOnly was already caught: it notes its copy (recordCopies → NotePendingWrites) before it returns, and the final sync condition includes SnapshotOverlaps. The hole was a publish caught midway. publishUnits marks the units published under the registry mutex and only then records and notes the copy, all under the other thread's GPU mutex. A host write checking AnyShadowedOverlaps in between sees nothing live and nothing pending, so it skips the sync.

  • publishUnits now holds a PublishInProgress count for its whole body. FlushForAccess adds site == HostWrite && AnyPublishInProgress() to its final sync condition, so that host write takes the GPU mutex (waiting out the publish) and syncs through its range. With no publish in progress it stays lock-free: 73 to 90 ns per 64 KiB host write, as before.
  • The new case HostWriteWaitsForAPublishInProgress starts the host write on another thread from the publish-selected hook, which fires exactly in that gap, and requires that it reached its flush there. It fails 5 of 5 runs with the check disabled and passes 5 of 5 with it.
  • The second case (a publish after the flush) does pass trivially under Whole. I kept it because it still fails on main and would catch a return to PartialUnits for host writes.

2. The two other crash sites. Logs (local paths replaced by <runtime>):

  • demons-souls-menu-segfault.log: SIGSEGV reading null+0x48 at +0x10da241, about 72 s in, in the menus.
  • demons-souls-index-base-abort.log: [gpu] driver failure: null or misaligned index base after loading into the world.

Both came from the Whole fix without the in-progress check, in the first 10 of 20 runs, while another build was running on the machine. Matched runs on main 1414f2c, interleaved one by one in one session with nothing else running:

tree runs crashed
main 3 3, all while loading (+0x1788ede)
this head 8 1, in the menus
stamp head, rebased (bb2072d3e6) 5 0

The crash on this head is a call through a null pointer, about 110 s in. Its stack runs through the same game frames as the first log (+0x87293b, +0x869046), so it looks like the same family. Across today the stamp head is 0 for 25. This is not significant on its own (3 of 29 for the Whole variants against 0 of 25), and I have no mechanism tying it to the change yet.

@Mouhand-Kaddo

Mouhand-Kaddo commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Note

🤖 Claude Opus 5.5 responding on behalf of @Mouhand-Kaddo

#18010 overlaps this PR in more than the UnitShadow.hpp line (both add one declaration after AnyShadowedOverlaps; that part merges either way). Its early return in FlushForAccess would skip this PR's publish-in-progress check:

  • perf(agc): answer clear accesses at the top of the flush hook #18010 returns at the top of the hook when ClearAccess holds: no pending clear storage on the thread, LiveUnitsClear, and no overlap in the thread's snapshot copy.
  • Another thread's publishUnits marks its units published and calls liveChanged() before it records and notes its copy. A host write in that gap sees no live units and no pending write, returns early, and the copy lands over its bytes later. That is the window HostWriteWaitsForAPublishInProgress covers.

Whichever lands second needs the early return to leave a host write to the rest of the hook while a publish is in progress:

if (HookClearAccess() && HookSnapshotEnabled() && !HookFlushCpuBlocks() && !(GuestMemory::CurrentReadSite() == GuestMemory::ReadSite::HostWrite && AnyPublishInProgress()) && ClearAccess(address, bytes)) {

Checked on a local merge of this head and #18010: HostWriteWaitsForAPublishInProgress fails 5 of 5 runs as merged, and passes 5 of 5 with that condition (the other host-write tests pass too). Not a dependency in either direction.

@Mouhand-Kaddo
Mouhand-Kaddo force-pushed the fix/agc-host-write-crash branch from f5df02a to 0c2c1a8 Compare November 13, 2026 14:42
@Mouhand-Kaddo

Copy link
Copy Markdown
Contributor Author

Note

🤖 Claude Opus 5.5 responding on behalf of @Mouhand-Kaddo

The Windows failure on 0c2c1a8a05 is not from this change: guest_ces_wide and guest_ces_wide_module hit the 120 s timeout with no output (job).

  • This PR only touches libSceAgcDriver. Both tests passed in 4.3 s on the previous head (f5df02af10, before the rebase onto main), and pass in 1.4 s on Linux at this head.
  • The same two tests time out on Windows in another PR's run on the same day: run 43448143220 (codex/nkwebkit-document-loader-notifications-four).
  • The previous Windows failure (guest_socket_stream_options, errno 22) was the check revert: socket error precedence coverage (#14472) #19489 reverted; the rebase picked that up.

I can't rerun the job from the fork. Could someone with access rerun the failed Windows job?

@blawesom

Copy link
Copy Markdown
Contributor

Validation: queue item 45 — PR #17787 (AGC host-write publication vs unit shadow)

Automated sequential-queue validation run (item 45 of 50). Verdict: PASS (Linux/AMD scoped).

Environment

  • Machine: CachyOS, kernel 7.3.4-1-cachyos, Ryzen 7 9800X3D, AMD Radeon RX 9070 XT (RADV GFX1201) + AI PRO R9700, /dev/kfd present
  • Compilers: gcc/g++, CMake Ninja, CMAKE_BUILD_TYPE=Release, BUILD_TESTING=ON, CMAKE_BUILD_PARALLEL_LEVEL=12 / --parallel 12
  • Validation layer: VK_ADD_LAYER_PATH=/home/benj/scratch/vvl-layer (VK_LAYER_KHRONOS_validation)

Commits

  • Base (origin/main at validation time): a9f291040088cac6babfbe270c50f344a4f6f27d — worktree /home/benj/scratch/wt5/base-main (reused existing build, read-only, clean)
  • PR head: 0c2c1a8a05865d97f5c2697fde88bb8476ff0426 "fix(agc): publish a host write's whole units first so a unit shadow cannot land over it" — worktree /home/benj/scratch/wt5/pr-17787 (PR state re-checked: OPEN, headRefOid matches)
  • PR touches: GuestMemory.{hpp,cpp} (new ReadSite::HostWrite + WritesGuestMemory), UnitShadow.{hpp,cpp} (AnyPublishInProgress), Recorder.cpp, new test tests/execution/HostWriteShadowedUnit.cpp

Build

  • Configure: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++ -DBUILD_TESTING=ON → exit 0, wall 11 s (log q45-pr17787-configure.log)
  • Build: cmake --build build --parallel 12 (timeout 7200) → exit 0, wall 351 s, 9857/9857 targets (log q45-pr17787-build.log)

Focused tests (identical matched set in both trees, 13 tests)

Pattern (from ctest -N in both trees, diff-verified identical): host_write_hook|host_write_pending_storage|unit_shadow|small_tiled_shadow|reg_shadow|idle_publish|shadowed_key_stores|bda_reads_shadowed_results
Matched: agc_driver_host_write_hook, agc_driver_host_write_pending_storage, agc_unit_shadow, agc_idle_publish_dmabuf_wait, agc_idle_publish_wait, agc_driver_bda_reads_shadowed_results, agc_driver_bda_reads_shadowed_results_per_build, agc_unit_shadow_completion_store, agc_shadowed_key_stores, agc_driver_unit_shadow, agc_driver_unit_shadow_budget, agc_small_tiled_shadow_label, agc_driver_reg_shadow_info
(The PR-only new test agc_driver_host_write_shadowed_unit is intentionally outside this pattern so both trees match; it was run separately, below.)

Test command (both trees, identical env, timeout 3600):
ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_ADD_LAYER_PATH=/home/benj/scratch/vvl-layer VK_LOADER_DEBUG=layer ANYPS5_GPU='AMD Radeon RX 9070 XT' ctest --test-dir build -R '<pattern>' -V

Results

Tree ctest exit Passed Skipped Failed wall
base a9f29104 0 13/13 (4 ran and passed, 9 skipped) 9 0 0 s (log q45-tests-base.log)
PR 0c2c1a8a 0 13/13 (same 4 passed, same 9 skipped) 9 0 1 s (log q45-tests-pr.log)

Per-test pass/skip outcomes are identical between base and PR (same test names, same status). Skips are device-capability skips on RADV (e.g. "the device does not import watched host memory for unit shadows"), identical in both trees, not failures.

Supplemental (PR tree only): ctest -R '^agc_driver_host_write_shadowed_unit$' -V with the same env → 1/1 Passed, exit 0 (log q45-tests-pr-newtest.log).

Layer checks (per AGENTS.md)

  • was not found but was requested by env var VK_INSTANCE_LAYERS: 0 occurrences in all three logs (base, PR, new-test)
  • Insert instance layer "VK_LAYER_KHRONOS_validation": present in all three logs (14/14/1)

Validation-error diff (VUID-/SYNC-HAZARD/bracketed IDs)

  • VUID-* / SYNC-HAZARD-* / Validation Error / Validation Warning occurrences: base = 0, PR = 0 → diff empty, no new IDs introduced by the PR

Push

  • git push fork +0c2c1a8a05865d97f5c2697fde88bb8476ff0426:refs/heads/validation/pr-17787 → ref refs/heads/validation/pr-17787 on blawesom/AnyPS5

Verdict

PASS — build clean, 13/13 focused AGC tests pass with identical per-test outcomes vs base, validation layer inserted in every run, zero validation errors in both trees, and the PR's new regression test agc_driver_host_write_shadowed_unit passes.

Limitations

  • Linux + AMD RADV (RX 9070 XT) only; no NVIDIA/Intel/AMD-PRO or Windows coverage.
  • 9 of 13 focused tests skip on this device for capability reasons (identical on base and PR), so the executed subset is 4 tests plus the PR-only new test; the unit-shadow code paths that need watched host memory imports are not exercised on RADV.
  • Single run per tree (no repetition); intermittent faults are not ruled out.
  • The PR branch contains other commits on top of the base beyond its own fix commit; VUID attribution was unambiguous here because both trees produced zero validation diagnostics.

@moong15

moong15 commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

Stellar Blade (PPSA13197) on Windows hits what looks like the same regression: since #6926, FAsyncLoadingThread crashes with 0xc0000005 45-75 s into most launches while it parses package summaries. The summary buffers it reads are zeroed or garbage, in 64 KiB-aligned guest ranges, and some launches instead abort with a UE4 out-of-memory error on a garbage size.

Bisect of main (first-parent, Oct 22 to Nov 13; the #12970 instance lock range was tested with #12970 reverted so the game can relaunch):

build crashed launches
66db234b2d (merge before #6926) 0 of 8
a2624e4313 (#6926) 3 of 4
main 8de3dc8140 about 85%
main 8de3dc8140 with only the GuestArenaSetHostWriteHook_nid_no_patch(&GuestMemory::PrepareHostWrite) registration removed 0 of 8

AMD Radeon RX 9070 XT, Windows 11. I have not run this PR's branch or APS5_NO_UNIT_SHADOW=1 yet, so I can't say whether this fix covers it.

@Mouhand-Kaddo

Copy link
Copy Markdown
Contributor Author

Note

🤖 Claude Opus 5.5 responding on behalf of @Mouhand-Kaddo

@moong15, that fits this bug. Removing the PrepareHostWrite registration removes the flush #6926 added before every host write, and that flush is what left wholly covered units fresh for another thread's publish to copy over the read buffer. Zeroed or stale package summaries in 64 KiB-aligned ranges (one unit shadow unit each) are what that copy produces when a file read lands in reused image memory.

Could you run this PR's head, 0c2c1a8a05, with the hook registered as on main? Two runs would settle it:

  • this head with defaults (the fix);
  • main with APS5_NO_UNIT_SHADOW=1, to confirm the crash goes through unit shadows.

Nothing in the fix is Windows-specific, but nobody has run it on Windows yet, so a crash count over the same 8 launches would be the first result there.

…annot land over it

Co-authored-by: JJenkx <31495916+JJenkx@users.noreply.github.com>
@Mouhand-Kaddo
Mouhand-Kaddo force-pushed the fix/agc-host-write-crash branch from 0c2c1a8 to 2d2c4ec Compare November 14, 2026 08:58
@github-actions github-actions Bot added the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 14, 2026

@Superseabas Superseabas 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.

Windows check of head 2d2c4ec1ad on two GPUs, merged onto main 3ffcba66e0. The bug reproduces on Windows, and this PR fixes it there, using a Windows port of the new test (below). It may also be what @moong15 sees in Stellar Blade on Windows.

Setup: Windows 11 Home 10.0.26200, WinLibs GCC 16.2.0 (x86_64-ucrt-posix-seh, r3), Release, run from PowerShell with ANYPS5_REQUIRE_VULKAN=1, ANYPS5_NO_SHADER_CACHE=1 and the Khronos validation layer. GPUs: NVIDIA GeForce RTX 5070 Ti (621.01) and the Ryzen 7 7700X's integrated AMD Radeon (Adrenalin 26.10.2). main doesn't build on Windows right now (#18037's setenv in UploadCacheReadOnlyFlush.cpp), so both sides carry #19899 only so they build.

No regressions: ctest -R '^agc|gpu|vulkan|video_out' on main and with this PR:

main this PR
RTX 5070 Ti 0 failed of 1828 0 failed of 1829
Radeon 1 failed of 1828 1 failed of 1829

The one Radeon failure is agc_driver_sample_order_grid_reference on both sides (fixed by #9503). The extra test is agc_driver_host_write_shadowed_unit, which skips here. No other test changes its result, and there are no validation messages on either GPU, on either side.

The new test on Windows. As it is, it skips on Windows ("udmabuf imports are Linux only"). Only its setup is Linux-specific. On Windows, a 1 MiB guest-arena block imported through a host pointer stays write-watched: the driver's import probe reports "host imports of write-watched memory keep the write watch: yes … direct host imports of private memory are settled and stay watched" on both GPUs. So I ported the setup, leaving every check as it is (patch below), and ran it 3 times per GPU:

RTX 5070 Ti Radeon
main's driver code (the PR's 5 production files reverted) fails 3 of 3 fails 3 of 3
this PR passes 3 of 3 passes 3 of 3

On main, both GPUs fail the same 4 cases. In the two "host write over a shadowed unit" cases and "host write during another thread's publish of its unit", byte 0 holds the shadow's GPU results instead of the host write's. "short host write of 65553 of 131072 bytes at +0" fails with "byte 65553 holds 51, not 190". The other 8 short-write cases pass on main too. With this PR every case passes, with no validation messages.

The Windows port of HostWriteShadowedUnit.cpp (built and run on both GPUs; macOS keeps a stub)
--- a/core/libs/prx/libSceAgcDriver/tests/execution/HostWriteShadowedUnit.cpp
+++ b/core/libs/prx/libSceAgcDriver/tests/execution/HostWriteShadowedUnit.cpp
@@ -8,6 +8,9 @@
 #include "VulkanTestDevice.hpp"
 #include "prx/libc/include/GuestArena.hpp"
 #include "prx/libc/include/GuestWriteWatch.hpp"
+#ifdef _WIN32
+#include <windows.h>
+#endif
 #ifdef __linux__
 #include <fcntl.h>
 #include <sys/mman.h>
@@ -25,9 +28,9 @@
 #include <thread>
 #include <utility>
 
-#ifndef __linux__
+#if !defined(__linux__) && !defined(_WIN32)
 int main() {
-    std::printf("skipped, udmabuf imports are Linux only\n");
+    std::printf("skipped, host imports of write-watched memory are tested on Linux and Windows only\n");
     return VulkanTestSkipped;
 }
 #else
@@ -52,6 +55,7 @@
 std::uint8_t* mapping = nullptr;
 int backing = -1;
 
+#ifdef __linux__
 bool Resolve(std::uintptr_t address, std::size_t bytes, int* file, std::uint64_t* offset) {
     const auto begin = reinterpret_cast<std::uintptr_t>(mapping);
     if (address < begin || address + bytes > begin + MappingBytes) return false;
@@ -59,6 +63,7 @@
     *offset = address - begin;
     return *file >= 0;
 }
+#endif
 
 int Skip(const char* why) {
     std::printf("skipped, %s\n", why);
@@ -213,6 +218,15 @@
 int main() {
     using namespace AgcDriver::Graphics;
     try {
+#ifdef _WIN32
+        auto device = OpenVulkanTestDevice();
+        if (!device) return VulkanTestSkipped;
+        if (!UnitShadowEnabled()) return Skip("unit shadows are off");
+        mapping = static_cast<std::uint8_t*>(GuestArena::GuestArenaAllocate_nid_postfix(MappingBytes, 65536));
+        Require(mapping != nullptr, "host write over a shadowed unit: cannot allocate the arena block");
+        GuestArena::GuestArenaCommit_nid_postfix(mapping, MappingBytes, PAGE_READWRITE, MappingBytes);
+        std::memset(mapping, AroundByte, MappingBytes);
+#else
         const int udmabuf = open("/dev/udmabuf", O_RDWR | O_CLOEXEC);
         if (udmabuf < 0) return Skip("host imports are unavailable: /dev/udmabuf is not accessible");
         close(udmabuf);
@@ -228,6 +242,7 @@
         mapping = static_cast<std::uint8_t*>(mapped);
         GuestArena::GuestArenaSetSharedBacking_nid_postfix(Resolve);
         std::memset(mapping, AroundByte, MappingBytes);
+#endif
 
         const auto address = reinterpret_cast<std::uint64_t>(mapping);
         GuestAllocations::Mutation().Add(mapping, MappingBytes, true, true, true);
@@ -237,7 +252,9 @@
         }
         Require(ranges.size() == 1, "host write over a shadowed unit: the allocation is not registered");
         Require(device->ImportGuestMemory(ranges, GuestAllocations::GuestAllocationsGeneration_nid_postfix(), false), "host write over a shadowed unit: the import made without the GPU lock was refused");
+#ifndef _WIN32
         GuestWriteWatch::GuestWriteWatchRegister_nid_postfix(mapping, MappingBytes);
+#endif
 
         const auto firstUnit = (address + Unit - 1) & ~(Unit - 1);
         const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(*device);
@@ -246,7 +263,11 @@
             std::lock_guard lock(AgcDriver::GuestMemory::GpuMutex());
             import = HostImportFor(context, address, MappingBytes);
         }
+#ifdef _WIN32
+        if (import == nullptr) return Skip("no host import of the arena block");
+#else
         if (import == nullptr || !import->dmaBuf) return Skip("the device imported the mapping through a host pointer, which is compared, not watched");
+#endif
         if (!AgcDriver::GuestMemory::Watched(firstUnit, 8 * Unit)) return Skip("the imported units are not write-watched");
 
         landHook = AgcDriver::GuestMemory::CurrentFlushHook();
@@ -266,7 +287,9 @@
         AgcDriver::GuestMemory::SetFlushHook(landHook);
         Require(passed, "host write over a shadowed unit: a publish put a unit shadow's results over a host write, or a short host write lost the GPU's results past it");
 
+#ifndef _WIN32
         GuestWriteWatch::GuestWriteWatchUnregister_nid_postfix(mapping, MappingBytes);
+#endif
         GuestAllocations::Mutation().Remove(mapping);
         std::cout << "host write shadowed unit tests passed\n";
         return 0;

Windows arena memory is write-watched without GuestWriteWatchRegister, as in SampledCacheBudget.cpp's WatchedSurface. 1 MiB is also Windows' floor (settleFloorBytes) for keeping a settled import watched. The main failures and the PR passes in the tables above are from this patch plus one diagnostic print. The patch as shown was then built and passed once more on each GPU. I haven't built it on Linux or macOS.

I'd suggest adding the Windows setup, so the regression test also covers the platform where Stellar Blade crashes. That's optional for this PR.

Reading the change: tagging host writes ReadSite::HostWrite instead of Store is what makes FlushForAccess choose PublishScope::Whole for them. WritesGuestMemory keeps the hook-sync profiling treating them as stores. The AnyPublishInProgress wait covers the case where another thread's publish is already under way. One small, non-blocking point: PublishShadow's skip inside a completion (UnitShadow.cpp, Recorder::InCompletion() && CurrentReadSite() == ReadSite::Store) still names only Store. I found no path where a host write runs inside a completion: the driver's own GuestArena::HostWrite is under OwnHostWrite, so PrepareHostWrite returns early for it. But WritesGuestMemory there would keep the two sites alike.

Not run: Linux, macOS, and a title (I don't have Demon's Souls or Stellar Blade).

AI-assisted: yes (Claude Code)

@oneandonlydean
oneandonlydean merged commit 65178ec into boykopovar:main Nov 14, 2026
13 of 15 checks passed
@github-actions github-actions Bot removed the review queue Next in the maintainer review queue: checks pass, no open change request, no conflict label Nov 14, 2026
moong15 added a commit to moong15/AnyPS5 that referenced this pull request Nov 14, 2026
…dow fix lands

Fork only. Since boykopovar#6926 the hook flushes pending GPU results over every host
write; Stellar Blade's loader then reads clobbered package summaries and
crashes in about 85% of launches (0 of 8 with the hook off, 2026-11-14).
Drop this commit once boykopovar#17787 or another fix is on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agc libSceAgc* docs unblocks title Names a title ID on the Unblocks line

Projects

None yet

Development

Successfully merging this pull request may close these issues.