Skip to content

fix(libSceAgcDriver): refresh heap mirrors when the range is not write-watched - #6546

Closed
mariuszkreft wants to merge 1 commit into
boykopovar:mainfrom
mariuszkreft:fix/heap-mirror-unwatched-refresh
Closed

mariuszkreft wants to merge 1 commit into
boykopovar:mainfrom
mariuszkreft:fix/heap-mirror-unwatched-refresh

Conversation

@mariuszkreft

@mariuszkreft mariuszkreft commented Oct 15, 2026 •

Copy link
Copy Markdown

What

GuestMemory::CollectWrites returns 0 when the guest arena write watch does not cover a range. GuestMemory.hpp documents that callers must survive this by falling back to comparing bytes, and DispatchLookup.cpp and the mirror creation path (GuestBufferMemory.cpp, if (generation == 0) { ++state.heapUnwatched; return nullptr; }) both do. The three heap mirror refresh paths called Require instead, so on a host without write watching the first heap mirror refresh ended the process:

[videoout] presentation failed: compute shader 0x25b48de00: AGC graphics: a heap mirror's range is no longer write-watched
terminate called after throwing an instance of 'std::runtime_error'

They now count the case in the existing heapUnwatched counter and continue. ChangedBlocks already reports every block as written when the range is unwatched, so the refresh stays conservative and correct, just slower.

Tested

Ubuntu 24.04.5, kernel 7.0.0-31-generic. Grand Theft Auto V (PPSA04264), NVIDIA GeForce RTX 3090, driver 580.159.03. Write watching is off on this host (vm.unprivileged_userfaultfd = 0), which is how the crash reproduces; with this change the title gets past the shader that killed it and reaches its main menu and Story Mode, where it stops later, on an unrelated unimplemented path.

agc_write_tracking, agc_write_watch_coverage, agc_buffer_pool, agc_storage_written_buffer_order, nid_buffer_validation, agc_driver_typed_heaps and agc_driver_graphics pass, and the AGC/driver/buffer/shader ctest subset (498 tests) is green.

Caveat worth stating plainly: those runs used a local checkout whose base is roughly 1,500 commits behind main, since that was the tree the change was developed and debugged in. The branch itself is based on current main and passes the Conventions check, but the branch was not itself built and tested here. Reviewers may want to re-run the suite against this branch.

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
  • Unblocks: PPSA04264 Grand Theft Auto V (PPSA04264) #1203
  • GPUs tested: NVIDIA GeForce RTX 3090, driver 580.159.03, Ubuntu 24.04.5
  • AI-assisted: yes

…e-watched

CollectWrites returns 0 when the guest arena write watch does not cover a
range, which the write-tracking contract says callers must survive by falling
back to comparing bytes. DispatchLookup and the mirror creation path already do;
the three heap mirror refresh paths called Require instead and terminated the
process. ChangedBlocks already reports every block as written when the range is
unwatched, so the refresh stays correct and heapUnwatched records how often the
fallback was taken.
@github-actions

github-actions Bot commented Oct 15, 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 6646 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp L2094-2095, L2196, L2231

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 1191 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 1324 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 2434 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 4448 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 4449 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 5021 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 5372 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6146 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6177 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6185 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6186 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6197 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6292 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6499 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6548 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6615 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6786 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 6947 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7154 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7201 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7233 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7292 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7332 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7489 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7514 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7618 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp
PR 7642 core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp

@AlxcBTW

AlxcBTW commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Minecraft Dungeons II (PPSA16064), Windows 11, RTX 5070 Laptop (NVIDIA 617.42), a build of main with other open PRs: loading the world stopped once in 7 attempts of one job (6 gameplay rows, the aborted one was retried and loaded) with

terminate called after throwing an instance of 'std::runtime_error'
  what():  AGC graphics: a heap mirror's range is no longer write-watched

about 51 s after the start of the row, in the loading screens. The line before the throw in the periodic report had no heap mirror yet (0 heap, unwatched heaps 0), so the mirror was built and lost its watch within 10 s. A heap mirror is built only while CollectWrites covers its whole range (acquireMirror), but the range can leave the write watch afterwards: an import that does not stay watched excludes its 64 KiB blocks, and a staying import whose range is already partly outside the watch drops the whole window. Each build then called CollectWrites over the mirror's range, got 0 and threw. An earlier lab row stopped the same way.

