perf(agc): replace winpthreads locks and TLS on the draw path #6292
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/6292"
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 meh7an on 2026-10-15T09:26:26Z.
What
On Windows the driver is built with MinGW:
std::mutexlocks and unlocks through winpthreads (pthread_mutex_lock,pthread_mutex_unlock);thread_localis emulated: every access calls__emutls_get_address, which callspthread_getspecific.A draw takes a few dozen different mutexes, and every packet reads several thread-locals. On the S2 page of Sonic Origins Plus's main menu, the queue worker spent these samples per frame (APS5 sampler, 15 s):
pthread_mutex_lock1.22,pthread_mutex_unlock0.82,__emutls_get_address2.15 (1.80 of it inpthread_getspecific), and the device use gate 0.37. That is about 10% of its frame.AgcDriver::Mutex(Execution/include/Mutex.hpp) is an inline mutex on one atomic word.std::atomic::wait, which spins 12 pauses and 4 yields itself before it sleeps). Likestd::mutex, it is neither recursive nor fair.std::mutexwith 4 to 8 threads on one lock, and that waiting at once beatsstd::mutexat every thread count. Without the spin, main'sagc_driver_multisample_fill_host_onlyfailed most runs: waiters that sleep at once widen a race main already has (#6512), a multisampled target's clear recorded on another device's recorder. #6522 fixes that race, so this PR depends on it. The game numbers below come from the spinning version; on that page the contended path takes no samples (0.00 per frame in three sampled runs of my fork's dev), so they hold.std::mutexes of the draw path. #1201 already made two more aSlimMutex(the pending storage writes and the unit shadows), and those stay as they are.std::mutex: the five astd::condition_variablewaits with, and the sparse and settle queue mutexes, which the context hands out asstd::mutex*.DeviceUseGatekeeps its user count and the replacement flag in one atomic word instead of a mutex and a condition variable. A packet enters and leaves with one atomic instruction each.GpuMutextakes anAgcDriver::Mutexand counts its own recursion. Its owner token is the thread environment block's address (CurrentThreadToken) instead of a thread-local's.HostThreadSlot(libc/include/HostThreadSlot.hpp) holds a per-thread value of up to 8 bytes.TlsAlloc), read and written through the thread environment block in one or two instructions. Elsewhere it is athread_local.ThreadOwned).Driver::timedreads no clock unlessAPS5_PROFILE_DRAWasks for its report. A wait packet reads it only forAPS5_TRACE_GPU's slow-wait line (suggested by @simonbronk).agc_locks(tests/Locks.cpp, a plain CPU test, so the Windows CI job runs it too) checks:try_lock, and a sleeping waiter's wake;With this change, per frame:
pthread_mutex_lock1.22 to 0.31,pthread_mutex_unlock0.82 to 0.20,__emutls_get_address2.15 to 1.48, and the device use gate 0.37 to 0.05. What remains is the mutexes kept or outside the draw path, and thread-locals this change does not touch.Tested
Windows 11 (10.0.26300), WinLibs GCC 15.2.0 (UCRT), Release, NVIDIA GeForce RTX 2080 Ti, driver 617.14.
53a0a27bb.84e3b73f1made the depth surfaces'surfacesMutexastd::recursive_mutex, and its callers lock it again while they hold it. It stays astd::recursive_mutexand is not switched toAgcDriver::Mutex.AgcDriver::Mutex.agc_driver_image_array_window_past_layer_limitis not run: MinGW does not build itsalignas(65536).guest_kqueueexited with 0xc0000409 once under--parallel 4. It passed 6 of 6 runs alone.1d4164552.IndirectDispatch.cppkeeps main'sGuestBufferMemory.hppinclude, and the buffer pool keeps main's memory property fields, next toAgcDriver::Mutex.Snapshots().mismatched, soGuestBufferMemory.cpponly turnsreportMutexinto anAgcDriver::Mutex.agc_driver_image_array_window_past_layer_limitis not run: main does not compileImageArrayWindowPastLayerLimit.cppwith MinGW (alignas(65536)).agc_driver_pass_input_hazard(added inba4571a25) fails ("a pass writing the indices an open pass reads in place took no barrier") on plain main1d4164552as well, 0 of 4 runs alone.0bc3003f8.AdoptLatestCollectEpochandlastBumpedEpochread the collect epoch through theHostThreadSlot.LockSpinning) inside its recursion guard.dumpRequest's new suffix and the descriptor pool'sfreeDescriptorSetsstay, withAgcDriver::Mutex.AcquireCachetakes theAgcDriver::Mutex.agc_driver_bda_devicefails (vkWaitForFences graphics: Vulkan result -4) on plain main0bc3003f8as well, 0 of 4 runs alone.c84249186. Next todrawCacheMutex, main added the draw relocation fields (#4943), and #5875 keyed the compute pipelines byComputePipelineKeyand dropped the pipeline store'sscratchKey.drawCacheMutex,computePipelinesMutexand the pipeline store's mutex stayAgcDriver::Mutexes, and every lock of them is astd::lock_guardorstd::unique_lockas before. The collect memo ring goes through its thread slot as before. #1201's per-epoch collect map next to it keeps itsthread_local, like the other thread-locals main added since.tools/check_conventions.pypasses:HostThreadSlottakesTlsAllocandTlsSetValuefrom<processthreadsapi.h>, and the GPU mutex's unlock keeps main's comment where it was.agc_driver_gpu_indirect_arguments_misaligned_writer_ahead, which main itself does not compile with MinGW), including the newagc_driver_locks.agc_driver_multisample_fill_host_onlyfailed 0 of 200 runs (8 at a time) on main72c5eed1f. On44df21632it also failed 0 of 400 withAPS5_PIPELINED_DRAWS=0(4 at a time) and 0 of 40 alone, and without #6522's line it failed 40 of 200 and 7 of 40.APS5_TRACE_SECONDS=200:15on the same machine in one session, caches warm. Traces attached.This pair overstates the change. The baseline's window ran slow outside the draw path:
Driver.Packetminus its draw part is 37.0 ms against 11.3 ms with this change. Its title FPS, 6.70, is also below every other run of that build (7.51 to 8.34). The sampled pair, 7.75 to 8.38 FPS (+8%), is the better estimate.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)Traces and summary lines (baseline b8acbb0d6, this change 824084ed7):
locks-traces.zip
The two summary lines, with
tools/trace_digest.pyfor each trace:Baseline (summary commit a38ad5e9fc89)
seconds 200:15 from present 2260: 95 presents, frame p50 156.7 / p90 163.0 / p99 190.3 / max 190.3 ms, GPU busy 78.6 ms per present
NVIDIA GeForce RTX 2080 Ti, NVIDIA 617.14, Windows 10.0.26300, 3840x2160, commit a38ad5e9fc89 (dirty), dropped: yes
Slowest frames (largest slices inside each, inclusive)
Threads (ms per frame)
Largest slices (ms per frame, inclusive, all threads): batch 78.5, Driver.Packet 34.4, Driver.Packet.draw 27.8, Driver.Draw 27.5, Driver.Present 27.0, Driver.Present.render_fence_wait 26.4, Vulkan.Retire 26.4, Vulkan.Retire.wait 26.4, Driver.Draw.draw_and_resource_release 6.1, Graphics.Draw 6.0
Longest waits
This change (summary commit b8acbb0d65c3)
seconds 200:15 from present 2475: 115 presents, frame p50 129.7 / p90 139.3 / p99 153.5 / max 153.5 ms, GPU busy 85.8 ms per present
NVIDIA GeForce RTX 2080 Ti, NVIDIA 617.14, Windows 10.0.26300, 3840x2160, commit b8acbb0d65c3 (dirty), dropped: yes
Slowest frames (largest slices inside each, inclusive)
Threads (ms per frame)
Largest slices (ms per frame, inclusive, all threads): batch 85.7, Driver.Present 32.0, Driver.Present.render_fence_wait 31.4, Vulkan.Retire 31.4, Vulkan.Retire.wait 31.4, Driver.Packet 23.6, Driver.Packet.draw 22.7, Driver.Draw 22.5, Driver.Draw.draw_and_resource_release 4.9, Graphics.Draw 4.8
Longest waits
Imported from boykopovar/AnyPS5. Originally posted by SoRadGaming on 2026-10-15T11:14:59Z.
Windows / AMD results for this head, in a scene where queue worker 0 is the limit: ASTRO BOT (PPSA21564 01.007.000),
-lvl hub_crashsite(the full Crash Site hub).Host: Windows 11 Pro 26200, Ryzen 7 5800X3D, Radeon RX 9070 XT (AMD proprietary driver 32.0.23033.1002), 32 GB, WinLibs GCC 15.2.0 r7, Release.
Builds.
mainc0be1f69b+ #6060 + #6273 + #6188 (draw-ahead) + #6266, plus two local collect-memo changes.Driver.hpp, #6188 adds draw-cache members next todrawCacheMutex. I kept them, withdrawCacheMutexasAgcDriver::Mutex.GuestMemory.cpp, around the collect memo and the epoch check of the 64 KiB widening (#6273). I kept the widening on Windows, with its epoch read throughHostThreadSlot<std::uint64_t, CollectEpochSlot>.Method. No input, warm shader cache (1,904 hits, 0 misses),
APS5_NO_SNAPSHOT_CHECK=1 APS5_RESOURCE_CACHE_ENTRIES=4096, no profiling switches. FPS is the window's present counter over 120 s, after a 120 s settle once the level has started. Runs alternate.Seven launches with this PR went through boot, loading and at least 3 minutes in the hub: the two measured above, and five more held 3 minutes each, at 6.62-6.67 FPS. None had a stop, a hang or an error in the log.
AI-assisted (Claude Code); the builds and runs are on my machine.
Imported from boykopovar/AnyPS5. Originally posted by simonbronk on 2026-10-15T12:40:37Z.
Independent Windows microbenchmark of
AgcDriver::Mutexat head54b0ce01a165784a47031550691fbc385f72f548(AI-assisted).The uncontended improvement reproduces, but I found a contention/CPU tradeoff worth measuring before tuning the spin budget. This does not contradict the title results already posted: it is a saturated synthetic critical section, not a frame workload.
Windows 11 22631, i7-8700 (6 cores / 12 logical CPUs), WinLibs GCC 15.2.0 r7,
-std=c++20 -O3 -DNDEBUG -static -pthread. The exact unchangedExecution/include/Mutex.hppis included directly; the baseline isstd::mutexfrom that compiler. No change to caller sites, TLS orDeviceUseGateis exercised.Five paired batches per thread count, alternating std/PR order on alternate batches; medians below. Each worker increments one protected counter; a simultaneous start gate precedes timing. 1 thread: 1,000,000 acquisitions total. 2/4/8 threads: 400,000 acquisitions total. Wall time includes completion/join; worker cycles are summed
QueryThreadCycleTimedeltas divided by total acquisitions (not wall time).All protected totals were exact: 11 million increments per mutex implementation. Also checked successful free
try_lock, failure oftry_lockwhile a different thread owns the mutex, and a waiter blocked during a 20 ms hold and waking after unlock (2 s completion bound). These are basic probes, not a memory-model proof or starvation test.I then changed only
spin < 100tospin < 0in an external copy of the same header and repeated the five paired batches; a separatespin < 8trial is included too. The no-spin trial gave:The uncontended fast path is retained; on this saturated test, avoiding the explicit spin loop substantially reduces elapsed time and aggregate worker cycles. The experiments ran sequentially, each with its own interleaved std control; they are not a randomized cross-variant title study. Eight spins still cost more than zero in the 4/8-thread cases. This suggests testing a smaller/adaptive spin budget or retaining the old mutex on strongly contended sites, rather than assuming the uncontended result applies to every lock. I am not proposing zero spins as a shipping default without representative title traces.
Attached reproducible probe, unchanged pinned header, both one-constant experimental copies, runners and raw samples. No repo source edit, new PR or push. No GPU/title/FPS/full-build/project-CTest/Linux run, TLS/gate/GpuMutex integration, fairness, long critical-section throughput or oversubscription test. Existing GPU/title results from other contributors are not my validation.
windows-lock-contention-pr6292.zip
Imported from boykopovar/AnyPS5. Originally posted by simonbronk on 2026-10-15T12:52:10Z.
Small clock-gating follow-up for head
54b0ce01a165784a47031550691fbc385f72f548, independent of the mutex contention experiment (AI-assisted).The profiling-gating part still leaves one unconditional clock read in
Driver::execute, in theopcode == 0x3c || opcode == 0x93wait-packet branch.waitStartis consumed only by the followingtraceGpu && ...diagnostic; withAPS5_TRACE_GPUabsent it is never used. This also affects waits already satisfied by the time the worker sees them.Suggested one-line patch in
Execution/src/Driver/Packets/PacketExecution.cpp:The wait call,
gateOpened() = trueand the existingtraceGpu && elapsed > 200 msdiagnostic stay in place. This follows the conditional clock read already used forPacketTimerin this PR.I checked the timing/control region with an external standalone C++ probe, not
Driver::executeor an emulator build. It preserves the start-read/conditional-end-read sequence, calls a synthetic already-satisfied wait through a profiling-disabled wrapper, and records the work and gate side effects. Both functions are kept out of line in the probe. Windows 11 22631, i7-8700, WinLibs GCC 15.2.0 r7,-std=c++20 -O3 -DNDEBUG -static; seven paired batches of one million calls per mode/version, alternating order:The point is avoiding one unnecessary clock read on the default path, not a whole-packet speedup of this magnitude: almost all actual wait/driver work is absent from this probe. Trace-on was slightly slower here, and no trace-on improvement is claimed. All 28 million synthetic calls retained the expected work count and open gate. Four additional 250 ms synthetic waits (both versions, trace off/on) verify the diagnostic predicate stays false with tracing off and true with tracing on.
Attached applicable patch, pinned original file, probe, runner and samples. The runner regenerates the patch against the stated head. No repository source edit, separate PR or push. No full build/CTest, actual waitMemory, packet decoder, GPU, game/FPS or current-main composition validation. The 200 ms test checks only the extracted control logic; it does not check the real diagnostic packet dump. Please run the relevant driver checks before integrating.
wait-packet-clock-gating.zip
Imported from boykopovar/AnyPS5. Originally posted by simonbronk on 2026-10-15T13:40:25Z.
Follow-up on the integration/conventions blockers at head 54b0ce01a165784a47031550691fbc385f72f548: I prepared a candidate against main
a5e2a80c6b.The actual Git merge has one include conflict in DepthSurface.cpp. The candidate keeps the existing GuestMemory.hpp include and adds Mutex.hpp once. It also replaces the two hand-written TLS imports with <processthreadsapi.h> inside the existing Windows x86-64 GNU guard, and removes three prose comment lines in GuestMemory.cpp flagged by the comment policy. The mutex algorithm, spin count and TLS load/store code are unchanged; my earlier waitStart clock patch is separate.
Validation:
The attached bundle includes the three resolved files, checked application helper, exact-revision instructions, probe source, both tested headers and results. This is a local integration candidate, not a push to your branch. Full emulator build, CTest, other platforms, GPU/title execution and FPS were not tested; hosted CI still needs to run after integration. Prepared and reviewed with AI assistance.
pr6292-integration-candidate.zip
Imported from boykopovar/AnyPS5. Originally posted by meh7an on 2026-10-15T16:37:58Z.
Thanks, all. Rebased onto main
92e50418fas adcaa64ad, with these changes:APS5_TRACE_GPU, as you suggested.HostThreadSlottakesTlsAllocandTlsSetValuefrom<processthreadsapi.h>, and the comment this PR added is gone. Rather than deleting main's "Still the holder here" comment, the GPU mutex's unlock movesmutex.unlock()into main'sif (outermost)block, so that comment stays as it was.tools/check_conventions.pypasses.On the spin, I tried dropping it (
lockContendedgoing straight toexchange(Contended)and the wait, which spins 12 pauses and 4 yields itself in libstdc++ before it sleeps). It madeagc_driver_multisample_fill_host_onlyfail most runs. Runs one at a time, 40 each:APS5_PIPELINED_DRAWSon92e50418fEach failure is the test's "the sentinel fill did not land": the fill is not in guest memory yet when
WaitIdlereturns. Main already has this race, and pipelined draws mostly hide it. Waiters that sleep at once widen its window. So the spin stays in this PR. Dropping it can follow once that race is fixed, with your benchmark as the reason. On the page I measure, the contended path takes no samples (0.00 per frame in three sampled runs today), so the PR's numbers do not depend on the spin either way.Imported from boykopovar/AnyPS5. Originally posted by meh7an on 2026-10-15T19:18:05Z.
@simonbronk, the spin is gone now (091a0cc82, rebased onto main
44df21632): a contended lock waits on the word at once.The race it was hiding turned out to be main's, #6512. In
agc_driver_multisample_fill_host_only,recordCommandsinMultisampleTarget.cpprecorded a multisampled target's barrier and clear into the active recorder, which belongs to anotherVkDevicethan the target's image. The validation layer reports it (VUID-vkCmdClearColorImage-commonparent), and the next batch's fill was lost now and then. #6522 fixes that, so this PR now depends on it.On main
44df21632with #6522 and this PR without the spin, runs of that test:APS5_PIPELINED_DRAWS=0, 4 at a timeThe full suite passes 1299 of 1300 there; the one not run is
agc_driver_gpu_indirect_arguments_misaligned_writer_ahead, which main itself does not compile with MinGW.Imported from boykopovar/AnyPS5. Originally posted by simonbronk on 2026-10-15T19:48:24Z.
@meh7an thanks for the update. Here is a title measurement of 091a0cc82 on Windows. It's inconclusive for this scene.
Onimusha: Way of the Sword (PPSA27836), Windows 11 26200, RTX 5070 (NVIDIA 617.42), WinLibs GCC 15.2, Release. Base:
main44df21632plus the title's PRs (#5907 #5841 #5884 #5915). Test: the same tree plus #6522 (09f574989) and this PR. Scene: boot to the language menu, no input, warm shader cache,APS5_TRACE_SECONDS=60:30. Runs alternated base, PR, PR, base, base, PR.munmapbursts that wait for GPU work). Those stalls land in or out of the 30 s window by chance, so I wouldn't read them as a regression of this PR.[resources]images and stage B phases) and to waits, not to lock or TLS overhead. So a 2% effect is about what I'd expect. No functional difference: both builds reach the same screens.AI-assisted: Claude Code.
Imported from boykopovar/AnyPS5. Originally posted by moong15 on 2026-10-19T13:16:54Z.
Evidence from Stellar Blade on Windows (MinGW build): I measured this change as part of #6615's stack, which includes it. Ported onto a downstream perf branch on origin/main
4ffb0cd12(RX 9070 XT, 4K, warm cache, two base/port pairs, 49-150 s of gameplay, whole traces), the stack gave +4.5% and +9.5% presents (about +7%). p50 dropped 9-13% and p99 16-22%. Peak commit was 0.75-1.2 GB higher. I couldn't isolate #6292 on its own. Full table and trace_digest output: https://github.com/boykopovar/AnyPS5/pull/6615#issuecomment-6268138557.Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-20T12:59:23Z.
Thanks. The mutex, the use gate, the GPU mutex's recursion and the TEB slot reads all check out. The offsets match the x64 TEB layout, and a small harness built from
HostThreadSlot.hppkept per-thread values isolated in both a direct slot and an expansion slot (index 74) across three threads, matchingTlsGetValuethroughout.One ask, about where the new test lives.
tests/execution/Locks.cppis picked up by the execution-test glob, and the Windows CI job configuresANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown. Every other execution test, including this one, is built fromExecutionTestNotBuilt.cppthere and reports a skip. Linux CI does run it, but on LinuxHostThreadSlotis a plainthread_local. So no CI job runs the TEB code this PR adds. The test doesn't need Vulkan, so could you register it as a plain CPU test outsidetests/execution(likeagc_lds_lock_budget), so it runs on the Windows job too?Imported from boykopovar/AnyPS5. Originally posted by meh7an on 2026-10-20T13:43:48Z.
Thanks, and thanks for checking the slots against
TlsGetValuewith a harness.tests/Locks.cpp, a plain CPU test namedagc_locks, registered likeagc_shared_write.libSceAgcDriverandlibcand needs no Vulkan device, only the headers.ExecutionTestNotBuilt.cppskip.HostThreadSlotas a plainthread_local.1d4164552it passes on Windows, where the slots read the TEB.Imported from boykopovar/AnyPS5. Originally posted by CnRJay on 2026-10-21T17:54:00Z.
Review: COMMENTED
The profile is a convincing reason (
pthread_mutex_lock/unlock,__emutls_get_addressand the device use gate are about 10% of the queue worker's frame on Sonic Origins Plus), the first spinning version was caught and fixed on @simonbronk's contention benchmark, and the frame effect is measured on two machines (7.75 to 8.38 fps title reading on the 2080 Ti; SoRadGaming's Astro Bot Crash Site on a Radeon). The risk is in what it replaces.std::mutexes for a hand-written, non-fair, non-recursive mutex built onstd::atomic::wait. The description's own account is that waiters that sleep at once widened a race main already has (agc_driver_multisample_fill_host_onlyfailing most runs, #6512), which #6522 fixes. So this PR changes scheduling enough to expose latent races, and the safe merge order is #6522 first. State that in the dependency list and keep the test running in a loop in CI (--repeat until-fail), since the next latent race will show up in the same way and in some other test.std::mutex; add the case that matters here, the GPU mutex held across a long operation by the queue worker while the packet worker and a loader thread wait, with the hold time of a real submit, and report the waiters' wake latency.HostThreadSloton Windows is aTlsAllocslot read through the TEB. Say what happens if the slots are exhausted orTlsAllocfails (it should throw at startup), and that a slot is released at shutdown.GpuMutex's owner token is the TEB address. If a thread could exit while holding it, a later thread that is given the same TEB address would appear to own the lock. A one-line statement that no thread can exit while holding the GPU mutex (or a test) would settle it.mainrepeatedly (the description lists five rebases). The conflicts show the risk: every change to a draw-path mutex now needs the new type. A staged landing would help: theHostThreadSlotandDriver::timedchanges (no behavior change on contention) first, the mutex replacement second.