Skip to content

perf(agc): query guest page access with PROCMAP_QUERY on Linux - #157

Merged
adriadam10 merged 2 commits into
boykopovar:mainfrom
Pacuka:perf/linux-maps-cache
Oct 8, 2026
Merged

adriadam10 merged 2 commits into
boykopovar:mainfrom
Pacuka:perf/linux-maps-cache

Conversation

@Pacuka

@Pacuka Pacuka commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What

On Linux describePages (GuestMemory.cpp) opened and parsed the whole /proc/self/maps for every run it reported (the arena/image page spans that answer most queries on Windows are empty there), about 0.5–0.8 ms per lookup.

On kernels with the PROCMAP_QUERY ioctl (Linux 6.11+) each run is now one ioctl on an open /proc/self/maps fd with PROCMAP_QUERY_COVERING_OR_NEXT_VMA: the kernel returns the VMA covering the cursor, or the next one above it, with its read/write flags. No snapshot is kept, so host-only mapping changes (thread stacks, guard pages, driver allocations) are seen immediately. A VMA starting above the cursor is a gap up to vma_start, and ENOENT is a gap to the end, matching the gap handling from #442. The fd is opened and probed once; if the probe fails (ENOTTY on older kernels), the line scan stays as the fallback. When <linux/fs.h> predates 6.11 (ubuntu-latest has 6.8), the v1 struct procmap_query, the flags used and PROCMAP_QUERY are defined locally, so the fast path is still compiled and the runtime probe decides. APS5_NO_PROCMAP_QUERY skips the probe, so the line scan can be tested on a kernel that has the ioctl.

Tested

Linux 7.2 (CachyOS, GCC): full build, ctest 359/359 with the system headers, with the local definitions (linux/fs.h include disabled) and with APS5_NO_PROCMAP_QUERY=1.
Standalone comparison against the line scan over 2003 addresses in a process with ~4000 mixed-protection VMAs: identical readable/writable answers and run ends (the only difference is the end of the gap above 0x7fffffffe000, where the line scan stops at [vsyscall]; both report it inaccessible), 763 µs vs 0.54 µs per lookup.
Minecraft (on a local branch with more rendering work), 100 s runs: [guestmem] verify total 6.7 s with this change, against 52.1 s with the previous maps snapshot cache; no verify failures in either 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 in TechnicalDebt
  • 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
  • AI-assisted: yes

🤖 Generated with Claude Code

@github-actions github-actions Bot added agc libSceAgc* needs rebase Conflicts with main, rebase needed labels Sep 29, 2026
@oneandonlydean

Copy link
Copy Markdown
Collaborator

A note on the gap case in the Linux describePages, which this PR rewrites but keeps as it is on main.

When the cursor is in a gap between mappings, the Linux path reports the whole rest of the range unmapped and returns. That includes mapped pages after the gap. Main's line scan does this, and here findRegion returning null after the reload takes the same exit.

A concrete case: map three anonymous RW pages, munmap the middle one, then query all three. Results with this PR merged onto current main (plain main gives the same):

Query Expected Result
CommittedRanges(base, 3 pages) [base, +1 page) and [+2, +3 pages) [base, +1 page) only
CommittedRanges(base + 1 page, 2 pages) [+2, +3 pages) none
ReadCommitted(base, 3 pages), byte at +2 pages (holds 0x5a) 0x5a 0x00

The same skip hits EqualsCommitted (pages after the gap are never compared), WriteChangedCommitted (writes to them are dropped) and the DescribeCommitted calls in GuestBufferMemory. On Linux, sceKernelMunmap of part of a mapping really unmaps it, so these gaps do occur inside guest ranges.

In this PR's structure the fix is small. When no region contains the cursor, report the gap up to the next region above it and carry on, as the VirtualQuery path does with a free region:

