gpu: read back submitted buffer data without a flush #1254
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!1254
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-1254"
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-08 20:26 UTC · original
NeySlim:perf/detached-downloads→main· +542 −42 · 9 files · 1 commits · openProblem
Every synchronous buffer readback (
BufferCache::DownloadBufferMemory<false>) records its copy at the end of the current command buffer, submits it and waits until the GPU has drained everything. Guest CPU faults on GPU-written pages (reads and writes), scalar reads of the resource specialization, indirect dispatch arguments and color metadata all go through it.In God of War Ragnarök (PPSA08332, 05.005) gameplay this happens about 6600 times every 5 seconds, mostly for guest reads and writes that fault one page at a time on buffers a shader wrote earlier. Each one splits the command buffer (about 9500 submissions every 5 seconds) and the GPU command thread is blocked about 1.6 s out of every 5 s, while most of these reads only need data written by work that was already submitted.
Change
CommandScheduler::SubmitDetached: records a small command buffer, submits it to the same queue with its own fence and waits for it. Its leading barrier covers every command submitted before it on the queue, and a queue-submission fence also covers earlier batches, so the copy runs behind all submitted work. The current command buffer stays open (rendering is not ended) and the tick timeline does not advance.BufferCachetracks the guest ranges that unsubmitted work may still write: ranges bound for writing byObtainBuffer, until the draw, dispatch, fill or copy using them is recorded (RecordPendingWrites) and then until the command buffer holding it is submitted; the copy into a new owner when buffers are joined; image data copied into a buffer bySynchronizeBufferFromImage. A recorded shader with address writes, which the cache does not track by range, counts for every range.Test
buffer_cache_detached_download(--buffer-cache-detached-only, also in the default run): data written by a submitted fill is read back while the current command buffer stays open and keeps its tick, and a finished neighbouring page is published with it. A neighbour written by the open command buffer, a page bound for writing but not recorded yet, and a page outside the neighbourhood stay GPU-owned. Reads of data written by the open command buffer, of a joined owner, of image data copied into the owner by a texel read, after a priority operation deferred at the open tick, and after recorded address writes still flush.SchedulerDetachedSubmission(run bycommand_scheduler_timelineand the default run): a detached copy issued behind a submission that waits on an external timeline semaphore only returns after that submission ran, reads its write, and leaves the open command buffer and tick unchanged.Validation
Linux, Ryzen AI Max+ 395, Radeon 8060S, Mesa RADV 26.2.3.
shader_recompiler_compute,gpu_tiler,texture_cache_layered_image,texture_cache_image_views,texture_cache_storage_sampled,texture_cache_image_overlap,texture_cache_htile_clear,buffer_cache_ranges).shader_recompiler_compute_tests, one case per process: same results as main (605 of 615 cases pass with the change, 603 of 613 on main; the same 10 fail on both on this RADV setup).Remaining waits are reads of data written by the command buffer being recorded (draw-indirect arguments read on the CPU, color metadata, some descriptor tables); they still flush.
Not tested on Windows or macOS. The change uses core Vulkan objects (command pool, fence, queue submission) and the existing page tracking, with no platform-specific code.
AI use
I used Claude Code (AI agent) to measure where the GPU thread waits, 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-08 20:29 UTC · original · edited 2026-10-17 14:09 UTC
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
31eaef72-32b9-4376-a810-102d4c8d06d9📥 Commits
Reviewing files that changed from the base of the PR and between 23ba5b448053f1e42990e1ffb18d311b084cbd66 and
d6ff37635a.📒 Files selected for processing: 8
CMakeLists.txtsrc/graphics/host_gpu/renderer/cache/bufferCache.cppsrc/graphics/host_gpu/renderer/cache/bufferCache.hsrc/graphics/host_gpu/renderer/cache/textureCache.cppsrc/graphics/host_gpu/renderer/commandScheduler.cppsrc/graphics/host_gpu/renderer/renderCompute.cppsrc/graphics/host_gpu/renderer/renderDraw.cpptests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.
📝 Walkthrough
The scheduler adds detached Vulkan command submission that waits for its fence without advancing the active command-buffer tick. BufferCache tracks pending and unsubmitted writes, uses that tracking to choose between detached and current-command-buffer readback, and can include eligible nearby dirty pages in small synchronous downloads. New tests cover scheduler ordering, readback behavior, and a dedicated CTest selector.
Suggested reviewers:
nmzikPriority: ➖ Normal
Change: Feature
Merge Risk: ⚪ Minimal · up to
d6ff3The change lets small GPU buffer readbacks complete without flushing the open command buffer whenever no unsubmitted or pending writes could affect the requested data. Otherwise it falls back to the existing flush path. No concrete defect was found in the write tracking, neighbour-page publication, or detached submission, and the change appears ready to merge after normal checks.
Pre-merge checks:
4 ·
1
Full details: Docstring Coverage
Explanation
Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 7 files. (2 skipped: 1 unsupported, 1 too large.)
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
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.@NeySlim on GitHub · 2026-10-10 02:21 UTC · original
Rebased on main after
5559cfcb:SynchronizeBufferFromImagenow uses the newDownloadImage(..., levels), and the image copy is still marked as an unsubmitted write.BufferCacheDetachedDownloadgained a check for that case (a texel read copies a newer image into the owner, then a readback of that range must flush), which fails without the marking. ctest and the GPU suite (one case per process) fail the same tests as main (47/55 vs 46/54, 605/615 vs 603/613). The in-game numbers were not measured again.@Nawid3333 on GitHub · 2026-10-18 23:51 UTC · original
Test result: Demon's Souls (PPSA01341) on Windows with an AMD Radeon RX 6700 XT and a Ryzen 7 5700X, tested by volan3 in #821.
Builds: main
099de8de+ #1152 + #1630, then the same plus this PR, tested as commit b0f8d02c (same patch-id as this PR's headd6ff3763). Performance panel numbers (not a controlled A/B: the tester was asked to use the same place, but that is not confirmed):With this PR the third launch reached gameplay. The second launch stopped before gameplay with
shader resource specialization failed: indirect image table at pc 0x000000fc has incompatible candidatesand the fatalMaterializeResourcescheck. The same message (at pc 0x0000114c) stops Marvel's Wolverine on main (#1453), so I don't think it comes from this PR, but I can't rule out a timing effect yet.I also checked four places where the detached path could miss a write, against the code of that build:
RecordPendingWritesruns after the draw is recorded (drawMeshTasksEXT/EmitDrawPrimitives) and tags the pending ranges with the current tick, so the shader writes get the tick of the command buffer that holds the draw, also when a stream-buffer wrap submits during binding preparation.ObtainBufferis the only place that adds tom_gpu_modified_ranges, and it adds the same range tom_pending_writes; while a range is pending,CanDownloadDetachedrefuses it and the download takes the old flush path.SynchronizeBufferFromImagereturns early unless the image starts inside the buffer and copies tobuffer.Offset(image.info.data.address)(address minus the buffer's CPU address), so the marked range(image.info.data.address, copy_size)is the copy destination.SubmitInfo::AddWait, whose only caller is the swapchain's image-acquired semaphore (swapchain.cpp:877), andEndDetachedsubmits without waits. So no batch ahead of the detached fence waits on a master tick or a guest-signalled value.@Nawid3333 on GitHub · 2026-10-20 20:19 UTC · original
A/B in Demon's Souls (PPSA01341) on Windows 11, RX 9070 XT, Ryzen 7600X: main
0cad4672+ #1630 (to get past #1660) with lab counters, with and without this PR (d6ff3763cherry-picked cleanly). Same scripted input, the character creation menus at 9-11 min, medians of 2-second samples, two runs each, alternating:No hang or device loss in the four 11-minute runs.
What it does not change in this scene: a buffer readback still takes about 2 ms (2.0-2.2 ms without, 2.2-2.5 ms with), and so does a CPU read fault on a GPU-written page (2.2-2.5 ms in both builds). Most of the whole-plan SRT walker's time is spent in those faults (see #1456).
@NeySlim on GitHub · 2026-10-20 20:55 UTC · original
Good to see it on Windows and DeS too. So the next cost there is the ~2 ms per readback itself, and #1456's whole-plan walk just inherits it. I'll look at where those 2 ms go.
@NeySlim on GitHub · 2026-10-21 07:24 UTC · original
Looked into the 2 ms on my side (GoW, RADV). The copy itself is ~6 µs and the fence wakeup ~20 µs; the rest is waiting for the GPU work already submitted ahead of it, since the writer is usually still in flight. So #1254 removes the flushes but can't shorten that. In GoW most of those waits came from tessellated indirect draws that #1288 still kept on the CPU path; moving them to the GPU path removes them (about +5% in the cutscene). If you can, it'd help to know whether in DeS the writer is usually the last submitted batch or older work, that decides whether a separate copy queue would pay off.
@Nawid3333 on GitHub · 2026-10-21 16:39 UTC · original
@NeySlim Measured in the same Demon's Souls scene (main
0cad4672+ #1630 + this PR, lab counters): for each buffer I recorded the tick when it was last bound as written, and at everyBufferCache::ReadMemorycompared it withCurrentTick()andIsFree():So in DeS the writer is almost never the last submitted batch; most readbacks read data whose writer has already finished. Those still take about 1.5-2 ms each, but that time is measured on the calling thread around
SendCommandSync, so it includes handing the readback to the busy GPU thread, and I can't split it into GPU wait and hand-over yet. If that split would help you decide on the copy queue, I can add it.@NeySlim on GitHub · 2026-10-22 07:11 UTC · original
That's the case where a separate copy path pays off: when the writer has finished, a copy on its own queue waits ~80 µs here instead of the whole submitted work. In GoW I tried it and also served those readbacks straight from the guest thread: guest waits halved, but the GPU thread lost more than it saved, because GoW's readbacks mostly hit the last batch. DeS looks like the opposite, so yes, the split (time until the GPU thread picks the readback up vs. the readback itself) would show whether the hand-over or the GPU wait dominates.
@Nawid3333 on GitHub · 2026-10-31 12:29 UTC · original · edited 2026-10-31 12:31 UTC
Demon's Souls (PPSA01341) on Windows 11, RX 9070 XT, Ryzen 5 7600X: main
4919fdb6against main + this PR (d6ff3763cherry-picked; one line adapted to main's rename:stage->runtime->module->info.has_address_writesin renderDraw.cpp). Both builds also carry a lab input-script player that presses the same buttons in every run. Runs from boot without save data.With Tracy on main, a flush before a guest write to a GPU-modified buffer page took 24 ms (1,866 flushes in one capture), a read fault on such a page 15-22 ms. In one of 9 main runs the boot got stuck in these flushes (2,863 in one capture, 21 ms each); none of the 9 runs with this PR got stuck there.
To your question from 10-22, measured with a log around
BufferCache::ReadMemory(hand-over = until the GPU thread starts the readback, readback = the rest, including the GPU wait). Calls that downloaded, among the first 20,000ReadMemorycalls of two runs per build, median / mean in ms, ranges over the two runs:On main the GPU wait dominates. With this PR the median readback drops to about 1 ms or less, but a tail stays (readback p90 28-32 ms in every row, both builds), and for write faults the hand-over is now about as long as the readback (means 5.7-10.3 vs 8.8-9.3 ms, hand-over p90 ~25 ms): the GPU thread is busy, partly with its own readbacks (about 11,700 of the first 20,000 calls in each run). Your neighbour download shows too: on main 3,300 of 15,526 and 3,756 of 19,999 logged read faults hit the page right after the previous fault's page, with this PR none of 19,999.
What the readbacks bring back: the same log compares each downloaded range with the guest bytes it replaces. On main, 43% and 64% of the readbacks (35,500 and 51,000 per run) changed no byte, and of 112 MB and 125 MB downloaded, 10.7 MB and 8.2 MB differed. With this PR 43% and 44% changed no byte, of 1.08 GB and 1.14 GB downloaded (it also takes the neighbouring ranges) 136 MB and 71 MB differed. For example, a page holding 16-byte ranges marked as written is read back 1,535 times, 1,466 of them unchanged; on another page the game reads at +0xed8, next to written ranges that end at +0xed0, and 687 of 710 readbacks are unchanged. Kyty's own GPU thread reading guest memory on such pages takes 41-45% of the read-fault time on main and 63% with this PR, the rest is the game's job worker threads. So in DeS most of these waits are for bytes the GPU did not change:
ObtainBuffer(..., written)marks the whole bound range of a written storage buffer as GPU-modified.Correction to my 10-20 table: its "CPU waiting on the GPU" rows came from a counter in
MasterSemaphore::Wait. This PR's readback waits inEndDetached(waitForFences), which that counter does not see, so those rows understate the PR side. The readback time and frame rate rows are not affected.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.