You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
perf(agc): cut the CPU work of PM4 register writes, submission copies and validation - #18914
The CPU path of a PM4 submission does more work than it needs at four points: writing register ranges, copying and scanning the command buffer, looking up the indirect register lists, and validating register writes. This PR removes that work while preserving packet validation, ordering and register values.
CbSet*RegistersDirect and the register range and list writers of libSceAgc copied their values into a std::vector before writing. They now write straight into the command buffer, split by the same runs. A single register write goes from 56 to 22 ns (1,239 to 595 instructions, one allocation to none); a 12-register list in 6 runs from 1,051 to 183 ns (17 allocations to none).
A submission's register lists are kept in a sorted array (RegisterLists) instead of a std::map; at() still throws std::out_of_range for a missing cursor (the diagnostic text depends on the standard library on main), and ReferencedPrograms and the dispatch-ahead scan read the new type. copyCommands sizes its buffer up front.
copySegment records the cursors of the flip, rendering-wait, end-of-pipe, label-write and wait packets and copies runs of ordinary packets with one insert; waitForFlipRoom, holdFlipBehindWorker and reserveOutputs visit only the recorded cursors, and fall back to the full scan when the copy met a non-type-3 or truncated tail. Copying 26 draws goes from 2.69 to 0.80 us (60.5k to 18.5k instructions); the three scans from 727, 731 and 1,175 ns to 3.1, 4.7 and 4.4 ns. A whole 26-draw submission (copy and scans) costs 9.7 us before and 5.1 us after (190k to 113k instructions, 9 allocations to 1); with three indirect register packets per draw, 29.4 and 16.3 us.
Pm4::Validate checks the four register write opcodes (80 % of a draw's packets) first, and an opcode table replaces the UnsupportedReason switch for opcodes that have no reason. A register write validates in 4.8 ns instead of 11.3 ns.
Behaviour locks: new tests pin the register writers across buffer growth and run splitting, the lookup of absent register list keys and the PM4 validation messages of the register write opcodes and of every unsupported opcode (all pass before and after the change). A differential of the new validation against the previous one over 4 million random and edge packets found no mismatch, and a digest over 8,000 random PM4 streams (valid ones and ones with truncated or non-type-3 tails, indirect packets, flips, rendering waits, end-of-pipe releases, label writes and conditional ends) covering copy, validate, lists, waitForFlipRoom, holdFlipBehindWorker and reserveOutputs is identical before and after. The figures are single-process fixture measurements (alternating runs of the parent and the change) from the older stack the commits were written on, not a title trace.
The register writer tests cover range lengths 64, 65 and 130, and register lists of 32, 33, 64, 65 and 130 entries. Register writes share the accepted flag mask with the general validator. The tests check rejection reasons for every opcode and flag byte, and exercise the four register-write opcodes at every flag byte.
Tested
Linux retest on the rebased head. Base 01c550960a9; change 144ab00b45f. The marker NOP fast path on the previous head rejected 0x68754000 in GCN mode. Marker NOPs now go through general validation. A focused reproducer on Linux fails on 6a8befbcf85 and passes on both main and the new head: GCN accepts the ordinary marker on both queues, legacy flip markers retain their specific error, and non-GCN rejects typed markers.
Ubuntu 25.10 x86-64, GCC 15.2 Release, BUILD_TESTING=ON. The same 11 CTests ran serially on main and the PR under QEMU user 10.0.13 (AVX2), using Mesa llvmpipe 25.2.8 (LLVM 20.1.8) and Khronos validation 1.4.335. Both runs: 11 passed, 0 failed, 0 skipped. Both logs show the loader inserting the validation layer, no missing-layer warning and no VUID-. agc_driver_pm4 ran and passed on the new head. The suite also covers register writer boundaries, context register RMW, REWIND copy/size/trace, prepared shaders (default, indirect, debug) and both GPU-written indirect-buffer cases.
The REWIND test includes twelve deliberate waits and produces a one-present trace. First lines of tools/trace_digest.py for the same synthetic fixture (not used as performance evidence):
main: frames 0:1 from present 0: 1 presents, frame p50 70.5 / p90 70.5 / p99 70.5 / max 70.5 ms, GPU busy 0.0 ms per present
PR: frames 0:1 from present 0: 1 presents, frame p50 73.8 / p90 73.8 / p99 73.8 / max 73.8 ms, GPU busy 0.0 ms per present
I checked the indirect-buffer merge: replacement keeps the lists before the splice, takes the re-read lists within it, and shifts later cursors by the size difference. After a splice the submission falls back to the full scan. Output reservations capture waits before processing the next relevant packet, including trailing segments. The rebase preserved that code unchanged.
Paired CPU fixture on this head: one three-word SET_SH_REG (opcode 0x76, register offset 0x10, increasing payload) validated on the graphics queue. Linux x86-64 via OrbStack on an Apple M3 Max, GCC 15.2, -O2, no LTO. Both binaries linked the same harness and GCN decoder with their revision's production PM4 validator. Eight processes per arm in alternating order, 250,000 warmups and 10 million calls per process, no other compilation or tests running in the container. Median 13.18 ns/call on main (13.13–13.72) and 6.52 ns/call on this head (6.45–6.60). This measures CPU packet validation only. On an earlier revision the Cyberpunk intro comparison found no measurable frame-rate change. No paired title trace was captured on the new head.
Earlier macOS run:
macOS 27.0.1, Apple M3 Max (36 GB), MoltenVK 1.4.2 from Vulkan SDK 1.4.363.0, Release build with -DBUILD_TESTING=ON, x86_64 under Rosetta 2. main does not run its libraries on macOS, so both sides are main3b7f31fa7 with the macOS port (the squash of #8658, which its author upstreams in parts) and local macOS build fixes for tests of main that Apple clang refuses; the change side adds this PR's commits.
Focused AGC, shader recompiler and VideoOut set, 811 tests, on both sides with VK_LAYER_KHRONOS_validation, VK_LOADER_DEBUG=layer, ANYPS5_REQUIRE_VULKAN=1 and ANYPS5_NO_SHADER_CACHE=1 (ctest --test-dir build-macos -R '<811 test names>' -V): on the change 702 pass, 71 skip, 37 fail and 1 times out, against 704, 71, 35 and 1 on main. The two tests that differ, agc_driver_graphics and agc_graphics_profile_draw, both stop on "two ranges under a budget for two were not imported" (the host refusing a memory import under load), which is intermittent on this Mac with or without the change: run alone ten times in the same conditions, agc_driver_graphics passes 8 times on main and 9 times with the change, and agc_graphics_profile_draw 9 times and 10 times. Every other test has the same status as on main; the failures are the ones main has on macOS (MoltenVK limits and macOS-only gaps of the tests). Both runs report the same 77 VUID- errors test by test, and was not found but was requested by env var VK_INSTANCE_LAYERS appears only in the 12 lines that print the failure regex of the agc_driver_image_table_packed* tests. The logs show the loader inserting the layer (Insert instance layer) in 490 tests.
WriteRegisterRange copied the values into a std::vector before the buffer
allocation and WriteRegisters added a vector per run plus a snapshot of the
whole list, so a single register write cost one allocation and a list of
twelve registers in six runs cost 16 or 17.
The snapshots now live in a 64-word (32-register for the list) stack buffer
that falls back to the heap above that size. Values are still read before the
buffer is allocated, run splitting, check order and exceptions are unchanged.
Measured on agc_command_tests probe (7 alternating runs per arm, median ns,
instructions, allocations per call): single register 56 ns / 1239 / 1 ->
22 ns / 595 / 0; range of 8 56 -> 22 ns; SetShRegistersDirect 12 registers in
6 runs 1051 ns / 21.6k / 17 -> 183 ns / 3.4k / 0; SetUcRegistersDirect 928 ->
111 ns, 16 -> 0 allocations. The indirect builder (unchanged control) stays at
14.6 ns.
Submission::copy records the cursors of flip, rendering-wait, EOP-release,
label-write and wait packets while copying and appends runs of ordinary
packets in one insert. waitForFlipRoom, holdFlipBehindWorker and
reserveOutputs visit only the recorded cursors, and fall back to the full
scan when the copy met a non-type-3 or truncated tail.
26-draw submit: copy plus scans 9.7 -> 5.1 us (190k -> 113k instructions),
waitForFlipRoom 727 -> 3 ns, holdFlipBehindWorker 731 -> 5 ns,
reserveOutputs 1175 -> 4 ns.
…supported opcodes
Characterizes the exact Pm4::Validate messages for the four register write opcodes (flags, sizes, offsets, queues, tag markers) and the rejection reason of every unsupported opcode, so that a faster validation path can be shown to keep them.
…dispatch
Pm4::Validate checks the four register write opcodes (SET_CONTEXT/SH/UCONFIG_REG and the indexed uconfig write, 80% of the packets of a draw) first, and an opcode table replaces the UnsupportedReason switch for opcodes that have no reason. Messages and their order are unchanged (differential against the base copy over 4M random and edge packets: 0 mismatches). A register write validates in 4.8 ns instead of 11.3 ns.
This pull request is labeled perf, so it needs the summary line of a capture on main and one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste both aps5-summary.jsonl lines, attach the two traces and add the output of tools/trace_digest.py.
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.
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.
Independent Windows / RX 7800 XT result for #18914
Tested head a95bfaad31ab8f81441bbe1ce1f6e20886ca5d37 against unmodified maine6a39b3759b8ba948189a911088b06561595b059. The PR arm is their clean local merge 760a4ce7f2569ce9b3f8c5aa8adfa8909d39ef85, tree 6dc3a24c55f6895b7f6dfaa3c095a13e91a7965f. No other PR or platform fix was applied; the source remained clean. These are pinned results, not a test of a future rebase onto newer main.
Setup: Windows 11 Pro 10.0.26300, Ryzen 5 7600, AMD Radeon RX 7800 XT, Windows driver 32.0.32015.7029 / Vulkan device API 1.4.359. MinGW GCC 15.2.0, CMake 4.3.1, Release, BUILD_TESTING=ON, bundled dependencies. Full libs target and the same 917 test/helper targets built on each arm using an existing build cache, two compiler jobs, BelowNormal. Tests ran serially at Normal priority, without a process RAM ceiling or restricted CPU affinity.
Functional and validation comparison
The same 1,736 AGC, AGC driver, shader/recompiler and VideoOut CTest names ran on both arms. This is the selected relevant suite, not every repository test.
No newly failing case or timeout appeared. The nine shared failures have matching diagnostics: the eight f16 signed-zero cases described in LeandroLP23's #18484, plus agc_driver_sample_order_grid_reference. Our f16 startup probe selects native narrowing (0 of 220032 probe results differ). Neither #18484 nor its environment workaround was applied or tested here.
The PR's extended agc_register_command_tests, agc_driver_pm4, agc_driver_prepared_shaders and _debug all pass.
The two apparent improvements are intermittent, not demonstrated fixes. Five additional alternating runs per arm, using frozen binaries without rebuilding, give:
Test
main failures / 5
PR failures / 5
agc_driver_dumped_constant_capture
2 / 5
2 / 5
agc_driver_unregistered_label_on_gpu
1 / 5
1 / 5
The former reports 255 instead of 127/128 after rewriting a dumped constant; the latter sees the earlier label only after device idle. The late-label symptom is also documented in #17999/#17937. Those proposed fixes were not applied here. These small repeat counts do not establish failure probabilities.
Validation: Khronos layer 1.4.368 was actually inserted in 1,179 cases on each arm; logs select the RX 7800 XT and contain no missing-layer warning. Neither arm logs a VUID- message. Both log the same 61 non-VUID validation warnings in 14 cases, with identical per-test IDs, counts and severities (Undefined-Value-* shader-output warnings). They are not warning-free runs. No new validation message was found.
The 30-second default preserves explicit per-test TIMEOUT properties. Overlay implicit layers were disabled only for these processes. No driver shader-cache reset was made.
Independent CPU fixtures
A deterministic corpus of 2,310,720 generated/edge PM4 packets gives identical acceptance counts and diagnostic digest: 12,781 accepted, 2,297,939 rejected, FNV-1a64 785099e5dbbf028c. This is finite-corpus evidence, not a proof for every possible stream.
Separate CPU timing fixtures alternate five processes per arm, seven warmed million-call trials per metric per process. No compilation or GPU suite overlapped these timings. Medians are nanoseconds per call:
Fixture
main
PR
register range, 1 value
35.711
13.434
register range, 8 values
37.611
14.954
register range, 65 values (spill)
42.524
43.721
12-register list, six runs
561.865
101.236
validate SH register packet
6.130
3.930
The 65-value case has overlapping ranges and a PR outlier; its median is slightly higher. Raw samples are included. These fixtures do not measure whole-submission time, a title trace, or game FPS, and do not satisfy the bot's real-title performance-capture requirement.
Small diagnostic wording difference: the host-only missing-key helper throws std::out_of_range on both arms, but GNU libstdc++ prints map::at on main and the new RegisterLists::at prints map::at: key not found. The description's same-message claim therefore differs on this Windows toolchain; the exception type is unchanged.
The evidence includes commands, selected test/target lists, CMake caches, submodule pins, executable/runtime hashes, full logs and JUnit, per-test comparisons, CPU fixture sources/results, and sampling limits. A PR run interrupted during a workspace/runtime transition was preserved separately and restarted in full; its partial results are not combined with the completed run. External helper setup failures were corrected without editing tested source and are separated from valid results.
Not tested: a real title, FPS, console behavior, Linux or macOS. These results do not validate later source changes or a future rebase.
AI-assisted: yes (Codex); all build/test results above come from our own pinned Windows builds and saved logs.
Windows check of head a95bfaad31. Setup: Windows 11 Enterprise 22621, AMD RX 6700 XT, AMD driver 26.10.1, MinGW-w64 GCC 15.2 UCRT, Release.
The 28 AGC driver tests that cover the changed files, including agc_driver_pm4, agc_driver_pm4_failure, agc_driver_pm4_failure_inline, agc_driver_pm4_rewind_trace and the agc_driver_prepared_shaders* set:
GPU, through the shared Windows GPU FIFO with ANYPS5_REQUIRE_VULKAN=1, merged onto mainbb61b03635 (merge f2ea6c679b): all 28 passed in 3 of 3 runs, 84 of 84 outcomes. The binaries matched the hashes recorded at preparation, and the receipt shows exit 0 and app_count=0.
CPU, Vulkan hidden (merge 8620b576a5): 5 passed and 23 skipped (they need a device), 0 failed, in 3 of 3 runs.
This is a correctness check only; I did not measure the CPU-time change.
A Linux run, next to the Mac and the two Windows runs: RTX 3070 (8 GB), NVIDIA 610.57.04, Ryzen 5 5600X, Debian 13, kernel 6.12.115, GCC 13.3.0 Release, validation layer 1.4.335, ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1 VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation.
the 47 tests of agc_driver_graphics_tests, including agc_driver_graphics and agc_graphics_profile_draw, 3 runs
all passed 3/3
all passed 3/3
VUID- lines / layer not found
0 / 0
0 / 0
The "two ranges under a budget for two were not imported" stop from the Mac did not appear in any of these runs. This is a correctness check only; I did not measure timings.
agc_register_command_tests 0.16 s (the new register-write validation cases), agc_driver_pm4 0.58 s (the new Pm4.cpp decode), agc_driver_prepared_exports 0.81 s; 3 of 3 pass.
No VUID- line and the layer loaded.
No AMD timing number: the PR's CPU measurements are from macOS/MoltenVK under Rosetta. This is the functional side on Windows with a different compiler and driver.
…ITE register write
Move the register-destination COND_WRITE check to the top of the scan loop,
away from the indirect-register branch that boykopovar#18914 rewrites, so the two
changes merge without a conflict. Behaviour is unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reason will be displayed to describe this comment to others. Learn more.
I traced the three paths that carry the "unchanged" claim on a95bfaad31.
Direct register writes.WriteRegisterRange still leaves the payload untouched when values == nullptr (Packet.cpp:154 passes the null through), but that is unchanged from main: the old snapshot.resize(count) was inside the same values != nullptr branch, and the batch path writes nothing in that case. The run splitting in WriteRegisters reproduces the old count != 0, count <= 0x3fff, offset <= 0xffff and count <= 0x10000 - offset checks.
Register lists.readRegisterLists clears submission.registerLists before it appends (Submission.cpp:353), and it walks commands in ascending order, so the sorted vector is never fed out of order. The reuse path in copyCommands is safe because the only caller clears first.
Scan cursors. Every scanned packet is recorded: the batch path records the first packet and each following one at first + (end - cursor); the default path records at the insertion point; the predicated-indirect path inserts the 4-word packet and the target goes through the same copyLink; the truncated tail is the only path that sets scanAll = true. I did not find an insertion that leaves scanAll == false with a missing cursor.
Two small test gaps, neither blocking:
testRegisterWritesDoNotAllocate uses 12 registers and 8 values, below the 32/64 inline limits of SmallSnapshot; it would still pass if the spill thresholds regressed. Add 64/65-entry cases (and a contiguous run longer than 64) and assert the contents.
Pm4::Validate's WithoutReason cache duplicates the flag check: it is equivalent today, but a later narrowing of allowedFlags would be accepted by the cache. A shared helper, or a test that both paths agree on every opcode/flag pair, would pin it.
The four independent hardware reports cover the functional side; I did not find a behavior change the PR misses.
… lists valid across an indirect buffer refresh
copyLink: the run of unguarded packets is copied before main's REWIND branch; a run already ends at a REWIND or an INDIRECT_BUFFER, so the REWIND word is still loaded once in its own branch.
refreshIndirectSegment (new on main): the register lists of the replaced segment go through RegisterLists::replace, which drops the lists inside the segment, takes the new ones and moves the later ones with their packets. The submission falls back to scanning every packet after a splice, since the scan list was built at the copy.
reserveOutputs: main's capture of rendering waits for each indirect segment runs inside the packet scan, at the first scanned packet at or after the segment, and for the remaining segments after the scan.
holdFlipBehindWorker: the two scans keep the scan list and return main's result.
Tests: both sides' PM4 tests are kept; testRegisterListReplace covers the new method.
@atinseau I merged current main (1770ee2) into this branch to clear the conflicts: one merge commit, 63c1244, on top of a95bfaa. Please pull before your next push.
This was more than a textual merge, because main now re-reads an indirect buffer when execution reaches it (refreshIndirectSegment, #11346) and splices the new commands into the submission. Please check the parts that are mine:
RegisterLists::replace(start, end, delta, inner) is new. Main's refresh shifted and inserted into the old std::map; with your sorted vector it drops the lists inside the replaced segment, takes the re-read ones and moves the later ones with their packets. testRegisterListReplace in tests/Pm4.cpp covers it.
After a splice the submission sets scanAll = true, since scanCursors was built at the copy. Every ScanPackets user runs at submit, before the submission is queued, so this is a guard, not a cost on the submit path.
reserveOutputs: main captures the rendering waits of each indirect segment when its loop reaches the segment. With your scan list that capture runs at the first scanned packet at or after the segment, and once more after the scan for the segments left. Only scanned packets change the wait targets, so the order is the same as on main.
The rest is direct:
copyLink: your run of unguarded packets sits before main's REWIND branch. The run already ends at a REWIND or an INDIRECT_BUFFER, so the REWIND word is still loaded once in its own branch.
holdFlipBehindWorker: your two scans, with main's bool result.
tests/Pm4.cpp: your testValidationMessages and main's testContextRegRmw are both kept.
Tests on the merged head (Linux, RTX 4090): 107 passed, 0 failed, 27 skipped (all video out flip tests, which my test filter matched by name and which do not touch this change). The run includes agc_driver_pm4, agc_register_command_tests, agc_driver_prepared_shaders, the rewind tests and main's agc_driver_gpu_written_indirect_buffer pair. None of them puts a register list inside a refreshed indirect buffer, so that path is covered only by the unit test. Conventions check passes. I did not measure performance on the merged head.
…on paths accept
The register write fast path of Pm4::Validate tested the header flags with its own mask, apart from the allowedFlags of the general path. Both now use RegisterWriteHeaderFlags and PredicatedHeaderFlag, and testValidationMessages sweeps all 256 flag bytes of the four register write opcodes against the message of the general path.
(cherry picked from commit 901d9cf23744ee34e5cd5b37e2c3ec815f692a6d)
The no-allocation check used 8 values and 12 registers, below the 64 values and 32 registers SmallSnapshot keeps inline. Ranges of 64, 65 and 130 values and lists of 32, 33, 64, 65 and 130 registers, contiguous or not, now assert the allocation count up to the limit and the packet contents at every size.
(cherry picked from commit 2bb64117bcd3e38509914f88982a68871c4c3651)
Only plain NOPs with untyped payloads can skip general validation. Let the existing GCN rules accept marker NOPs and report the specific legacy flip and reservation errors.
Ran the 11 focused tests from the Tested section with the Khronos validation layer on Linux and an NVIDIA GPU, on the rebased head 144ab00b45 with the marker NOP fix; the earlier NVIDIA Linux run is of a95bfaad31.
Setup: Arch Linux (kernel 7.3.4), GCC 16.2.1, Release, NVIDIA GeForce RTX 4090 (vendor 0x10de, device 0x2684, Ada, subgroup 32), proprietary driver 620.70.06, Vulkan 1.4.357, Khronos validation layer 1.4.363.1. Head 144ab00b45 merged onto main 1adc0e2f4b with --no-ff, clean merge. Main baseline is a Release build of 1adc0e2f4b on the same machine.
was not found but was requested by env var VK_INSTANCE_LAYERS
0
0
VUID-
none
none
agc_driver_pm4 (which covers the marker NOPs on both queues) and agc_register_command_tests pass on both sides, as do the REWIND, prepared-shader and GPU-written indirect-buffer tests. Every device selection picked the RTX 4090. This is a correctness check only; I did not measure timings.
No new VUID- errors; all focused tests pass on Ada.
AI-assisted: yes (Claude Code)
ycbuzi
added a commit
to ycbuzi/AnyPS5
that referenced
this pull request
Nov 19, 2026
The reason will be displayed to describe this comment to others. Learn more.
Reviewed — looks good
The reviewed changes appear sound on the inspected paths; author-reported tests passed, but I did not run checks in this review.
What I ran
Read the prepared diff and changed source at head 144ab00b45f172b9dd8ffd5be874ae9f585fd4ff using repo_read.py reader tools. No commands or tests were run.
Results
Check
Result
Note
Changed source review
passed
Inspected all nine changed files
Tests in this review
not run
Results in the description are author-reported
Findings
Blocking
None.
Non-blocking
None.
Not verified
I did not run tests, builds, or benchmarks. I read all files listed as reviewed in manifest.json; no files were excluded in that manifest. files.json was not available through the reader, so additional exclusions are not verified.
@oneandonlydean@atinseau A paired frame measurement on this head, as asked on Nov 17, on Windows + NVIDIA with an Intel CPU, in two titles with warm caches. Neither title changes by the 1–1.5 % or more that two runs per arm can resolve.
Setup
Windows 11 Pro for Workstations 26300, RTX 5060 Ti 16 GB (NVIDIA 621.24), i9-14900K, WinLibs GCC 15.2.0 r7, Release.
main5dcb83a552, and this head 144ab00b45 merged onto it (13b695d1a7, clean merge).
Astro Bot (PPSA21564 01.007.000), -lvl big_hand_pirate_island, no input, 200 s per run. Stray (PPSA02100 01.002.000), a scripted route to the first gameplay scene, 300 s per run.
Astro Bot, FPS over the 60 s after the level starts
3.807 / 3.815
3.830 / 3.818
Stray, FPS at 180–290 s
23.70 / 23.75
23.89 / 23.87
Astro Bot runs at about 4 FPS on this level, so each run is aligned at the level start instead of a fixed time window.
+0.3 % on Astro Bot and +0.7 % on Stray. On Stray the two main runs differ by 0.2 % and both runs of this head are above both, but two main runs of this scene usually differ by 1–1.5 % across sessions, so two runs per arm can't separate +0.7 %.
Most of what this PR changes (the register writers, the command copy and Pm4::Validate) runs at submit on the title's own thread (Submission.cpp:811–815), which no trace phase times, so the frame rate is the only measure of those paths here.
Where the change shows
Driver.Packet.execute (the queue worker's time on packets other than draws, dispatches and waits; it includes the register-list lookup this PR changes), in the 10 s trace window: on Astro Bot 7.1 / 6.8 ms per frame against 8.0 / 7.8 on main (and 8.0 on main's warm-up run). On Stray 1.25 / 1.20 against 1.56 / 1.47, but the two depth-128 runs, which don't have this PR, read 1.26 / 1.38, so I would not lean on the Stray numbers.
On Astro Bot both runs of this head, and main's warm-up run, were in a state with about 25 % more GPU copy bytes and ~8 ms less GPU busy per frame than the two measured main runs. It appears on main too, so it isn't from this PR, and the frame rate is the same in both states.
Summary lines (Stray, trace window at 240 s), main and this PR, for the PR body (the label is read from the body only)
Queue worker 0's trace buffer fills 7.5–9 s into each 10 s window (trace_dropped in the lines); the counters and phase totals above come from the summary lines, which keep them complete (totals_full is false).
Not covered: Linux, AMD, other titles. The traces are kept if you want them.
Paired frame measurement on Linux/AMD, in a scene where PM4 validation is a large CPU cost on main. No measurable change.
Setup: Linux 7.3.5, RX 7900 XTX (RADV), Ryzen 9 7950X, GCC 16.2.1, Release. A = main2b0d3eed8e; B = the same main with this PR's head 144ab00b45 merged (8027458f0c, clean merge). Insomnis (PPSA06829), fresh save, warm shader cache, New Game, ending in the first interior room with no further input. Runs were 330 s, alternating A B B A, through game_coord.py launch --perf. FPS is over 280–325 s. Every run shows the room's flashlight prompt in its screenshots at both 280 s and 325 s.
run
arm
FPS 280–325 s
1
main
9.06
2
this PR
9.26
3
this PR
9.53
4
main
9.62
Means: 9.34 (main) and 9.40 (PR). The difference is inside the run-to-run spread, and both arms drift upward over the session.
Why this scene should be sensitive. A main diagnostic run in the same room (inst223634, APS5_PROFILE_DRAW=1) reports, per 10 s on queue 0, 611 submissions with validate 5076.2 us per submission (about 3.1 s), ACQUIRE_MEM ×81,749 (2,343 ms) and DRAW_INDEX_OFFSET_2 ×97,216 (2,660 ms). A 6 s trace puts queue worker 0 at 88.5 ms busy per ~107 ms frame, with the GPU about 69 % busy. I did not run the profiled build with this PR, so I can't say how much of the 5 ms per submission it removes. The frame rate here does not move.
This passed review on 144ab00, but it now conflicts with main in Pm4.cpp. Please merge main into the branch and push; it goes back to the merge queue on the new head.
Snapshot and emit register writes core/libs/prx/libSceAgc/Command/src/Packet.cpp, core/libs/prx/libSceAgc/tests/RegisterCommands.cpp
Register-range and register-list writes use inline snapshots, with vector storage when the configured capacity is exceeded. Tests cover buffer growth, packet encoding, inline limits, and allocation counts.
Register-write checks move to a shared validation helper. Tests cover validation messages, header flags, and queue rules.
Use RegisterLists for indirect register data core/libs/prx/libSceAgcDriver/Execution/include/Driver/Queues/Submission.hpp, core/libs/prx/libSceAgcDriver/Execution/src/Driver/Dispatch/DispatchAhead.cpp, core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp, core/libs/prx/libSceAgcDriver/tests/Pm4.cpp, core/libs/prx/libSceAgcDriver/tests/execution/PreparedShaders.cpp
Submission replaces map-based indirect register data with RegisterLists. Lookup, replacement, packet preview, and program-reference paths use the new container.
Track and scan selected packet cursors core/libs/prx/libSceAgcDriver/Execution/src/Driver/Packets/CommandValidation.cpp, core/libs/prx/libSceAgcDriver/Execution/src/Driver/Queues/Submission.cpp, core/libs/prx/libSceAgcDriver/tests/Pm4.cpp
Submission records cursors for selected packets and uses them in flip checks and output reservation. Malformed packet parsing and indirect-segment refresh trigger full scans.
Possibly related issues
boykopovar/AnyPS5 issue 27409: The changes update command copying and packet scanning along the indirect-buffer path. The provided summaries do not establish that they fix the reported timeout.
Suggested reviewers:boykopovar, xairrrr, pipodi
Change: Refactor
Merge Risk: Minimal · up to 4d520
This change reduces CPU work in AGC register writes, register-list lookup, packet scanning and PM4 validation while keeping packet validation, ordering and register values the same. No concrete defect was identified, and the reported focused tests pass. The author's own measurements show gains on synthetic fixtures; title-level gains are not shown. Merge-readiness risk is minimal.
Security architecture risk: Moderate · up to 4d520
The optimization can cause the driver to miss a required wait if the submitted commands change while being copied. A missed wait can interrupt graphics and compute work across the same driver instance, rather than failing only the affected submission.
Retained concerns
Medium · security · inferred: The head derives wait and reservation positions from guest memory separately from the command bytes it later copies and validates. Concurrent modification can leave a valid command snapshot without its required preparation. The base scanned the owned snapshot for that preparation. In the head, a missing rendering-wait entry can fail execution and cause the shared driver failure handler to clear pending work across queues.
Security review details
Security Blast Radius
inferred — The supported exposure is availability within a driver instance. A worker failure can fail registered outputs, clear pending work across queues, and cause later submissions to fail. The reviewed path does not establish privilege gain or cross-process impact.
Security Findings and Attack Paths
inferred — A guest able to modify command storage during submission can cause the recorded preparation metadata to disagree with the validated commands. The downstream rendering-wait lookup assumes the reservation was prepared; it does not treat a missing entry as a submission-local rejection.
Trust Boundaries and Controls
observed — Packet framing and PM4 checks still gate preparation, and reservation still checks that referenced video outputs are registered. These checks do not establish that the cursor cache includes every command requiring preparation.
Hardening Proposals
proposed — Build the cursor index during validation of the owned command snapshot, or verify its completeness against that snapshot before any wait or reservation. If the index cannot be trusted, scan the validated snapshot in full before accepting the submission.
Finishing Touches
Generate unit tests (beta)
Create a new PR
Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
The reason will be displayed to describe this comment to others. Learn more.
Architecture findings (1)
Advisory architecture findings (1)
Minor — The head derives wait and reservation positions from guest memory separately from the command bytes it later copies and validates. Concurrent modification can leave a valid command snapshot without its required preparation. The base scanned the owned snapshot for that preparation. In the head, a missing rendering-wait entry can fail execution and cause the shared driver failure handler to clear pending work across queues.
Review info
Run configuration
Source mode: Auto
Repository: Unavailable
Branch: Unavailable
File: No configuration file from this repository applied
Commit: Unavailable
Layers: defaults
Review profile: CHILL
Plan: Advanced
Run ID: 3099cc99-3c4f-40fd-b47b-1ad89b1441d2
Commits
Reviewing files that changed from the base of the PR and between 1f27e2a and 4d5207a.
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
The reason will be displayed to describe this comment to others. Learn more.
Reviewed — comments
The diff and all nine changed files were reviewed at head 4d5207a4c557837589c10b4dc177db1602b5c147; no blocking defect was verified, but I did not run the checks needed to justify approval.
What I ran
I inspected the PR description, commit list, manifest, and complete diff at the stated head. No commands or tests were run by me. Test results in the description are author-reported.
Results
Check
Result
Note
Diff and changed-file review
passed
All nine changed files’ added lines were inspected.
Automated checks
not run
The described Linux and macOS runs were not independently verified.
Negative control
not run
No negative control was run during this review.
Findings
Blocking
None verified.
Non-blocking
No code-level findings. The reported test results and performance measurements remain author-reported for this review.
Not verified
I did not run tests, build the change, or independently verify the author-reported test and benchmark results. No files were excluded from the changed-file review; the diff excludes files omitted by the prepared review rules.
To get this to a good state
Nothing is required. The author-reported checks and performance measurements are optional context, not independently verified findings.
… and validation (boykopovar#18914)
* test(agc): lock register range and list writers across buffer growth and run splitting
* perf(agc): write register ranges and lists without heap snapshots
* perf(agc): keep submission register lists in a sorted array and size the command copy up front
* perf(agc): scan only the packets that need submission handling
* test(agc): lock the PM4 validation messages of register writes and unsupported opcodes
* perf(agc): validate register write packets without the opcode reason dispatch
* refactor(agc): name the register write header flags both PM4 validation paths accept
* test(agc): lock the inline limits of register range and list writers
* fix(agc): validate marker NOPs with the guest shader mode
* test(agc): check unsupported PM4 reasons for every flag byte
(cherry picked from commit e7e1b16)
… and validation (boykopovar#18914)
* test(agc): lock register range and list writers across buffer growth and run splitting
* perf(agc): write register ranges and lists without heap snapshots
* perf(agc): keep submission register lists in a sorted array and size the command copy up front
* perf(agc): scan only the packets that need submission handling
* test(agc): lock the PM4 validation messages of register writes and unsupported opcodes
* perf(agc): validate register write packets without the opcode reason dispatch
* refactor(agc): name the register write header flags both PM4 validation paths accept
* test(agc): lock the inline limits of register range and list writers
* fix(agc): validate marker NOPs with the guest shader mode
* test(agc): check unsupported PM4 reasons for every flag byte
(cherry picked from commit e7e1b16)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
agclibSceAgc*perf numbers missingperf pull request without a before and after summary lineperfPerformance change
11 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
The CPU path of a PM4 submission does more work than it needs at four points: writing register ranges, copying and scanning the command buffer, looking up the indirect register lists, and validating register writes. This PR removes that work while preserving packet validation, ordering and register values.
CbSet*RegistersDirectand the register range and list writers oflibSceAgccopied their values into astd::vectorbefore writing. They now write straight into the command buffer, split by the same runs. A single register write goes from 56 to 22 ns (1,239 to 595 instructions, one allocation to none); a 12-register list in 6 runs from 1,051 to 183 ns (17 allocations to none).RegisterLists) instead of astd::map;at()still throwsstd::out_of_rangefor a missing cursor (the diagnostic text depends on the standard library on main), andReferencedProgramsand the dispatch-ahead scan read the new type.copyCommandssizes its buffer up front.copySegmentrecords the cursors of the flip, rendering-wait, end-of-pipe, label-write and wait packets and copies runs of ordinary packets with one insert;waitForFlipRoom,holdFlipBehindWorkerandreserveOutputsvisit only the recorded cursors, and fall back to the full scan when the copy met a non-type-3 or truncated tail. Copying 26 draws goes from 2.69 to 0.80 us (60.5k to 18.5k instructions); the three scans from 727, 731 and 1,175 ns to 3.1, 4.7 and 4.4 ns. A whole 26-draw submission (copy and scans) costs 9.7 us before and 5.1 us after (190k to 113k instructions, 9 allocations to 1); with three indirect register packets per draw, 29.4 and 16.3 us.Pm4::Validatechecks the four register write opcodes (80 % of a draw's packets) first, and an opcode table replaces theUnsupportedReasonswitch for opcodes that have no reason. A register write validates in 4.8 ns instead of 11.3 ns.Behaviour locks: new tests pin the register writers across buffer growth and run splitting, the lookup of absent register list keys and the PM4 validation messages of the register write opcodes and of every unsupported opcode (all pass before and after the change). A differential of the new validation against the previous one over 4 million random and edge packets found no mismatch, and a digest over 8,000 random PM4 streams (valid ones and ones with truncated or non-type-3 tails, indirect packets, flips, rendering waits, end-of-pipe releases, label writes and conditional ends) covering copy, validate, lists,
waitForFlipRoom,holdFlipBehindWorkerandreserveOutputsis identical before and after. The figures are single-process fixture measurements (alternating runs of the parent and the change) from the older stack the commits were written on, not a title trace.The register writer tests cover range lengths 64, 65 and 130, and register lists of 32, 33, 64, 65 and 130 entries. Register writes share the accepted flag mask with the general validator. The tests check rejection reasons for every opcode and flag byte, and exercise the four register-write opcodes at every flag byte.
Tested
Linux retest on the rebased head. Base
01c550960a9; change144ab00b45f. The marker NOP fast path on the previous head rejected0x68754000in GCN mode. Marker NOPs now go through general validation. A focused reproducer on Linux fails on6a8befbcf85and passes on both main and the new head: GCN accepts the ordinary marker on both queues, legacy flip markers retain their specific error, and non-GCN rejects typed markers.Ubuntu 25.10 x86-64, GCC 15.2 Release, BUILD_TESTING=ON. The same 11 CTests ran serially on main and the PR under QEMU user 10.0.13 (AVX2), using Mesa llvmpipe 25.2.8 (LLVM 20.1.8) and Khronos validation 1.4.335. Both runs: 11 passed, 0 failed, 0 skipped. Both logs show the loader inserting the validation layer, no missing-layer warning and no
VUID-.agc_driver_pm4ran and passed on the new head. The suite also covers register writer boundaries, context register RMW, REWIND copy/size/trace, prepared shaders (default, indirect, debug) and both GPU-written indirect-buffer cases.The REWIND test includes twelve deliberate waits and produces a one-present trace. First lines of
tools/trace_digest.pyfor the same synthetic fixture (not used as performance evidence):I checked the indirect-buffer merge: replacement keeps the lists before the splice, takes the re-read lists within it, and shifts later cursors by the size difference. After a splice the submission falls back to the full scan. Output reservations capture waits before processing the next relevant packet, including trailing segments. The rebase preserved that code unchanged.
Paired CPU fixture on this head: one three-word SET_SH_REG (opcode
0x76, register offset0x10, increasing payload) validated on the graphics queue. Linux x86-64 via OrbStack on an Apple M3 Max, GCC 15.2,-O2, no LTO. Both binaries linked the same harness and GCN decoder with their revision's production PM4 validator. Eight processes per arm in alternating order, 250,000 warmups and 10 million calls per process, no other compilation or tests running in the container. Median 13.18 ns/call on main (13.13–13.72) and 6.52 ns/call on this head (6.45–6.60). This measures CPU packet validation only. On an earlier revision the Cyberpunk intro comparison found no measurable frame-rate change. No paired title trace was captured on the new head.Earlier macOS run:
macOS 27.0.1, Apple M3 Max (36 GB), MoltenVK 1.4.2 from Vulkan SDK 1.4.363.0, Release build with
-DBUILD_TESTING=ON, x86_64 under Rosetta 2.maindoes not run its libraries on macOS, so both sides aremain3b7f31fa7with the macOS port (the squash of #8658, which its author upstreams in parts) and local macOS build fixes for tests ofmainthat Apple clang refuses; the change side adds this PR's commits.VK_LAYER_KHRONOS_validation,VK_LOADER_DEBUG=layer,ANYPS5_REQUIRE_VULKAN=1andANYPS5_NO_SHADER_CACHE=1(ctest --test-dir build-macos -R '<811 test names>' -V): on the change 702 pass, 71 skip, 37 fail and 1 times out, against 704, 71, 35 and 1 onmain. The two tests that differ,agc_driver_graphicsandagc_graphics_profile_draw, both stop on "two ranges under a budget for two were not imported" (the host refusing a memory import under load), which is intermittent on this Mac with or without the change: run alone ten times in the same conditions,agc_driver_graphicspasses 8 times onmainand 9 times with the change, andagc_graphics_profile_draw9 times and 10 times. Every other test has the same status as onmain; the failures are the onesmainhas on macOS (MoltenVK limits and macOS-only gaps of the tests). Both runs report the same 77VUID-errors test by test, andwas not found but was requested by env var VK_INSTANCE_LAYERSappears only in the 12 lines that print the failure regex of theagc_driver_image_table_packed*tests. The logs show the loader inserting the layer (Insert instance layer) in 490 tests.python3 tools/check_conventions.py --base origin/mainpasses.tools/pr_overlap.pylists six open pull requests that change lines this PR changes: fix(agc): load each REWIND control once with acquire in copySegment #17411 (copySegmentloads each REWIND control once with acquire), perf(agc): queue a flip submission before holding the title for earlier flip work #18072 (queues a flip submission before holding the title), fix(agc): a 0xffffffff register offset names no register #16054 (a 0xffffffff register offset names no register), feat(agc): implement PM4 CONTEXT_REG_RMW #16878 (CONTEXT_REG_RMW), fix(agc): run an indirect buffer as it is when execution reaches it #11346 (runs an indirect buffer as it is) and feat(agc): read frame capture deltas with the title's work in flight #15136 (frame capture deltas). None implements the same optimization; whichever merges second rebases over the other. It could not compare eleven more that conflict withmain(for example perf(agc): compile uncached draws ahead of queue 0 #6188, fix: define decoded AGC state and bound size arithmetic #10249, feat(agc): list a capture's shaders and submissions and trace replay serials #11436).No new Windows run on this head.
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)Summary by CodeRabbit