if (region == nullptr) {
    const auto above = std::upper_bound(snapshot->regions.begin(), snapshot->regions.end(), cursor, [](std::uintptr_t value, const MappedRegion& mapped) { return value < mapped.first; });
    const auto next = above == snapshot->regions.end() ? end : std::min(end, above->first);
    if (!emit(PageRun{cursor, next, false, false})) return true;
    cursor = next;
    continue;
}

With that change on top of this PR, the three queries return the expected results and agc_driver_graphics_tests passes on Linux.

There's also a cost note, since this is a perf PR. A cursor in a gap takes the reload path, so each such query still reads all of /proc/self/maps. In PPSA21564 on my integration branch, the lighting programs read near-null addresses (0x18, 0x30, 0x58) about 1500 times a second during resource capture. The maps there are about 5700 lines, mostly NVIDIA mappings.

I have this fix against main's loop as about 10 lines plus a test. I can adapt it to your structure and send it as a follow-up once this lands, or it can be folded in here, whichever you prefer.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

#442 has landed since my earlier comment, so this now conflicts in GuestMemory.cpp. When you rebase, please keep its gap handling (emit the gap up to the next region and continue, as in the snippet above). For the reload cost I mentioned, one option: when the snapshot was just reloaded and is still the current generation, treat "no region contains the cursor" as a real gap instead of reloading again on every query. Happy to re-test on my integration branch once it is rebased.

@Pacuka