This PR makes that case survive. A test that reproduces it, unwatchedHeapMirrorTests in tests/BdaResources.cpp: it builds a heap mirror over three 64 KiB blocks, takes the middle block out of the watch with GuestMemory::Unwatch, writes three bytes into three blocks from the CPU, builds again (which must not throw and must show all three bytes in the mirror), writes a fourth byte and builds once more.

Run on Windows with Mesa 26.2.4 lavapipe (windows-latest has no Vulkan device; the lavapipe ICD is registered in the loader's registry), ctest entry agc_driver_graphics:

tree result run
03c4cb5 (the base of this PR) plus the test fails: AGC graphics: a heap mirror's range is no longer write-watched 38852204143
1924189 (this PR) plus the test passes (Graphics validation tests passed) 38852194982

The test needs a Vulkan device and a write-watched guest arena, so it runs on Windows with a GPU or lavapipe; the Linux lavapipe job skips it (guest arena unavailable or not write-watched), and a windows-latest runner has no Vulkan device. Patch on top of this PR's head:

--- a/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp
+++ b/core/libs/prx/libSceAgcDriver/tests/BdaResources.cpp
@@ -958,6 +958,62 @@ void importWatchTests() {
 #endif
 }
 
+void unwatchedHeapMirrorTests(const Context& context, const BdaTestAccess& access) {
+    if (!GuestArena::GuestArenaAvailable_nid_postfix() || !GuestArena::GuestArenaWriteWatched_nid_postfix()) {
+        std::cout << "guest arena unavailable or not write-watched: heap mirrors without a write watch not tested\n";
+        return;
+    }
+    constexpr std::size_t bytes = 3 * 65536;
+    void* block = GuestArena::GuestArenaAllocate_nid_postfix(bytes, 65536);
+#ifdef _WIN32
+    GuestArena::GuestArenaCommit_nid_postfix(block, bytes, PAGE_READWRITE, bytes);
+#endif
+    auto* guest = static_cast<std::uint8_t*>(block);
+    std::memset(block, 0x11, bytes);
+    const auto address = reinterpret_cast<std::uintptr_t>(block);
+    const auto registry = [&](bool add) {
+        auto* mutation = GuestAllocations::GuestAllocationsBegin_nid_postfix();
+        if (add) GuestAllocations::GuestAllocationsAdd_nid_postfix(mutation, block, bytes, true, false, true);
+        else GuestAllocations::GuestAllocationsRemove_nid_postfix(mutation, block);
+        GuestAllocations::GuestAllocationsEnd_nid_postfix(mutation);
+    };
+    const auto build = [&] {
+        GuestBufferMemory leased(context);
+        leased.AcquireRegistered();
+        leased.Upload(true);
+        const auto ranges = leased.AddressRanges();
+        const auto found = std::find_if(ranges.begin(), ranges.end(), [&](const auto& range) { return range.begin == address; });
+        Require(found != ranges.end() && found->deviceAddress != 0u, "the heap range is missing from the BDA table");
+        leased.WriteBack();
+        return found->deviceAddress;
+    };
+    const auto sweep = [&] {
+        GuestBufferMemory leased(context);
+        leased.AcquireRegistered();
+        leased.Upload(true);
+        leased.WriteBack();
+    };
+    sweep();
+    registry(true);
+    const auto before = MirrorCounters();
+    build();
+    const auto made = MirrorCounters();
+    Require(made.heapMirrors == before.heapMirrors + 1 && made.heapBytes == before.heapBytes + bytes, "a read-only heap range was not mirrored");
+    AgcDriver::GuestMemory::Unwatch(address + 65536, 65536);
+    Require(!AgcDriver::GuestMemory::Watched(address, bytes), "the heap range is still write-watched after one of its blocks left the watch");
+    guest[7] = 0x22;
+    guest[65536 + 9] = 0x33;
+    guest[2 * 65536 + 11] = 0x44;
+    const auto device = build();
+    Require(access.addressBytes(device)[7] == std::byte{0x22} && access.addressBytes(device)[65536 + 9] == std::byte{0x33} && access.addressBytes(device)[2 * 65536 + 11] == std::byte{0x44}, "a heap mirror whose range left the write watch missed a CPU write");
+    guest[65536 + 13] = 0x55;
+    const auto again = build();
+    Require(access.addressBytes(again)[65536 + 13] == std::byte{0x55} && access.addressBytes(again)[7] == std::byte{0x22}, "a heap mirror whose range left the write watch missed a CPU write of a later build");
+    registry(false);
+    sweep();
+    Require(MirrorCounters().heapMirrors == before.heapMirrors && MirrorCounters().heapBytes == before.heapBytes, "the heap mirror outlived its range");
+}
+
 void heapMirrorTests(const Context& context, const BdaTestAccess& access) {
     if (!GuestArena::GuestArenaAvailable_nid_postfix() || !GuestArena::GuestArenaWriteWatched_nid_postfix()) {
         std::cout << "guest arena unavailable or not write-watched: heap mirrors not tested\n";
@@ -1791,6 +1847,7 @@ void RunBdaResourceTests(const Context& context, const BdaTestAccess& access) {
     importNeighbouringEdgesTests(context);
     importAtMapOverBudgetTests(context);
     heapMirrorTests(context, access);
+    unwatchedHeapMirrorTests(context, access);
     importedHeapMirrorTests(context, access);
     importWatchTests();
     importedFreshTests(context);

AI-assisted: yes

@EagleBearerYS

Copy link
Copy Markdown
Contributor

@mariuszkreft a note from #6646, which handles the same Requires, in case it's useful.

Both PRs keep a heap mirror whose range has left the write watch from failing the build: #6546 refreshes such a mirror in full, and #6646 does too for a refused heap (and plans the range again when the host import path can take it).

One case behaves differently on this branch: a run of adjacent heap mirrors, which refreshHeapMirrors and refreshHeapRuns collect as one range, where only one heap has left the watch. collectWrites returns 0 without walking a range the tracker doesn't fully cover (GuestMemory.cpp:1210 at 1924189), so the CPU's writes into the run's watched heaps aren't collected into their block stamps, and appendChangedBlocks then finds their blocks unchanged.

A test for it: two adjacent 2 MiB heaps registered as one run, one 64 KiB block of the first taken off the watch, a write into each heap, then the next build. On this branch's head, with only the test added, it fails on Linux and Windows, with and without the address-space cache (run):

AGC graphics: the watched heap beside an unwatched one missed the CPU's write

The unwatched heap does serve its new bytes there.

#6646 handles it by collecting each mirror of such a run on its own (appendHeapRun): the unwatched one is refreshed in full, and its watched neighbours by the blocks the CPU wrote. The test is RunHeapMirrorRunUnwatchTests in #6646's tests/BdaResources.cpp (agc_heap_mirror_run_unwatch and _no_space_cache). Happy to share it as a patch for this branch, or to help in any other way.

@adriadam10

Copy link
Copy Markdown
Collaborator

Thanks for the fix and for tracking down the crash. Closing this one in favour of #6646, which handles the same three Requires and one more case this branch gets wrong:

  • GuestMemory::CollectWrites returns 0 without walking a range the tracker doesn't fully cover. refreshHeapMirrors and refreshHeapRuns collect a run of adjacent heap mirrors as one range, so when only one heap has left the watch, the CPU writes into its watched neighbours are never collected and appendChangedBlocks reports their blocks unchanged. Counting heapUnwatched and continuing hides the abort but serves stale bytes there.
  • EagleBearerYS showed it with a test on this head (two adjacent 2 MiB heaps in one run, one block taken off the watch, a write into each): it fails on Linux and Windows with the watched heap beside an unwatched one missed the CPU's write (run). fix(agc): plan a heap again when its mirror's range has left the write watch #6646 collects each mirror of such a run on its own (appendHeapRun) and carries that test.
  • This PR also adds no test; the one in the thread needs Windows plus a Vulkan device and is skipped on the Linux job.

Both PRs edit the same lines in GuestBufferMemory.cpp, so only one can land. Feel free to reopen if you rework it to collect per mirror and include a regression test.

@adriadam10 adriadam10 closed this Oct 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants