fix(libc): wait only for imports over the freed span #12157

Open
ulissesemuman wants to merge 2 commits from upstream-pr/12157 into main
ulissesemuman commented 2026-10-27 23:57:01 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ulissesemuman on 2026-10-27T23:57:01Z.


GuestAllocationsRequireUnpinned decides whether a guest free() may mutate an
allocation by testing range.use_count() != 1 on the registered Range that covers
the address. The AGC driver imports memory in windows of at most 64 MiB out of arenas
that are far larger (the block that fails here is 16 KiB inside a 1.4 GiB arena), so a
host import of any other part of the arena keeps every shared_ptr in that Range
alive and the wait covers bytes the mutation never touches. The waiter can only retire
imports that overlap the freed span, so the count never reaches one: a deterministic
livelock that ends in

guest allocation 0x336b84000+0x4000 is still pinned by GPU work or an import (waited 60000 ms for the lease (APS5_PIN_WAIT_MS))

and abort().

This adds a span criterion next to the reference count:

  • libc exports GuestAllocationsSetSpanQuery, a callback a driver registers with the
    pin waiter.
  • The AGC driver answers whether any live or parked host import maps the bytes being
    freed, comparing the physical span actually pinned (memoryBase/pinnedBytes) and
    taking the imports mutex without blocking (a busy mutex answers "covered").
  • A mutation proceeds when no snapshot of the registry is live and no import covers
    exactly those bytes. use_count stays the conservative criterion for lease holders,
    and any lease snapshot taken during the scan forces the old behaviour, so the window
    where the answer could go stale is the one the registry lock already closes.

The intent is registry-side span granularity: leases keyed by (address, bytes)
instead of by Range object, so the query needs no driver callback at all. This hook
is the shape that query needs, so moving the criterion into the registry does not have
to change the callers added here.

Overlaps #6565, which is the other half of this wait and not the same cause. That PR
stops a new lease or import of the extent a mutation is already waiting on from
re-pinning it, with a retiring span list in the registry; here the holders are five
live 64 MiB imports of other offsets of the same ~1.4 GiB arena, none of which
overlaps the freed 16 KiB, and the snapshot map of the wait was empty, so the
re-lease race is not what aborts this title. Both edits touch
GuestAllocationsRequireUnpinned, GuestAllocationsAcquire and
GuestAllocationsAcquireAll, so whichever lands first needs a small rebase. I would
rather the retiring list grow into the span criterion and drop the driver hook
entirely; the measurement above is in that PR's thread.

#6321 is the only other open PR that edits this wait's neighbourhood: it adds
ranges->reserve(registry().ranges.size()) as the first line of the body of
GuestAllocationsAcquire, which is the line this change replaces with the snapshot
cache. It changes the scan cost of RequireAvailable and Overlaps, not the pin
criterion, so it is a one-line rebase in either order.

Draft because of the base, not because of the mechanism. Everything here is measured
on aec3b3880; main is now 6e9b9134f6 (1660 commits, Apple/Mach-O support added
in GuestAllocations.cpp and GuestAllocationsAcquireMapped inserted next to the
function this change rewrites), and git merge-tree reports one conflicted file here:
the #ifndef _WIN32 line that became #if !defined(_WIN32) && !defined(__APPLE__),
directly above the newSnapshot() insertion. The criterion on 6e9b9134f6 is still
range.use_count() != 1 over the covering Range (GuestAllocations.cpp:445), so
the failure and the fix are both unchanged; the rebase and a re-run of the A/B on the
new main are the next push to this branch.

Tested

Windows 10.0.26300, AMD Ryzen 7 5700X, NVIDIA GeForce RTX 5060 Ti with driver 616.92,
ASTRO BOT PPSA21567 01.018.000.

The 12 focused AGC host-import and memory-lifetime test binaries, origin/main
(aec3b3880) and this branch, same machine and GPU, with ANYPS5_REQUIRE_VULKAN=1,
ANYPS5_NO_SHADER_CACHE=1 and VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation:
identical verdicts on both sides (10 pass, agc_host_import_sparse_tests skips with
77, agc_driver_recorder_tests fails the same way on main itself with
(9) a scan under a pending write was kept at Recorder.cpp:1680), the same set of
validation messages (VUID-VkDeviceCreateInfo-pNext-pNext, 13 occurrences per side,
already present on main), no terminate called in either log, and the validation
layer loaded in every process.

Astro Bot, same scene, same pad script, same relinked executable, only the
libc.prx/libSceAgcDriver.prx swapped, with APS5_TRACE_FRAMES=0:15 and
APS5_TRACE_SUMMARY_EVERY=5:

main (aec3b3880):

**frames 0:15** from present 0: 15 presents, frame p50 55.1 / p90 106.1 / p99 546.3 / max 546.3 ms, GPU busy 24.0 ms per present

this change:

**frames 0:15** from present 0: 15 presents, frame p50 60.2 / p90 125.3 / p99 618.6 / max 618.6 ms, GPU busy 27.2 ms per present

The first 15 presents differ only by boot noise (main spent 546 ms and this change
619 ms in present 0, which compiles the shaders of the first frame). Per-frame cost is
unchanged; what changes is that the scene after them exists: main stops presenting
after its 15th frame, waits 60 s on the lease of a 16 KiB block and aborts at +75.1 s
(reproduced at 72.6 s, 73.1 s, 74.6 s and 75.1 s; no APS5_TRACE_SECONDS window of
5 s, 10 s, 30 s or 90 s ever closes), so there is no later-scene capture to compare
against. With this change the same run reaches 213 s and is killed by the harness
timeout, 2296 presents in 15 s intervals, p50 78-81 ms (~12 fps) and GPU busy 51-57 ms
per present from the 108 s mark on, with no still pinned message:

**14 intervals**, 0.0 to 213.1 s, 2296 presents
NVIDIA GeForce RTX 5060 Ti, NVIDIA 616.92, Windows 10.0.26300, 3840x2160, commit ef18375f02df

| # | seconds | presents | p50 | p90 | p99 | max | GPU busy | busiest worker | largest phase |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 0-17 | 165 | 39.3 | 51.8 | 1213.2 | 7049.4 | 17.4 | 100 % | Driver.Packet 265.3 |
| 2 | 17-32 | 271 | 45.7 | 62.4 | 275.8 | 1096.0 | 24.1 | 146 % | Driver.Packet 193.1 |
| 3 | 32-48 | 52 | 101.7 | 274.4 | 4682.4 | 4682.4 | 43.6 | 100 % | Driver.Packet 872.5 |
| 4 | 48-63 | 116 | 114.2 | 238.1 | 370.8 | 375.8 | 37.6 | 100 % | Driver.Packet 404.6 |
| 5 | 63-78 | 119 | 115.4 | 238.0 | 331.0 | 335.9 | 37.6 | 101 % | Driver.Packet 396.3 |
| 6 | 78-93 | 126 | 109.2 | 222.4 | 348.4 | 364.9 | 37.3 | 100 % | Driver.Packet 374.3 |
| 7 | 93-108 | 141 | 82.9 | 210.9 | 387.8 | 490.1 | 39.0 | 100 % | Driver.Packet 327.6 |
| 8 | 108-123 (dropped) | 186 | 73.7 | 80.8 | 111.9 | 1183.6 | 51.5 | 99 % | Driver.Packet 229.1 |
| 9 | 123-138 (dropped) | 182 | 81.4 | 85.8 | 115.8 | 136.6 | 57.5 | 100 % | Driver.Packet 245.8 |
| 10 | 138-153 (dropped) | 184 | 81.2 | 85.8 | 92.9 | 95.8 | 55.0 | 100 % | Driver.Packet 242.8 |
| 11 | 153-168 (dropped) | 186 | 80.1 | 85.3 | 97.8 | 98.7 | 53.9 | 100 % | Driver.Packet 240.3 |
| 12 | 168-183 (dropped) | 191 | 78.0 | 82.8 | 96.3 | 96.4 | 53.6 | 100 % | Driver.Packet 234.6 |
| 13 | 183-198 (dropped) | 189 | 79.4 | 82.3 | 92.9 | 98.4 | 53.6 | 100 % | Driver.Packet 236.6 |
| 14 | 198-213 (dropped) | 188 | 79.6 | 84.0 | 99.5 | 106.4 | 53.8 | 100 % | Driver.Packet 238.5 |

Traces: aps5-trace-*.json.gz and aps5-summary.jsonl for main, for this change
with the 15-frame window, and for this change over the full 240 s run.

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:
  • GPUs tested: NVIDIA GeForce RTX 5060 Ti, driver 616.92, Windows 10.0.26300
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5042921454 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12157). Originally posted by [ulissesemuman](https://github.com/ulissesemuman) on 2026-10-27T23:57:01Z. --- `GuestAllocationsRequireUnpinned` decides whether a guest `free()` may mutate an allocation by testing `range.use_count() != 1` on the registered `Range` that covers the address. The AGC driver imports memory in windows of at most 64 MiB out of arenas that are far larger (the block that fails here is 16 KiB inside a 1.4 GiB arena), so a host import of any other part of the arena keeps every `shared_ptr` in that `Range` alive and the wait covers bytes the mutation never touches. The waiter can only retire imports that overlap the freed span, so the count never reaches one: a deterministic livelock that ends in ``` guest allocation 0x336b84000+0x4000 is still pinned by GPU work or an import (waited 60000 ms for the lease (APS5_PIN_WAIT_MS)) ``` and `abort()`. This adds a span criterion next to the reference count: - libc exports `GuestAllocationsSetSpanQuery`, a callback a driver registers with the pin waiter. - The AGC driver answers whether any live or parked host import maps the bytes being freed, comparing the physical span actually pinned (`memoryBase`/`pinnedBytes`) and taking the imports mutex without blocking (a busy mutex answers "covered"). - A mutation proceeds when no snapshot of the registry is live and no import covers exactly those bytes. `use_count` stays the conservative criterion for lease holders, and any lease snapshot taken during the scan forces the old behaviour, so the window where the answer could go stale is the one the registry lock already closes. The intent is registry-side span granularity: leases keyed by `(address, bytes)` instead of by `Range` object, so the query needs no driver callback at all. This hook is the shape that query needs, so moving the criterion into the registry does not have to change the callers added here. Overlaps #6565, which is the other half of this wait and not the same cause. That PR stops a *new* lease or import of the extent a mutation is already waiting on from re-pinning it, with a `retiring` span list in the registry; here the holders are five live 64 MiB imports of *other* offsets of the same ~1.4 GiB arena, none of which overlaps the freed 16 KiB, and the snapshot map of the wait was empty, so the re-lease race is not what aborts this title. Both edits touch `GuestAllocationsRequireUnpinned`, `GuestAllocationsAcquire` and `GuestAllocationsAcquireAll`, so whichever lands first needs a small rebase. I would rather the `retiring` list grow into the span criterion and drop the driver hook entirely; the measurement above is in that PR's thread. #6321 is the only other open PR that edits this wait's neighbourhood: it adds `ranges->reserve(registry().ranges.size())` as the first line of the body of `GuestAllocationsAcquire`, which is the line this change replaces with the snapshot cache. It changes the scan cost of `RequireAvailable` and `Overlaps`, not the pin criterion, so it is a one-line rebase in either order. Draft because of the base, not because of the mechanism. Everything here is measured on `aec3b3880`; `main` is now `6e9b9134f6` (1660 commits, Apple/Mach-O support added in `GuestAllocations.cpp` and `GuestAllocationsAcquireMapped` inserted next to the function this change rewrites), and `git merge-tree` reports one conflicted file here: the `#ifndef _WIN32` line that became `#if !defined(_WIN32) && !defined(__APPLE__)`, directly above the `newSnapshot()` insertion. The criterion on `6e9b9134f6` is still `range.use_count() != 1` over the covering `Range` (`GuestAllocations.cpp:445`), so the failure and the fix are both unchanged; the rebase and a re-run of the A/B on the new `main` are the next push to this branch. ### Tested Windows 10.0.26300, AMD Ryzen 7 5700X, NVIDIA GeForce RTX 5060 Ti with driver 616.92, ASTRO BOT PPSA21567 01.018.000. The 12 focused AGC host-import and memory-lifetime test binaries, `origin/main` (`aec3b3880`) and this branch, same machine and GPU, with `ANYPS5_REQUIRE_VULKAN=1`, `ANYPS5_NO_SHADER_CACHE=1` and `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`: identical verdicts on both sides (10 pass, `agc_host_import_sparse_tests` skips with 77, `agc_driver_recorder_tests` fails the same way on `main` itself with `(9) a scan under a pending write was kept` at `Recorder.cpp:1680`), the same set of validation messages (`VUID-VkDeviceCreateInfo-pNext-pNext`, 13 occurrences per side, already present on `main`), no `terminate called` in either log, and the validation layer loaded in every process. Astro Bot, same scene, same pad script, same relinked executable, only the `libc.prx`/`libSceAgcDriver.prx` swapped, with `APS5_TRACE_FRAMES=0:15` and `APS5_TRACE_SUMMARY_EVERY=5`: `main` (`aec3b3880`): ``` **frames 0:15** from present 0: 15 presents, frame p50 55.1 / p90 106.1 / p99 546.3 / max 546.3 ms, GPU busy 24.0 ms per present ``` this change: ``` **frames 0:15** from present 0: 15 presents, frame p50 60.2 / p90 125.3 / p99 618.6 / max 618.6 ms, GPU busy 27.2 ms per present ``` The first 15 presents differ only by boot noise (`main` spent 546 ms and this change 619 ms in present 0, which compiles the shaders of the first frame). Per-frame cost is unchanged; what changes is that the scene after them exists: `main` stops presenting after its 15th frame, waits 60 s on the lease of a 16 KiB block and aborts at +75.1 s (reproduced at 72.6 s, 73.1 s, 74.6 s and 75.1 s; no `APS5_TRACE_SECONDS` window of 5 s, 10 s, 30 s or 90 s ever closes), so there is no later-scene capture to compare against. With this change the same run reaches 213 s and is killed by the harness timeout, 2296 presents in 15 s intervals, p50 78-81 ms (~12 fps) and GPU busy 51-57 ms per present from the 108 s mark on, with no `still pinned` message: ``` **14 intervals**, 0.0 to 213.1 s, 2296 presents NVIDIA GeForce RTX 5060 Ti, NVIDIA 616.92, Windows 10.0.26300, 3840x2160, commit ef18375f02df | # | seconds | presents | p50 | p90 | p99 | max | GPU busy | busiest worker | largest phase | |---|---|---|---|---|---|---|---|---|---| | 1 | 0-17 | 165 | 39.3 | 51.8 | 1213.2 | 7049.4 | 17.4 | 100 % | Driver.Packet 265.3 | | 2 | 17-32 | 271 | 45.7 | 62.4 | 275.8 | 1096.0 | 24.1 | 146 % | Driver.Packet 193.1 | | 3 | 32-48 | 52 | 101.7 | 274.4 | 4682.4 | 4682.4 | 43.6 | 100 % | Driver.Packet 872.5 | | 4 | 48-63 | 116 | 114.2 | 238.1 | 370.8 | 375.8 | 37.6 | 100 % | Driver.Packet 404.6 | | 5 | 63-78 | 119 | 115.4 | 238.0 | 331.0 | 335.9 | 37.6 | 101 % | Driver.Packet 396.3 | | 6 | 78-93 | 126 | 109.2 | 222.4 | 348.4 | 364.9 | 37.3 | 100 % | Driver.Packet 374.3 | | 7 | 93-108 | 141 | 82.9 | 210.9 | 387.8 | 490.1 | 39.0 | 100 % | Driver.Packet 327.6 | | 8 | 108-123 (dropped) | 186 | 73.7 | 80.8 | 111.9 | 1183.6 | 51.5 | 99 % | Driver.Packet 229.1 | | 9 | 123-138 (dropped) | 182 | 81.4 | 85.8 | 115.8 | 136.6 | 57.5 | 100 % | Driver.Packet 245.8 | | 10 | 138-153 (dropped) | 184 | 81.2 | 85.8 | 92.9 | 95.8 | 55.0 | 100 % | Driver.Packet 242.8 | | 11 | 153-168 (dropped) | 186 | 80.1 | 85.3 | 97.8 | 98.7 | 53.9 | 100 % | Driver.Packet 240.3 | | 12 | 168-183 (dropped) | 191 | 78.0 | 82.8 | 96.3 | 96.4 | 53.6 | 100 % | Driver.Packet 234.6 | | 13 | 183-198 (dropped) | 189 | 79.4 | 82.3 | 92.9 | 98.4 | 53.6 | 100 % | Driver.Packet 236.6 | | 14 | 198-213 (dropped) | 188 | 79.6 | 84.0 | 99.5 | 106.4 | 53.8 | 100 % | Driver.Packet 238.5 | ``` Traces: `aps5-trace-*.json.gz` and `aps5-summary.jsonl` for `main`, for this change with the 15-frame window, and for this change over the full 240 s run. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [ ] Based on current `main`; no other open PR implements the same functions <!-- Based on aec3b3880 (2026-10-26). tools/pr_overlap.py --branch reports no confirmed overlap: 48 open PRs are listed as "could not be compared" because they conflict with the base, and of those 5 touch libc/src/GuestAllocations.cpp. Checked by hand: #6565 changes the same three functions for a different cause (see What), #6321 adds one reserve line inside GuestAllocationsAcquire (see What), and #1835, #5021 and #11341 touch other functions of the file (RegisterMainImage, the TrimToRegistered/GuestPages additions, RemapFixedIntoRegistered and UnmapRegistered). No open PR adds a span query. --> - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [ ] Unblocks: <!-- PPSA21567 (Astro Bot); no game bring-up discussion open for it --> - [x] GPUs tested: NVIDIA GeForce RTX 5060 Ti, driver 616.92, Windows 10.0.26300 - [x] AI-assisted: yes
MarcZX10 commented 2026-11-20 09:51:41 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-20T09:51:41Z.

Review: APPROVED


Reviewed — looks good

Nothing blocks this change; the code inspected supports the span-based pin check, with test execution and the unprovided excluded-file list not verified.

What I ran

Reviewed head ef18375f02dff942260509d60238a32bce7795c7 using the prepared diff and pinned repository reader (repo_read.py). No commands or tests were run.

Results

Check Result Note
Diff and changed source passed Three changed files read
Tests not run Only author-reported results are available
Excluded-file list not run files.json was unavailable

Findings

Blocking

None.

Non-blocking

None.

Not verified

  • No tests were run. The description reports results from Windows 10.0.26300, Ryzen 7 5700X, and GeForce RTX 5060 Ti, but those runs were not independently verified.
  • files.json was not available through the reader, so excluded files could not be identified. The three changed files listed in manifest.json were read: core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp, core/libs/prx/libc/include/GuestAllocations.hpp, and core/libs/prx/libc/src/GuestAllocations.cpp.

To get this to a good state

Nothing is required. Optional: run the focused AGC host-import and memory-lifetime tests on the current head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5990733810 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12157#pullrequestreview-5990733810). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-20T09:51:41Z. **Review:** APPROVED --- # Reviewed — looks good Nothing blocks this change; the code inspected supports the span-based pin check, with test execution and the unprovided excluded-file list not verified. ## What I ran Reviewed head `ef18375f02dff942260509d60238a32bce7795c7` using the prepared diff and pinned repository reader (`repo_read.py`). No commands or tests were run. ## Results | Check | Result | Note | |---|---|---| | Diff and changed source | passed | Three changed files read | | Tests | not run | Only author-reported results are available | | Excluded-file list | not run | `files.json` was unavailable | ## Findings ### Blocking None. ### Non-blocking None. ## Not verified - No tests were run. The description reports results from Windows 10.0.26300, Ryzen 7 5700X, and GeForce RTX 5060 Ti, but those runs were not independently verified. - `files.json` was not available through the reader, so excluded files could not be identified. The three changed files listed in `manifest.json` were read: `core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp`, `core/libs/prx/libc/include/GuestAllocations.hpp`, and `core/libs/prx/libc/src/GuestAllocations.cpp`. ## To get this to a good state Nothing is required. Optional: run the focused AGC host-import and memory-lifetime tests on the current head.
ligmaSec commented 2026-12-03 15:44:05 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by ligmaSec on 2026-12-03T15:44:05Z.

Review: COMMENTED


newSnapshot() increments liveSnapshots before allocating Lease::Ranges. If that allocation throws, the deleter is never installed. The counter then stays elevated and disables the span-clear path for later frees. Please make the counter registration exception-safe. The branch also conflicts with current main in the guest allocation and buffer import paths.

AI-assisted: yes.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6173139664 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/12157#pullrequestreview-6173139664). Originally posted by [ligmaSec](https://github.com/ligmaSec) on 2026-12-03T15:44:05Z. **Review:** COMMENTED --- `newSnapshot()` increments `liveSnapshots` before allocating `Lease::Ranges`. If that allocation throws, the deleter is never installed. The counter then stays elevated and disables the span-clear path for later frees. Please make the counter registration exception-safe. The branch also conflicts with current main in the guest allocation and buffer import paths. AI-assisted: yes.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/12157:upstream-pr/12157'
git switch 'upstream-pr/12157'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/12157'
git switch 'upstream-pr/12157'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/12157'
git switch 'upstream-pr/12157'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/12157'
git switch 'main'
git merge --squash 'upstream-pr/12157'
git switch 'main'
git merge --ff-only 'upstream-pr/12157'
git switch 'main'
git merge 'upstream-pr/12157'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
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.

Reference
boykopovar/AnyPS5!12157
No description provided.