Pacuka commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, and sorry for the delay. While rebasing I found that the cache itself no longer holds on current main: RunLiveStackAccessTests (from #459) mprotects guard pages without a guest generation change, and a cached snapshot still reports them readable ("the released test stack is misreported"). Trusting a just-reloaded snapshot for misses fails the same way in the other direction: agc_driver_graphics_tests maps host pages after a miss reload and they read as unmapped. So keying the snapshot on the guest allocation generation is only exact for guest-registered ranges, and even there the write-watch protection changes could leave the writable bit stale.

Two options I see: (a) use the snapshot only for addresses inside guest-registered allocations and read /proc/self/maps for everything else, or (b) drop the cache and keep only an exact fast path: addresses below /proc/sys/vm/mmap_min_addr (64 KiB by default) can never be mapped, so they are a gap without reading the file. That covers the near-null lighting reads (0x18, 0x30, 0x58) you measured, and #442's gap handling stays as is. Which would you prefer? I'm also fine with closing this in favour of your follow-up.

@oneandonlydean

Copy link
Copy Markdown
Collaborator

You're right, and the #459 test is right too: host mappings (thread stacks and their guard pages, driver allocations) change without the guest allocation generation moving, so a snapshot keyed on it can't answer for them, and my suggestion to trust a just-reloaded snapshot on a miss fails the same way, as you found.

Of your two options, (a) still leaves the writable bit stale, as you say, and (b) is exact only while mmap_min_addr isn't lowered at runtime and the process has no CAP_SYS_RAWIO, so I'd rather not rely on it.

One option that is exact without a cache: the PROCMAP_QUERY ioctl on an open /proc/self/maps fd (Linux 6.11, linux/fs.h). With PROCMAP_QUERY_COVERING_OR_NEXT_VMA it returns the VMA that contains the address, or the next one above it, with its read and write flags, straight from the kernel. Each run in describePages is then one ioctl instead of a full parse, and #442's gap handling maps onto it directly: if vma_start is above the cursor, the gap runs up to vma_start, and ENOENT means a gap to the end. On older kernels the ioctl fails with ENOTTY and the line scan stays as the fallback.

If you'd rather not take that on, closing this is fine with me too.

@Pacuka
Pacuka force-pushed the perf/linux-maps-cache branch from d9d6edb to d1fa963 Compare October 5, 2026 20:19
@Pacuka Pacuka changed the title perf(agc): cache the parsed /proc/self/maps for guest page queries on Linux perf(agc): query guest page access with PROCMAP_QUERY on Linux Oct 5, 2026
@Pacuka

Pacuka commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, PROCMAP_QUERY it is. I rebased onto current main and replaced the cache: each run in describePages is now one ioctl with PROCMAP_QUERY_COVERING_OR_NEXT_VMA, a VMA above the cursor is a gap up to vma_start, ENOENT is a gap to the end, and the line scan stays as the fallback when the probe on the fd fails (older kernels). No snapshot is kept, so the host-only mappings from the #459 test are always answered exactly.

Measurements are in the updated description: same answers as the line scan, ~0.5 µs instead of ~760 µs per lookup, and in a 100 s Minecraft run the verify total went from 52.1 s (old cache) to 6.7 s.

@github-actions github-actions Bot removed the needs rebase Conflicts with main, rebase needed label Oct 5, 2026
@oneandonlydean

Copy link
Copy Markdown
Collaborator

Thanks, this is what I had in mind. I checked the query path against the line scan:

  • A VMA above the cursor becomes a gap up to vma_start, and ENOENT becomes a gap to the end.
  • Readable comes from PROCMAP_QUERY_VMA_READABLE, and writable only together with readable, the same as permissions[0]/[1].
  • The probe runs once in a function-local static, so its initialisation is thread-safe. A kernel without the ioctl (ENOTTY) falls back to the line scan for good.

A small program on 7.2 gives the expected answers for each case: an RW page, a hole left by munmap (the next VMA is returned), a PROT_NONE page (flags 0), a read-only page, 0x18 (the first VMA above it) and an address above the last VMA (ENOENT).

One thing affects what this PR actually speeds up. The fast path is compiled only when <linux/fs.h> defines PROCMAP_QUERY, which needs 6.11 or newer UAPI headers. The Linux CI job and release.yml build on ubuntu-latest (24.04, linux-libc-dev 6.8), so there the #if defined(PROCMAP_QUERY) block is compiled out. CI passing tests only the line scan, and the release binaries keep the old cost even on new kernels.

Since the runtime probe already handles old kernels, the header check could also fall back to a local definition when the macro is missing:

  • struct procmap_query with the v1 fields, from size to build_id_addr (104 bytes)
  • PROCMAP_QUERY as _IOWR('f', 17, struct procmap_query)
  • the three flag values you use

The struct is size-versioned, so the kernel accepts that layout on any version that has the ioctl.

Separately, nothing tests the fallback on a machine where the ioctl works. Something like an environment switch that skips the probe would let RunLiveStackAccessTests and the gap tests cover both paths locally. That part is optional.

@Pacuka
Pacuka force-pushed the perf/linux-maps-cache branch from d1fa963 to a1427b8 Compare October 6, 2026 15:22
@Pacuka

Pacuka commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for checking it against the line scan. Both points are in now (rebased onto current main):

  • When <linux/fs.h> doesn't define PROCMAP_QUERY, the file defines struct procmap_query with the v1 fields (size to build_id_addr, static_assert on 104 bytes), the three flags it uses and PROCMAP_QUERY as _IOWR('f', 17, struct procmap_query), so the fast path is compiled on 6.8 headers too and the runtime probe decides.
  • APS5_NO_PROCMAP_QUERY skips the probe, so the line scan can be tested on a kernel that has the ioctl.

Tested on Linux 7.2 (CachyOS, GCC), ctest 359/359 in three setups: system headers, the local definitions (with the linux/fs.h include disabled, as on the 6.8 headers of ubuntu-latest), and APS5_NO_PROCMAP_QUERY=1. Under strace, agc_driver_graphics_tests makes 246 PROCMAP_QUERY ioctls and opens /proc/self/maps twice with both header setups, and opens it 246 times with no ioctls when the switch is set.

@Pacuka

Pacuka commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

The Linux job failed on a timeout in agc_driver_flat_store (the recorded batch never finishes on llvmpipe). The same test timed out the same way on an unrelated branch (run 37406080556, feat/agc-image-tables-global), and it passes 20 times in a row here with and without APS5_NO_PROCMAP_QUERY. I can't re-run jobs, so could you re-run the failed one when you get a chance?

@alfalfa-star

Copy link
Copy Markdown
Contributor

Tested a1427b83 with LEGO Horizon Adventures (PPSA14632) on Linux: Arch, kernel 7.2.7, GCC 16.2.1, RX 9070 XT (RADV GFX1201), --to-intel. I cherry-picked it onto my test branch (an older main plus #861, #425 and a few of my open PRs).

Before: the game died about 2 minutes in, inside a deliberate crash by Unreal's GC (IncrementalDestroyGarbage → AbortInsideMemberFunction). A texture's render-thread release fence had been pending for more than 10 s, because each frame took about 75 s. Almost all of that time went into describePages re-reading /proc/self/maps:

[guestmem] ... verify 74204 calls 35824 MiB 104.4 s          (cumulative, ~2 min in)
[packets] queue 0x0 ... DISPATCH_DIRECT x37 8746ms           (per 10 s)

The busy queue worker's stack ended in std::ios_base::~ios_base() under describePages ← verify ← CheckRange ← WriteChanged ← StorageTexture::writeBackLayers.

With this PR: no abort in an 8-minute run. The game presents steadily (about 4 frames per 10 s, still CPU-bound elsewhere) and reaches its boot-flow movie for the first time:

[guestmem] ... verify 9412219 calls 4374488 MiB 2.3 s         (cumulative, 8 min)
[packets] queue 0x0 ... DISPATCH_DIRECT x575 4300ms          (per 10 s)

That is about 127× as many verifies in 2% of the time. No verify failures and no new errors in the log.

@Pacuka

Pacuka commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks a lot for testing it on LEGO Horizon Adventures, and for the before/after numbers. Seeing the GC abort go away and the game reach its boot-flow movie is a much better proof than my Minecraft runs, and it confirms the gain on RDNA4 as well.

@fisherjoey

Copy link
Copy Markdown
Contributor

Measured with a game on Linux, in case it helps the review.

Demon's Souls (PPSA01341 v1.07) on Linux 7.2, RTX 5070 Ti. During its intro movie (Bink 2 decoded in compute), almost all CPU time on cache hits went to dispatch validation, and in validation to describePages re-reading /proc/self/maps: about 48,000 opens of the file in 25 s, with 64% of samples inside read() and the rest in stream parsing.

main main + this PR
intro movie fps 0.63 to 0.67 5.3 to 6.0
validate per dispatch, queue 0 indirect / other queues 10,480 us / 8,887 us 51.8 us / 8.5 us
GuestMemory::CompareMapped average 658 us 5.8 us (one PROCMAP_QUERY, 2 to 4 us)
dispatch-cache lookups per 10 s 1,353 10,760

Same build otherwise, same run directory, APS5_PROFILE_DRAW=1. Nothing broke in about 10 minutes of runs with the PR applied.

@github-actions

github-actions Bot commented Oct 7, 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
#1114 core/libs/prx/libSceAgcDriver/Execution/src/GuestMemory.cpp L537-551

TibixDev pushed a commit to TibixDev/AnyPS5 that referenced this pull request Oct 7, 2026
Integrate upstream PR boykopovar#157 at a1427b8. Query individual VMAs through the kernel and retain the text scan on older kernels.

Local validation: graphics, shader-memory and write-tracking tests pass with the ioctl path and with APS5_NO_PROCMAP_QUERY=1. The Skyrim performance capture identified repeated maps parsing as a CPU hotspot.

AI-assisted upstream implementation and local integration.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@Dextroid17

Copy link
Copy Markdown
Contributor

Replying to the invitation when #1114 was closed as a duplicate of this one: #157 does not miss the case I hit. I verified it on both code paths.

The case was the guard-page assertion in tests/LiveStack.cpp (a thread stack whose two guard pages are mprotected to PROT_NONE), reached through agc_driver_graphics. On the snapshot-cache version that test failed with the released test stack is misreported; the maintainer's closing comment quotes that as the stale hit.

Linux 7.2.9 (CachyOS, GCC, Release), NVIDIA RTX 3080 Ti:

ioctl path (this branch):            agc_driver_graphics  →  Passed  4.14 s
forced fallback (APS5_NO_PROCMAP_QUERY=1):  agc_driver_graphics  →  Passed  4.18 s
full suite, fallback forced:         ctest -j 16  →  359/359 passed  (23.39 s)
full suite, system headers:          ctest -j 16  →  359/359 passed

Kernel here is 7.2.9, so the PROCMAP_QUERY path is the live one rather than the fallback — worth stating, since a pass on an older kernel would only have exercised the line scan.

Why it does not have the problem the other one had, in the terms the failure showed. The stale hit came from a cache refreshed only on a miss: a region that still covered the queried address was a hit, so nothing was re-read, and a page that had since become PROT_NONE kept reporting accessible. This keeps no snapshot at all, so a guard page whose protection changed after the fact is re-examined on the next query. The LiveStack assertion is exactly the shape that "host-only mapping changes are seen immediately" predicts, which is why it is a better test of the claim than a timing number.

The forced-fallback run is the part I would keep in the PR: it makes the line scan testable on a kernel that does have the ioctl, and 359/359 with the fallback forced means the two paths agree on the case that mattered rather than only the fast path being exercised.

That is everything I had. Nothing outstanding from my side.

Written with AI assistance.

TibixDev pushed a commit to TibixDev/AnyPS5 that referenced this pull request Oct 8, 2026
Integrate upstream PR boykopovar#157 at a1427b8. Query individual VMAs through the kernel and retain the text scan on older kernels.

Local validation: graphics, shader-memory and write-tracking tests pass with the ioctl path and with APS5_NO_PROCMAP_QUERY=1. The Skyrim performance capture identified repeated maps parsing as a CPU hotspot.

AI-assisted upstream implementation and local integration.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@oneandonlydean

Copy link
Copy Markdown
Collaborator

Tested this on current main: ctest 410/410, and in a title whose mappings grow over the run it removes the slowdown completely (it held 60 fps where main falls to single digits). One thing before merging: in describePages, when the ioctl fails with anything other than ENOENT, it falls through to the /proc/self/maps line scan. That's a retry after an error; please return false there instead, so it surfaces as "cannot query guest memory". The path chosen once by the probe at startup is fine.

Pacuka and others added 2 commits October 8, 2026 13:04
describePages parsed the whole /proc/self/maps for every run it
reported. On kernels with the PROCMAP_QUERY ioctl (Linux 6.11+) each run
is now one ioctl on an open /proc/self/maps fd with
PROCMAP_QUERY_COVERING_OR_NEXT_VMA, which returns the covering or next
VMA and its read/write flags straight from the kernel, so the answer is
exact for host mappings too. A VMA starting above the cursor is a gap up
to its start and ENOENT is a gap to the end. Kernels without the ioctl
keep the line scan.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@adriadam10
adriadam10 force-pushed the perf/linux-maps-cache branch from a1427b8 to 18bc4b6 Compare October 8, 2026 11:25
@adriadam10

Copy link
Copy Markdown
Collaborator

Pushed the fix Dean asked for, so this doesn't have to wait:

  • 18bc4b6: in describePages, a PROCMAP_QUERY that fails with anything other than ENOENT now returns false ("cannot query guest memory") instead of falling back to the /proc/self/maps line scan. The fallback is only used when the startup probe picks it.
  • Rebased onto current main (084aeeb).

Linux, GCC 16.2.1, RADV gfx1035: full ctest 442/442. With APS5_NO_PROCMAP_QUERY=1 (line-scan path), agc_driver_graphics and the guest/shader memory tests pass too. Merging once CI is green.

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

Labels

agc libSceAgc*

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants