gpu: take GPU timestamps when the host GPU executes them #1282
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!1282
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1282"
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?
@NeySlim on GitHub · 2026-10-09 07:24 UTC · original
NeySlim:fix/gpu-clock-at-execution→main· +1789 −43 · 17 files · 21 commits · openProblem
RELEASE_MEM/EVENT_WRITE_EOPwith the GPU clock (data_sel3) andCOPY_DATAfrom the GPU clock writeSync::ReadReferenceClock()(the host TSC scaled to 100 MHz) into guest memory while the GPU thread parses the packet. The value is the parse time, not the time the GPU finished the work before the packet, so the durations a game measures between two timestamps are the time Kyty spends recording commands.God of War Ragnarök (PPSA08332, 05.005) writes about 1500 of them per second (roughly 150 per frame, 530 slots, rewritten every frame), around its render passes, and reads some of them back on a game thread. Its main passes render at 2688x1512 or 2560x1440 and switch between the two every few seconds (dynamic resolution at its lower steps).
Change
GpuTimestamps, owned byRenderContext. A GPU clock write recordsvkCmdWriteTimestamp2into a query (all commands for end-of-pipe events, top of pipe forCOPY_DATA). Timestamps can be recorded inside a render pass.CommandScheduler::SetBeforeSubmit), the queries of that batch are copied to a host-readable buffer and reset. A priority completion, queued at the first entry of the batch, converts the results and stores them in guest memory, in packet order.TriggerEopEventAtEndOfPipe, and the interrupt of a flip with interrupt): they go throughGpuTimestamps::Signaland run on the GPU thread right after the values before them. A game woken by an interrupt reads the values written before it. Flip completion itself and the suspend-point release are not held: the GPU thread waits for them (flip queue slots), so holding them behind a GPU-thread store could deadlock.RELEASE_MEM/EVENT_WRITE_EOP, flip labels): when a GPU clock value recorded before them is not stored yet, they are stored after it at completion (or on the GPU thread behind it); otherwise they are still written when parsed, as before. A label a game polls therefore never becomes visible before the timestamps written before it. The GDS end-of-pipe path, which already waits for the GPU, first stores the pending values. GPU-side reads recorded after such a label (WAIT_REG_MEM,COND_EXEC,COND_INDIRECT_BUFFER, boolean predication) see it at once, also when they read another width (a 32-bit wait on half of a 64-bit label, a 64-bit compare over a 32-bit one). They saw it at once before this change too, as labels were written when parsed: all guest queues are parsed on one thread and recorded into one host queue, so the order between queues stays as it was, and a queue waiting for another queue's label does not wait for the GPU. Other reads of the label memory (shaders,DMA_DATAorCOPY_DATAfrom memory) see it only once it is stored at completion: those recorded before that read the previous value. A queue suspended onWAIT_REG_MEMfor another value polls again as soon as a completion stores one (GuestGpu::NotifyGuestWrite), instead of after the 100 ms idle wait.WRITE_DATAand other CP writes keep their parse-time behaviour. A CP write to bytes of a label or GPU clock value not stored yet (WRITE_DATA, the destination ofDMA_DATAorCOPY_DATA,DUMP_CONST_RAM,GET_LOD_STATS, occlusion dumps) comes after it: those bytes are dropped from the pending value, so later GPU-side reads see the new write and the completion does not store over it. A shader write to a label address recorded after a deferred label is not ordered this way: the label still lands over it at completion.ReadReferenceClockreturns.VK_KHR_calibrated_timestampsorVK_EXT_calibrated_timestamps, the device clock is sampled against the reference clock every 2 s, through the entry points of the extension the device enabled. The rate is measured from the first sample: the masked tick intervals between samples are summed, so counters with fewer than 64 valid bits wrap without error. A sample more than a quarter of a counter period after the previous one measures again from there. Each new segment starts 1 s after its sample and continues the previous one: a batch submitted before the sample and run within that second converts with the same function as the batches before it, so values stay monotonic across a correction.Test
GpuCommandLane: twoRELEASE_MEMtimestamps recorded while the GPU timeline is blocked must read back times after the GPU is released 20 ms later (on main they hold the parse time and the check fails). The end-of-pipe clock with interrupt and the compute-queue clock interrupt read their values from guest memory after completion.GpuCommandLanealso records 4196 timestamps over 1000 slots in one go (more than the queries in flight): every slot holds the time of its last write, in recording order.ObtainBufferwith a write) must land through the GPU thread and survive the readback; a lone one must land without another GPU clock write.AllocateProgramMemorymemory (no backing alias) must land (exits on the previous version of this PR);memory_tracker_testschecks thatStoreUnwatchedrefuses a range without backing and writes nothing.WAIT_REG_MEM(32 and 64-bit, on half of a 64-bit label and over a 32-bit one),COND_EXEC,COND_INDIRECT_BUFFERand boolean predication packets, and must hold its value after completion; labels with nothing pending are still written at parse time (existing checks).WRITE_DATAafter a deferred label (full and half of a 64-bit one), aDMA_DATAfill after one, and aWRITE_DATAafter a pending timestamp:WAIT_REG_MEMandCOND_EXECsee the new value and memory holds it after completion. Fails without the change (each part checked by reverting it).GpuClockSegments(exact scaling for 100 MHz, 1 GHz and 19.2 MHz counters, continuity across a segment change) andGpuClockCalibration: a simulated 36-bit, 19.2 MHz counter running 50 ppm off its reported period, over 3 hours (three wraps), calibrated every 2 s with one skewed sample, then after a 40 min gap: converted times stay within 1 us, monotonic, with the measured rate; uncalibrated, the same counter followed over 2 hours. Each fails when its part of the change is reverted.shader_recompiler_compute_tests, one case per process: 613 of 623 pass; the 10 others fail on main too on this setup (same list on a clean main build).memory_tracker,page_manager,resource_trackingandresource_materializationpass.Validation
Linux, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3.
Earlier version of this PR (timestamps only, labels written when parsed):
Not tested on Windows or macOS (CI builds them). The change uses core Vulkan queries and
VK_KHR/EXT_calibrated_timestampswhen present;ReadReferenceClockis the existing TSC-based clock on every platform.AI use
I used Claude Code (AI agent) to check how the game uses these timestamps, write the change and the tests, and run the measurements and tests above on my machine. I reviewed the diff and the results before opening this PR.
@coderabbitai[bot] on GitHub · 2026-10-09 07:31 UTC · original · edited 2026-10-21 05:15 UTC
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
807c30aa-34dd-4181-ad43-70e5f6aebac6📥 Commits
Reviewing files that changed from the base of the PR and between da3021014568238fd4585c10febbe6cb7cf26aa6 and db44c099a230c6df7acfa6dd8610572d8f2c9e14.
📒 Files selected for processing (5)
src/graphics/guest_gpu/command_processor/pm4Handlers.cppsrc/graphics/guest_gpu/graphicsRun.cppsrc/graphics/host_gpu/renderer/gpuTimestamps.cppsrc/graphics/host_gpu/renderer/gpuTimestamps.htests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 1 remain after this review.
📝 Walkthrough
📝 Walkthrough
Walkthrough
The change adds calibrated GPU timestamp sampling, conversion, query resolution, and deferred guest-memory storage. Guest GPU timestamp and label paths use the timestamp interface, and pending labels can be read by GPU commands. RenderContext and PageManager provide completion-time stores that reject watched memory and support retries. Vulkan setup selects calibrated-timestamp support when available. Tests cover clock conversion, timestamp ordering, storage, retries, and interrupt sequencing. Command submission can report when the GPU no longer accepts work.
Suggested reviewers:
claxten10Priority: ➖ Normal
Change: Bug fix
Merge Risk: ⚪ Minimal · up to
db44cThe change takes GPU timestamps at the time the GPU executes the commands and keeps the ordering of timestamp, label and interrupt writes. No outstanding merge-blocking issues were found in the supplied context.
Pre-merge checks |
4 |
1
❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 6.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 94 functions across 17 files. (1 skipped: 1 too large.)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share
Comment
@coderabbitai helpto get the list of available commands.@ -0,0 +607,4 @@});stored++;}}@coderabbitai[bot] on GitHub · 2026-10-09 07:31 UTC · original · edited 2026-10-09 07:51 UTC
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Fix
StoreRetriesso it does not drop retried writes to unmapped destinations.Completesetsdeferred = trueafter the first watched store, or when older retries are pending. After that point, every later write in the batch goes tom_retries. This includes destinations whereIsMappedreturns false.RenderContext::StoreAtCompletionwrites those destinations directly withmemcpy.StoreRetriesskips any retry whereIsMappedis false, so the timestamp value for those destinations is never written. A guest that polls that address can then read a stale value or wait forever.To fix this, write every retry in order. Use a plain store for both mapped and unmapped destinations, as in the existing direct path.
🐛 Proposed fix
📝 Committable suggestion
✅ Confirmed as addressed by @NeySlim
@coderabbitai[bot] on GitHub · 2026-10-09 07:31 UTC · original · edited 2026-10-09 07:50 UTC
On
src/graphics/host_gpu/renderer/renderContext.cppline 94 (outdated):🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 27465
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 32684
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 41983
🏁 Script executed:
Repository: KytyPS5/KytyPS5
Length of output: 33812
Synchronize the watcher check with the backing write.
GpuTimestamps::Completeruns onCommandScheduler's priority thread, while texture-cache operations can update watchers directly throughTrackImage.StoreAtCompletionreleases the page lock whenIsWatchedreturns, then callsWriteBacking. A watcher can be added in this gap, leaving the cached image stale.Make the watcher decision and backing write atomic with respect to watcher registration.
✅ Confirmed as addressed by @NeySlim
@coderabbitai[bot] on GitHub · 2026-10-09 07:31 UTC · original · reviewed
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
9694cfb5-5ac9-4383-8f9e-473dbd5eb09d📥 Commits
Reviewing files that changed from the base of the PR and between
7b9997baeaand 690c71713fb06866a198d2497eb70b9f447c429a.📒 Files selected for processing (12)
src/graphics/guest_gpu/graphicsRun.cppsrc/graphics/host_gpu/graphicContext.hsrc/graphics/host_gpu/pageManager.cppsrc/graphics/host_gpu/pageManager.hsrc/graphics/host_gpu/renderer/commandScheduler.cppsrc/graphics/host_gpu/renderer/commandScheduler.hsrc/graphics/host_gpu/renderer/gpuTimestamps.cppsrc/graphics/host_gpu/renderer/gpuTimestamps.hsrc/graphics/host_gpu/renderer/renderContext.cppsrc/graphics/host_gpu/renderer/renderContext.hsrc/graphics/presentation/window/vulkanWindow.cpptests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.
@ -0,0 +607,4 @@});stored++;}}@NeySlim on GitHub · 2026-10-09 07:50 UTC · original
Fixed in 23fb2cf7. StoreRetries now writes every retry in order, mapped or not. The IsMapped check guarded against a retry landing after its range was unmapped, so RenderContext::UnmapMemory now stores the pending retries on the GPU thread before it drops the range. GpuCommandLane covers both: a timestamp to GPU-invisible memory deferred behind a watched one is stored by the next timestamp, and one to a range being unmapped is stored by the unmap.
@NeySlim on GitHub · 2026-10-09 07:50 UTC · original
On
src/graphics/host_gpu/renderer/renderContext.cppline 94 (outdated):Fixed in ebdecd95. PageManager::StoreUnwatched replaces IsWatched plus WriteBacking: it holds the region locks of the pages (at most two, in address order, created if absent) across the watcher check and the backing write, so a registration either completes before the store, and its upload reads the stored bytes, or waits for it. The caches register their watchers before reading guest memory (TrackImage before UploadImage, ForEachUploadRange protects before copying), so this closes the gap. MemoryTrackerTests covers it: a watcher registering during the store is blocked until it lands, and watched pages, including the second page of a crossing store, refuse it.
@coderabbitai[bot] on GitHub · 2026-10-09 07:51 UTC · original
On
src/graphics/host_gpu/renderer/renderContext.cppline 94 (outdated):@NeySlim, thanks for the fix and the explanation. Holding the page-region locks across the watcher check and backing write closes the registration race. The reportedMemoryTrackerTestscoverage also checks registration blocking and refusal when the second page is watched.✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@ -0,0 +607,4 @@});stored++;}}@coderabbitai[bot] on GitHub · 2026-10-09 07:51 UTC · original
🧩 Analysis chain
🏁 Script executed:
Length of output: 8826
🏁 Script executed:
Length of output: 4463
@NeySlim, verified23fb2cf7and the current PR code.StoreRetriesnow writes every retry in order.RenderContext::UnmapMemorydrains retries before removing the range. TheGpuCommandLaneregression tests cover both cases you described. I did not run the tests.Thanks for clarifying the unmap lifetime requirement.
✏️ Learnings added
If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!
✅ Review thread resolved.
You are interacting with an AI system.
@NeySlim on GitHub · 2026-10-09 08:33 UTC · original
Problem: when a completed timestamp targets a page a cache watches, its value is left to the GPU thread, which only stored it at its next GPU clock write (or at an unmap). A game that writes a single timestamp to such a page and then waits for it, with no further timestamp packet, waited until something unrelated happened.
Fix: the completion that defers a value now queues a store on the GPU thread (new
GuestGpu::TrySendCommand, reached throughRenderContext::PostGpuCommand, which tolerates a GPU that is shutting down since completions can outlive it). The GPU thread stores all pending retries, in order, as soon as it is between packets; one queued store covers every retry left until it runs. Writes and unmaps still store them too, so ordering is unchanged: later values wait behind earlier deferred ones, and a drain in progress still defers the completions that overlap it. Interrupts of the same packets are unchanged: they already run after the completion, and a deferred value lands on the GPU thread shortly after rather than at the next clock write.Test:
GpuCommandLanewrites one timestamp to a page with GPU data not read back yet, submits it and records no further GPU clock write; the value must appear within 2 s. Without the fix it never does (checked by reverting the fix alone). ctest memory_tracker and resource_* pass; the GPU suite one case per process gives the same results as before the change.@NeySlim on GitHub · 2026-10-09 11:52 UTC · original
Review fixes pushed (the description is updated):
WAIT_REG_MEM,COND_INDIRECT_BUFFER, predication) use the deferred value at once, as the host queue runs later commands after it. Without that, frame rate in God of War Ragnarök halved.EXIT_IF; one thread stores deferred values at a time.page_manager_testsstubsTryWriteBacking, so it links again.Each change has a test that fails without it. GPU suite one case per process: same failures as main.
@NeySlim on GitHub · 2026-10-09 12:18 UTC · original
Review fixes pushed (the description is updated):
WAIT_REG_MEMon half of a 64-bit label, or the 64-bit compare ofCOND_INDIRECT_BUFFERover a 32-bit label) and read the old memory, so a wait suspended until completion and a branch took the wrong side. Reads now apply every deferred label they overlap, byte by byte, over memory read after the lookup.COND_EXECread guest memory directly and skipped its packets on a deferred label; it now reads it like the other packets.DMA_DATA/COPY_DATAfrom memory) see the label at completion; the description says so.nearclashed with thewindef.hmacro; renamed.Tests:
GpuCommandLanenow goes through the packets (WAIT_REG_MEM32/64-bit across widths,COND_EXEC,COND_INDIRECT_BUFFER, boolean predication) on labels deferred behind a pending timestamp; each check fails when its fix, or theReadLabelcall in its packet, is reverted. memory_tracker, page_manager and resource_* pass; GPU suite one case per process: 595 of 604 pass, the same failures as main.The Linux CI failure (
ResourceMaterializationTests.cpp:246,IndirectDescriptornot default-constructible) comes from main, not from this branch.@NeySlim on GitHub · 2026-10-09 15:04 UTC · original
Rebased on main and fixed the write-after-label ordering:
WRITE_DATA,DMA_DATA/COPY_DATAdestination,DUMP_CONST_RAM,GET_LOD_STATS, occlusion dumps) to bytes of a deferred label or a pending GPU clock value now drops those bytes from it. GPU-side reads after the write (WAIT_REG_MEM,COND_EXEC,COND_INDIRECT_BUFFER, predication) see the new value, and the completion stores only the bytes nothing overwrote, so it no longer replaces the newer value in memory. The completion store and the update hold the same lock, so either order ends with the later write. Labels still need no GPU wait, so the frame rate fix is unchanged.GpuCommandLanecheck through packets:WRITE_DATAafter a 32-bit label, after half of a 64-bit label, aDMA_DATAfill after a label,WRITE_DATAafter a pending timestamp. It fails when the overwrite tracking, the masked read or the masked store is reverted.GPU suite one case per process: same 10 failures as a clean main build (610 cases). memory_tracker, page_manager and resource_* pass.
@NeySlim on GitHub · 2026-10-12 02:09 UTC · original
Rebased on main after
5b730d4d; no behaviour change. The end-of-pipe writes it inlined ingraphicsRun.cppnow carry the change directly: GPU clock values go throughGpuTimestamps::Writeand labels throughWriteLabelinwrite32/write64and the flip paths, and the interrupts ofTriggerEopEventAtEndOfPipeand of a flip with interrupt still run behind the values written before them (GpuTimestamps::Signal). The GDS end-of-pipe path still stores pending values first.memory_tracker, page_manager and resource_* pass;
--gpu-command-lane-onlypasses 10 runs out of 10, and the timestamp, interrupt, label andWAIT_REG_MEMchecks still fail when their part is reverted. GPU suite one case per process: 613 of 623 pass, the same 10 failures as a clean main build.View command line instructions
Manual merge helper
Use this merge commit message when completing the merge manually.
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.