perf(agc): answer Refresh's registry and host-import lookups from an index and a cache #7514
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/7514"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from boykopovar/AnyPS5. Originally posted by AlxcBTW on 2026-10-18T10:34:54Z.
What
StorageTexture::Refreshruns for every storage image a dispatch or draw reads or writes, tens of thousands of times per 10 s in a gameplay scene, and looks up the same facts each time: which images pending in the same memory overlap it, which pending image sits at its address, and which host import holds its range. Three commits, each on by default and each exact (the same answers, only cheaper to get), followed by the merge ofmain(base0c6a5bd59), a docs commit that adds theAPS5_NO_REFRESH_LOOKUP_CACHErow todocs/dev/ENVIRONMENT.md, and the follow-up fixes described under "Follow-up after the merge of main":perf(agc): answer Refresh's pending registry queries from an address index.PendingListkeeps its images in aRangeIndex(newGraphics/include/RangeIndex.hpp) beside the vector: items keyed by[begin, end), ordered by (begin, registration order), overlap queries in O(log n + k) over an implicit balanced tree that holds the largest end of each subtree (rebuilt in O(n) on the first query after a change).otherPendingOverlapsasks the index for images overlapping the range (any image butthis),pendingAliasasks for the images starting at its address. Before, both scanned every pending image under the registry mutex (std::any_ofover the vector; the loop ofpendingAlias). The index is updated where the vector is (push_back,erase,remove).perf(agc): skip the per-unit state of a Refresh that finds nothing stamped. A Refresh of an image with block units, unchanged DCC keys and no pending alias, whose surface has no stamp since the image's generation (GuestMemory::UnchangedSince, the test the code already makes), answers "unchanged" whatever the per-unit state says: no unit is changed, nothing is compared, nothing is borrowed. It no longer allocates the per-unitchangedlist or walks it for pending units. The host-import lookup and everything after the early return stay. The quick path is taken only for a whole-image Refresh (!scoped; see the follow-up below).perf(agc): remember the host import a storage image's Refresh found. EachStorageTextureremembers the import its last Refresh lookup returned, with the range, the import table's epoch (bumped whenever an import is dropped or the device changes) and a new insert count (bumped whenever an import is added).HostImportForCachedtakes the import mutex and does the Windows settle step and the registry staleness check exactly asHostImportFordoes, and answers from the remembered import when range, epoch and insert count are unchanged and the registry has not moved since the imports were reconciled, with the same last-use stamps as a full hit (findImport's and the explicit one, 2 per lookup); otherwise it runs the full lookup (nowhostImportSettled, the old body ofHostImportForafter the settle) and remembers its result. A lookup that finds no import is not remembered.All three are turned off together by
APS5_NO_REFRESH_LOOKUP_CACHE=1(set at all means off, like the otherAPS5_NO_*switches); with it set the code paths are the old ones (the index is not even filled). I considered two PRs: the index and the lookup cache touch different data and could stand alone, but they are one topic (Refresh's lookups), share the switch, and the only measurements I have are of the stack that has them together, so one PR with the three commits in the order that each builds and passes alone.Why the answers are the same:
[descriptor.baseAddress, baseAddress + guestBytes)and both are fixed at construction, so the range an entry is filed under is the rangeoverlaps()tests.RangeIndex::Overlappingvisits exactly the entries withaddress < end && begin < address + bytes(the predicate ofStorageTexture::overlaps, zero-length queries return nothing as before),StartingAtvisits the entries with that begin in registration order, which is the vector's order for equal begins (an erase and re-push goes behind the others in both).otherPendingOverlapsandpendingAliasonly ask for existence or collect candidates in that order, andpendingAliasstill filters by size and block units as before. Theflushinglist is untouched.scopedis false:firstLayer == 0 && lastLayer == trackedLayers) withquicktrue, the code that is skipped only reads and writeschanged, which is all false when no unit is stamped;comparedis only set by the block scan thatquickskips andpendingChangedstays false; the alias branch needs a non-null alias; theunchangedreturn is the one the old code reaches. A scoped Refresh (the layer range of a render target or view) does not take it, see the follow-up.findImport(the import containing the range, by base) plus a stamp. Imports enter the table in one place (the insert count) and leave it inretireImport, the device reset and the shutdown clear (each bumps the epoch), so with epoch and insert count unchanged and the registry not stale the import found by range is the remembered one, and the stamps makelastUseanduseCounterend up as after a full lookup (the eviction rule reads both).Follow-up after the merge of main.
mainnow hasStorageTexture::refresh(firstLayer, lastLayer)withscoped = firstLayer != 0 || lastLayer != trackedLayers: a Refresh scoped to the layers of a target or view. The first CI run after the merge (at3258892a4) failed inagc_driver_array_layer_target_cpu(segfault) and inagc_host_import_retire. Both causes are found:changedstays empty (changed.assign(trackedLayers, false)is skipped). In a scoped Refresh the next block,if (scoped && !keysChanged), readschanged[layer]for every layer outside the scope (!changed[layer] && !compared), which is a read past the end of an emptyvector<bool>. The whole-image Refresh that this PR was written against had no such block.e230f5fa5adds!scopedto the quick-path condition (it added!comparedas well;comparedis false at that point, because only the block scan thatquickskips sets it, so that term never held anything back and7aba17fffleaves it out again). For a whole-image Refresh the skipped code is unchanged from above, so the shortcut stays exact there; a scoped Refresh takes the old path in full.agc_host_import_retire. The cached hit stamped the import's last use once where the full lookup stamps it twice (findImportand the lookup itself), and the new case "a cached lookup and a full lookup stamp the last use differently" reports exactly that.e230f5fa5also fixed this, by a second stamp line.d485deee2removed that line again as a duplicate and the same case failed in all three CI runs of that head (run 39688330136, 39688369669, 39688423114:FAIL: a cached lookup and a full lookup stamp the last use differently);7aba17fffputs it back. Net effect ofd485deee2and7aba17ffftogether: only the dead!comparedterm is gone.The switch
APS5_NO_REFRESH_LOOKUP_CACHEis not read by the CI test set, so the cause is shown by the code, by the failing run at3258892a4and the passing runs after the two fixes, not by a run with the switch set.Not covered by this PR: equivalence of the whole Refresh is argued from the code and measured by the lab verify runs below (compare mode that is not in the PR); the title speed gain is not established (below).
Tested
agc_, after the merge ofmain; not run on Windows. The runs of the current head7aba17fff(each is the head plus the CI scaffolding commit): runs 39693268189, 39693318038 and 39693362034, each 877 of 877 passed, includingagc_driver_array_layer_target_cpu,agc_host_import_retireandagc_driver_sgpr_pattern_fill_keysin every run. Before it:3258892a4failed (segfault inagc_driver_array_layer_target_cpu, failure ofagc_host_import_retire);e230f5fa5, run 39683281454, passed;d485deee2failedagc_host_import_retirein three runs (39688330136, 39688369669, 39688423114; 876 of 877 passed each, all else includingagc_driver_array_layer_target_cpupassed). The same regex onmain(a6dcea927, run 39688450938): 876 of 876 passed; a second run ofmainwith the three testsagc_driver_array_layer_target_cpu,agc_host_import_retireandagc_driver_sgpr_pattern_fill_keys(run 39693413422): 4 of 4 passed,mainhas no segfault in these runs. That the segfault is the quick path of a scoped Refresh rests on the code reading above and on the failing run; no run exists of the head3258892a4with the switch set. The runs atd485deee2(only the!scopedterm added, no segfault) are the closest to a test of the fix alone.agc_range_index(tests/RangeIndex.cpp, new executable): the index against a brute-force list over random registries (four seeds, address spaces from 16 to 2^40 bytes, 3000 to 4000 rounds each of random inserts, removals of a random live entry and inserts at a fixed begin, with four random overlap queries and a start query after every round, and a final drain of all entries); fixed cases for the strict overlap rule at both ends, empty query, zero-length entry, registration order at one begin, a removed entry, a re-registered entry and a query running past the end of the address space.agc_host_import_retire(tests/HostImportRetireHold.cpp) has two new cases: the cached lookup agrees with the full lookup, a repeat hits the remembered import, another range and an empty range are not answered from it, and a cached hit and a full lookup movelastUseby the same amount; and the cache follows the import table: an import added between two lookups (which also moves the registry) leaves the answer equal to the full lookup, a dropped import (the heap grows, the import is replaced by one over both ranges) is not answered from the cache and the cache refills, a cache filled after the drop agrees, and a range outside every registered range answers null and is not remembered. The rewatch of a settled import (Windows only) is not driven by a test; it does not change the import pointer.best10and its successors, a run of lab changes of which the lab switchAPS5_LAB_REFRESH_LEVERis the only difference between the arms. The lab version of the cache is the same as commit 3 here without the switch and without the lab counters; the lab version of the index is commit 1; its quick path is commit 2. Lab arm=1had in addition an unexact variant, the host-import lookup skipped on the unchanged path (it also skips the last-use stamps), which this PR does not contain. Arm=2(the cached lookup) contains the index and the quick path as well, so it is this PR; arm=1is not.Job 95 (A/B/C, trace-digest figures, no profile counters; a: best10, b:
=1index + quick path + skipped lookup, c:=2index + quick path + cached lookup, which is this PR; arm order a b c, c b a, b a c; gameplay is a 180 s walk traced from 170 s, title is 200 s traced from 100 s):Row r3-g-a-2 is a world-load crash and retry (
FAsyncLoadingThread0xc0000005, the title's own load-time crash, not this change); one b row ran out of memory (0.45 GiB free, stopped), so b has two gameplay rows. Gameplay means: a 4.02 FPS (5.45 without the crash row), b 5.80, c 6.93. Title means: a 8.67, b 8.26, c 9.08. These were daytime rows: they ended at 0.5 to 6.4 GiB free with 46 to 56 GiB committed and about 35 browser processes open, which is the memory-noisy state this machine produces gameplay figures in (31 GiB), and the spread inside arm a alone is 1.15 to 5.95 FPS. I read them as: c is ahead of a in every gameplay row against a's rows that did not crash, and the title shows no difference (8.38 and 9.78 in c against 9.27 and 8.07 in a); I do not claim a gain from them. There is no clean A/B of this change on its own.Job 91zz-best12 (best11 against best12, both with
APS5_LAB_REFRESH_LEVER=2andAPS5_LAB_DEPTH_CLEAR_HLE=1; it compares two integration stacks and is not an A/B of this change, listed because the lever is on in both arms and its counters are the largest sample of the cached lookup):Gameplay rows ended at 4 to 6.5 GiB free (noisy), the title rows at 9.3 GiB free (clean). The difference between the stacks is not this change.
Counters that bear on exactness and on how often each lookup is taken (lab builds, per 10 s, the lab counters are not in the PR):
verify2(job 91zz of 17.10, gameplay: each cached answer compared with the full lookup made right after it), last three windows of the row: 131,395 hits and 3,841 misses; 116,834 and 3,725; 122,069 and 4,041; epoch moves seen at a miss 221, 22, 256; verify2 differences 0 (since start), noDISAGREEline, stop reasonprogram-done. Cached mode, title row of the same job: 112,204 hits and 2,641 misses; 111,038 and 2,620; 113,122 and 2,644, no epoch move, 0 differences. In the best12 rows (cached mode only, last window per row): gameplay best11 92,390 hits / 5,037 misses, 108,903 / 4,128, 95,631 / 3,804; best12 180,725 / 7,338, 150,467 / 5,934, 122,903 / 4,141; title 133,818 / 3,178, 134,236 / 4,151, 136,771 / 4,125, 136,252 / 3,464. So 96 to 98 % of the lookups are hits.verify(job 91z of 17.10, gameplay: the old scans run beside the index and the quick answer is compared with the full path): "disagreements 0 (since start)" on every one of the 26 windows of the row, for example 117,271 refreshes, 58,310 index queries and 45,056 entries returned in the last 10 s. Inonmode of the same stack (arm=1, gameplay rows of job 91z), 9,900 to 28,800 of 66,000 to 180,000 refreshes per 10 s took the quick path, and the index answered 32,000 to 96,700 queries per 10 s returning 0.7 to 1.0 entries on average.Refresh's cost, from the hold profile (lab build best10 with the profile switch on, so no lever; gameplay row g1 of job 88, summed over every thread and hold site, per 10 s, spans nested inside
storage-refresh-self; the profile costs two clock reads per span, so its FPS is not comparable):StorageTexture::Refresh1,139 ms over 59,137 calls (19.4 us per call) in the earlier profile; the finer one,rf-host-import(theHostImportForlookup) 519.3 ms over 20,497 calls (25.3 us per call),rf-scan-blocks154.2 ms,wb-windows386.6 ms,rf-alias(pendingAlias) 10.3 ms over 20,497 calls (0.5 us),rf-unchanged-tail10.4 ms over 17,781 calls,refresh-proved18.2 ms over 32,147 calls,rf-decide-loops6.6 ms over 20,497 calls, what remains instorage-refresh-self47.8 ms. The pending-registry scans were cheap to start with (24,000 scans over 2.9 M entries, about 120 per scan). Two things follow, and I want them read as limits of the claim: the span the cache can touch is the biggest one, but the profile does not split it further, and the cached hit still takes the import mutex, so how much of the 25 us is the map descent and how much is waiting for the mutex is not known; and the index and the quick path address spans that were already small (about 10 ms and 7 ms per 10 s). I have no hold profile of a build with the changes, so the reduction of these spans is not measured.Not measured: Windows CI, other GPUs, other titles, the tests with the switch set (the new tests run with the default, the cache test also compares against the full lookup). The
RangeIndexheader also has no user besidesPendingList.main. One build (maine5c2b3c32with this branch, #7489 and #7484 merged in) and arms that differ only by theAPS5_NO_*off switches, three title rows per arm and two gameplay rows, with the trace summary lines. The lab machine runs it as soon as it has the memory free for clean rows; I will post every row here.python3 tools/check_conventions.py --base origin/mainpasses. Based on0c6a5bd59(origin/main, merged into the branch).tools/pr_overlap.py(against the open pull requests on main) lists textual overlaps with #6454 (PendingList, aroundMayOverlapin Texture.cpp), #6457, #6479 and #6730 (all four:HostImportFordeclaration and body, GuestBufferMemory.cpp lines around 3002, and the signature in the header), #7457 (HostImportsstruct, the import insert andHostImportFor, which my commit 3 splits intohostImportSettled), #6718 and #6820 (Texture.cpp, the line of thedirectlookup in Refresh that commit 3 changes), #7082 (HostImportRetireHold.cpp, the end of the file where the new cases go), #7427 (Texture.hpp near the members) and #5431 (CMakeLists.txt, the test block); the other entries of the tool's list are shared files it could not compare. None implements an address index of the pending storage registry or a per-image cache of Refresh's host-import lookup. #7457 remembers structural misses ofHostImportFor; the cache here remembers hits and runs the sameHostImportForbody on a miss, so they compose.Checklist
main; no other open PR implements the same functionsNotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file.mdfiles or images added to the repository (attach them to this PR)Imported from boykopovar/AnyPS5. Originally posted by akkadbakkad89 on 2026-10-18T11:28:13Z.
Windows runs at head
b3120a214(first non-lavapipe datapoint for this head):agc_range_index,agc_host_import_retire,agc_host_import_retirementandagc_driver_graphicsall pass - 4/4 on NVIDIA RTX 3070 (driver 617.42) and 4/4 on Intel UHD 630 (ANYPS5_GPU=UHD, igvk64). Windows 11, MinGW (WinLibs GCC 15.2.0), Release.Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-18T16:33:46Z.
AMD on Windows: the tests this PR names pass on an RDNA 3.5 GPU.
Radeon 860M (RDNA 3.5, driver 32.0.13058.8001), Windows 11 26300, WinLibs GCC 15.2.0 r7, Release.
main6efb7261bwith this PR (b3120a214) merged, together with #7296, #7446, #7377, #7445, #6708, #6748, #6785, #6706, #6613, #7449, #7391, #7489, #7484. They were built once, so the result is for the combination; each merge was clean.agc_host_import_retire,agc_range_index: pass, 3 runs of 3.agc_*test on the combined build: 713 of 716 pass. The 3 that fail,agc_driver_host_import_lifetime,agc_driver_quad_pixel_maskandagc_driver_layered_volume_vertex_no_gpl, fail the same way on unchangedmainhere, so none comes from these PRs.AI-assisted
Imported from boykopovar/AnyPS5. Originally posted by AlxcBTW on 2026-10-18T16:48:13Z.
@akkadbakkad89 @LeandroLP23 thanks for the Windows runs on NVIDIA, Intel and RDNA 3.5. They are the first non-lavapipe data for this head. The speed A/B (this PR against
APS5_NO_REFRESH_LOOKUP_CACHE=1in one build onmain) is queued on the lab machine, and I'll post the rows here.AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-19T01:51:51Z.
@AlxcBTW #6364 (flush-wait-newer-writers) has merged, and #7514 now conflicts with it in
Texture.cpp, inStorageTextureList. Both PRs rewrite the same container:RangeIndex<StorageTexture*>index kept up to date bypush_back/erase/remove, and adds theOverlapping()/StartingAt()queries (keepingMayOverlap).changed()on every mutation, a lock-freeSurelyClear()reader, andrebuild()to publish.Both change
push_back/erase/remove/MayOverlapand the members, so this needs a design choice rather than a keep-both merge. Could you rebase onto current main and decide how the index and the published snapshot live together? Specifically: doesSurelyClear()read the index, or does it still need the snapshot; who bumps the version on each mutation; and do the index and the snapshot stay consistent under the same lock? A short note in the PR on what you chose would help the re-review. Thanks!Imported from boykopovar/AnyPS5. Originally posted by blawesom on 2026-10-19T07:59:03Z.
Rebase handoff — rebased onto current
main(all three commits, authorship unchanged). Two conflicts inTexture.cpp'sPendingList:main'schanged()bookkeeping kept with yourRangeIndexmaintenance layered intoerase/remove, and yourRangeIndex+rangesmembers. OneENVIRONMENT.mdrow added forAPS5_NO_REFRESH_LOOKUP_CACHE(the conventions check requires it).Verified on Linux (CachyOS, kernel 7.2.9, GCC 16.2.1, Ninja, Release,
BUILD_TESTING=ON, AMD RX 9070 XT / RADV): builds; conventions pass; full suite green apart from the four knownmainregressions (#5444 Mesa, #7584 BDA, #7766, #7784), none from this PR.To pick it up:
Head is
a72a93f20.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-19T08:53:26Z.
@blawesom thanks for taking this one on. The
PendingListconflict is the tricky part, and the resolution needs two changes before it can go in:push_backlost the index insert. Taking main's version (withchanged()) droppedindex.Insert(...), so nothing ever enters the index. With the default settings,otherPendingOverlapsand the alias walk inRefreshthen never see a pending image.erasenow reads*itaftertextures.erase(it), so it removes the next texture's entry, or dereferencesend()when the last one was erased. The removal has to happen before the erase.Keeping main's bookkeeping, this is what it should be:
Also, the new
ENVIRONMENT.mdrow describes the variable backwards. SettingAPS5_NO_REFRESH_LOOKUP_CACHEturns the index and the cached host-import lookup off and goes back to the scans, and there's no default value. Something like: "disables Refresh's pending-registry address index and cached host-import lookup; Refresh rescans as before".The tests came through intact.
@AlxcBTW this is a real rebase, so
--ff-onlywon't pick it up. Once the fix is onrebase/7514, adopting it would begit fetch https://github.com/blawesom/AnyPS5 rebase/7514, thengit reset --hard FETCH_HEADon your branch andgit push --force-with-lease. Or you can mergemaininto your branch with the samePendingListresolution as above. Since main changed a lot aroundRefreshsince your base, we'll rerun full CI and the game check on the new head.Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-21T21:17:41Z.
This pull request is labeled
perf, so it needs the summary line of a capture onmainand one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste bothaps5-summary.jsonllines, attach the two traces and add the output oftools/trace_digest.py.Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-10-21T21:48:09Z.
The current head
3258892a45crashes SuperTuxKart (PPSA69421, ps5-opengl) at the start of a race. The cause is the quick path inStorageTexture::refreshmeeting the scoped layer refresh from #6202, whichmaintook with #6718 today.Crash. Access violation reading
0x10inStorageTexture::refresh(libSceAgcDriver.prx+0x34352e). The call chain isDrawPipeline::run→commitDraw→Graphics::Draw→CachedStorageLayers→cachedStorageTexture→refresh. It happens on every run, about 3 s into the race, on the head as pushed and on my own merge of the previous head withmain0c6a5bd593.mainalone at0c6a5bd593does not crash.Cause. When
quickholds,changedstays empty (if (!quick) changed.assign(trackedLayers, false);). The scoped block added by #6202 still reads it for every layer outside the requested range:changed[135]on an emptystd::vector<bool>reads word 2 of a null buffer, which is the0x10in the fault. STK's two-slice color targets take this path on every draw. The merge doesn't show a textual conflict here, and the unit tests in this area pass (57 of 57 on the merged build), so nothing flags it before a title runs.Fix I tested. The same guard the PR already puts on the
pendingChangedloop:With
quicknothing is stamped andcomparedis false, so the loop would leaveoutsideall false anyway. With the guard the race runs, and therange_index|retire_hold|storage|pending|host_import|texture|array|layertests pass (80 of 81; the one failure isagc_driver_image_array_window_past_layer_limit, which doesn't compile onmain, #8310). A test that refreshes a scoped layer range of an unchanged block-unit image would catch this.Race numbers with the guard. Four alternating rounds, 20 s trace windows, same scene. Radeon 860M, Ryzen AI 7 350, Windows 11 26300, AMD 32.0.13058.8001, WinLibs GCC 15.2.0, Release.
main0c6a5bd593+ this PR + guardmain0c6a5bd593This doesn't support a speed claim either way:
The
APS5_PROFILE_DRAW=1run is more direct.lookupis 801 ms per 10 s with the PR and 654 ms without.readTargetis 1165 ms with the PR and 1200 ms without.In this title the Refresh cost sits in the target-page collect, which this PR doesn't aim at.
AI-assisted: yes (Claude Code)
Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-11-01T19:57:48Z.
Review: COMMENTED
1. No measurement of this PR. The Minecraft Dungeons II figures are, in the PR's own words, "from lab builds, not from this PR's head against main". In the A/B/C job the title rows show GPU busy per present at 76.6 to 77.3 ms in all three arms and FPS of 8.67 / 8.26 / 9.08 (arm c, the cached lookup, is what this PR contains), with a spread inside arm a of 8.07 to 9.27. Gameplay is explicitly memory-noisy (arm a alone ranges 1.15 to 5.95 FPS). The body says the title speed gain is not established, so the perf claim in the title is not backed. Please give
tools/trace_digest.pysummaries ofmainand of this head from the same machine and scene.2. Test coverage is Linux lavapipe CI only. Not run on Windows, where
HostImportForCachedrunssettleUnwatchedImportson every call. The switchAPS5_NO_REFRESH_LOOKUP_CACHEis not exercised by any test, so the old path is not compared against the new one in CI. Two of the three commits already failed CI after the merge (the out-of-rangechanged[layer]read and the last-use stamp count), which suggests the equivalence is not as obvious as the "same answers" argument says; a test that runs the same sequence with the switch on and off and compares results would cover that.3.
RangeIndexcost.InsertandRemovesetstale, and the nextOverlappingcall doesreach.assign(n, 0)plus an O(n)build.Insertitself is an O(n) vector insert. For a pending list that churns between queries (register, query, retire, query) each query is O(n) plus an allocation, i.e. no better than thestd::any_ofit replaces and possibly worse. What are the pending list sizes and the insert-to-query ratio in the title scene? A counter for rebuilds per 10 s next to the existing lookup counters would show whether the index pays off.Pull request closed