graphics: release idle images when a new image cannot be allocated #2551
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!2551
Loading…
Reference in a new issue
No description provided.
Delete branch "github-bot/gh-2551"
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?
@Nawid3333 on GitHub · 2026-11-25 19:02 UTC · original
Nawid3333:fix/image-create-memory-pressure→main· +237 −26 · 5 files · 4 commits · openCause
When
CreateImage(vmaCreateImage) fails,Image::Imagestops the emulator withfailed to create image: extent=... format=...(image.cpp), although the texture cache still holds images the current frame does not use. Idle images are only freed by the texture GC, which runs once per guest suspend point, deletes at most 10, 20 or 40 images per pass and only images idle for 16, 80 or 160 GC ticks (by memory pressure). During a loading burst it frees nothing in time.Logs attached here stop this way with a VMA heap at or near its budget: 007 First Light (#1989), Until Dawn (#2388) and Avatar: Frontiers of Pandora (#2331); TxF-AI reports the same stop in UFC 6 (#2019). Assassin's Creed Valhalla stops with the same message (comment). TxF-AI measured it on UFC 6 (#2019): at the stop about 990 to 1,345 images hold 8.8 to 10.4 GB, and 78 to 95 % of the image bytes were touched in the last 16 GC ticks.
Change
Image::Imagereturns without a backing whenCreateImagefails, instead of stopping. The body of~Imagemoves toImage::ReleaseBacking().TextureCache::InsertImage: while the new image has a format but no backing, it erases the slot, callsReleaseIdleImagesand tries again. When nothing can be released (also before the first GC pass) it stops with the samefailed to create imagemessage text as before, now fromInsertImage.ReleaseIdleImages(requested)goes through the LRU list from the oldest image and releases images not used in the current GC tick until their size reaches the requested size. It skips what the GC skips (unregistered images, stencil associations, heap-referenced images). An image whose newest data is a GPU write, with no later CPU or buffer write to its memory (SafeToDownload), is downloaded to guest memory first, as the GC does under memory pressure, and kept if it holds stencil or the download fails. It also keeps bound, target and video-out images, images accessed since the last guest suspend point and images that overlap the requested range. It frees the released images, waits once for the GPU (m_scheduler.Waiton the current tick, the submit-and-wait path a stream buffer wrap also takes while a draw is prepared) and destroys their backing.ResolveCache::Reusemarks a reused image as accessed throughtick_accessed_lastwithout moving it in the LRU list, so such an image is kept too.ReleaseIdleImagesalso waits for the priority operations of that tick (WaitPriorityOperations), asBufferCache::RunGarbageCollectordoes before it releases downloaded buffers. A released image's download reaches guest memory in such an operation; without the wait, its range could be found again and uploaded from guest memory before the data landed (found by CodeRabbit).RefreshImagedoes (TrackImage, thenResolveMaybeCpuHash(HashGuestEdges())) before the download check; before,SafeToDownloadcounted it as dirty and the image was released without its GPU write (found by CodeRabbit). The texture GC uses the same check and is unchanged.#1271 had the same idea (evict and retry in
InsertImage); it was closed with the comment "This is a hack and uses RAM as fallback (performance will be low)". #1961 (open, a Call of Duty Vanguard bring-up) contains a similar evict-and-retry among its other changes. This change keeps the GC's rules for what must not be lost (an image whose newest data is a GPU write is downloaded first; stencil holders and heap-referenced images stay), but not its minimum age or per-pass cap, and runs only where an allocation fails; it does not change where VMA places images (AUTO_PREFER_DEVICE, unchanged). Differences in the code: no second evictor with its own 256 MiB eviction target and 32 MiB download budget, nokeepparameter threaded through the callers (images overlapping the request are kept instead), and noCommandScheduler::Finish()before the retry. When the images a game needs do not fit, they are created and uploaded again (slower), where the build before stopped.Test
shader_recompiler_compute_tests --image-allocation-pressure-only(newImageAllocationPressure): a second runtime context gets a VMA allocator whose heaps are limited (pHeapSizeLimit) to what the harness allocator already uses plus 256 MiB, fills them, creates a GPU-written 8 MiB image, advances one frame and asks for a second image.93cce6656) with the test: exit 65,failed to create image: extent=1024x2048x1 format=37 layers=1 levels=1ImageAllocationPressure ok; the test also checks that the fill left no room for the new image, that the released image's GPU write is in guest memory as soon as the new image exists (a slow priority operation queued ahead of the download keeps it waiting), and that a small GPU-written image left maybe CPU-dirty by a write next to it is released with its GPU write.an image was released before its GPU write reached guest memory(5 of 5).a maybe-dirty image was released without its GPU write(5 of 5).The other texture-cache selectors (
--htile-clear-only,--image-overlap-only,--image-upload-only,--dcc-clear-only,--host-image-allocation-only,--image-view-cache-only,--depth-readback-only,--image-rebind-only,--storage-mip-host-only,--layered-image-only,--image-transition-only,--video-out-only,--descriptor-heap-only,--compute-meta-clear-only,--standard-tile-rt-only) give the same exit codes and last lines on main and with the change. Seven of them fail on both on this PC:image format does not support required usage(image.cpp), an unhandled host exception (runtimeLinker.cpp) andRenderExecutorStencilBindingDiscovery.(Windows 11, RX 9070 XT, clang-cl. Local runs of
shader_recompiler_compute_testshere need #2038's harness change, applied for the build only.)Fork CI on this commit: run 45694520901: the Windows job (32 of 32 tests) and the Linux job (16 of 16) pass; the macOS job was cancelled before its first step. CI does not run
shader_recompiler_compute_tests.In a game
With tester builds that add a log line when images are released (not part of this PR):
usage = budget, and nofailed to create image; the same setup without the change stopped on it early in loading (comment). The run later stopped at a pipeline creation failure (shaders.cpp:417), a separate problem. A second run, with a build that also logs the pipeline creation result, had 33 releases and nofailed to create image; it stopped at a device loss (createGraphicsPipelines failed: ErrorDeviceLost), also separate (comment).streamBuffer.cpp), which this change does not cover.Loading time with the change was not measured.
Refs #2019
Refs #2308
Written with Claude Code (AI): Claude Code wrote the change and the test and ran them; DeepSeek reviewed the diff.
🤖 Generated with Claude Code
@coderabbitai[bot] on GitHub · 2026-11-25 19:08 UTC · original · edited 2026-11-25 20:28 UTC
No actionable comments were generated in the recent review.
Walkthrough
When image creation fails without backing,
TextureCacheremoves the failed slot, releases eligible idle image backing, and retries.Imagenow exposes backing release and returns from construction when image creation fails. The Vulkan test suite adds an allocation-pressure check and supports running it separately.Suggested reviewers:
nmzik,thecruzChange: Bug fix
Merge Risk:
Minimal · up to
9e27dWhen an image allocation fails, the texture cache now frees idle images and retries before stopping the emulator. GPU-written contents are saved to guest memory first, and in-use images are protected. Nothing concrete remains to fix before merge. The new pressure test is not run by CI, so the author's reported local run is the only check of this path.
Pre-merge checks:
4
Full details: Title check
Explanation
The title names the main change: idle images are released when a new image allocation fails. The change matches this. The changeset adds ReleaseIdleImages, retries in InsertImage, and changes Image construction on CreateImage failure. The title is specific and concise, and it does not use vague terms.
Full details: Description check
Explanation
The description is detailed and on-topic. It explains the cause (CreateImage failure stops the emulator while idle images remain), the change (Image::Image returns without backing, ReleaseBacking, InsertImage retry, ReleaseIdleImages with GC-like protections, ResolveCache::Reuse accessed marking), and the test (ImageAllocationPressure). It matches the raw summary and the objectives.
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
f277efe9-9cc0-4592-b37b-48263a621dbcReviewing files that changed from the base of the PR and between
e2c82ade02and9e27d264d9.src/graphics/host_gpu/renderer/cache/textureCache.cpptests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
@coderabbitai[bot] on GitHub · 2026-11-25 19:08 UTC · original · reviewed
Actionable comments posted: 1
cd1a7a1b-ed77-4d3a-bc17-e51bbb6acc79Reviewing files that changed from the base of the PR and between
93cce66564and3bde87d248.src/graphics/host_gpu/renderer/cache/textureCache.cppsrc/graphics/host_gpu/renderer/cache/textureCache.hsrc/graphics/host_gpu/renderer/image/image.cppsrc/graphics/host_gpu/renderer/image/image.htests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@ -213,0 +245,4 @@TrackImage(id);image->ResolveMaybeCpuHash(image->HashGuestEdges());}if (image->SafeToDownload() && (image->info.HasStencil() || !DownloadImageMemory(id))) {@coderabbitai[bot] on GitHub · 2026-11-25 19:08 UTC · original · edited 2026-11-25 19:39 UTC
Protect a depth owner while one of its stencil associations is in use.
ReleaseIdleImageschecks only the depth owner'stick_accessed_last, heap references, and binding state. A stencil association thatFindImageselected in the current frame does not update its owner's LRU entry ortick_accessed_last. A later allocation failure in the same draw can therefore callReleaseIdleImages, which can select that owner.FreeImagethen frees each association, so the draw can hold an association ID for an image that no longer exists.The owner's heap references already protect resident heap bindings, because texture bindings resolve to the owner. The gap applies only to association use in the current frame. Make the recovery guard reject an owner while any of its
stencil_idshastick_accessed_last == m_gc_tick, or otherwise propagate association access to the owner. Confirm the chosen rule against the draw path that holds association IDs before merging.✅ Addressed in commit e315b61
@ -213,0 +245,4 @@TrackImage(id);image->ResolveMaybeCpuHash(image->HashGuestEdges());}if (image->SafeToDownload() && (image->info.HasStencil() || !DownloadImageMemory(id))) {@Nawid3333 on GitHub · 2026-11-25 19:31 UTC · original
Fixed in e315b619d:
ReleaseIdleImagesnow skips a depth image while any of its stencil associations was accessed in the current GC tick (tick_accessed_last == m_gc_tick).ImageAllocationPressurenow also creates an older depth image with a stencil association, marks the association accessed in the current tick before the failing allocation, and checks that both are still registered afterwards; without the change it fails witha depth image was released while its stencil association was in use.@coderabbitai[bot] on GitHub · 2026-11-25 19:36 UTC · original · edited 2026-11-25 20:09 UTC
On
src/graphics/host_gpu/renderer/cache/textureCache.cppline 257 (outdated):Wait for priority publications before releasing an image.
ReleaseIdleImageswaits only for the GPU tick. A GPU-written image that it releases can still have a deferred guest publication pending in the priority queue. Priority callbacks run asynchronously after that wait returns. A later reload of the same range can then upload the old guest bytes instead of the GPU-written data. Wait for the priority operations of the same tick before the released backings are destroyed.Suggested fix
✅ Confirmed as addressed by @Nawid3333
@coderabbitai[bot] on GitHub · 2026-11-25 19:36 UTC · original · reviewed
Actionable comments posted: 1
486d3e78-9729-4457-9a00-bdd463f51036Reviewing files that changed from the base of the PR and between
3bde87d248and e315b619dabe4e500ce9d7ccdc4d3edf67697750.src/graphics/host_gpu/renderer/cache/textureCache.cpptests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
@ -213,0 +245,4 @@TrackImage(id);image->ResolveMaybeCpuHash(image->HashGuestEdges());}if (image->SafeToDownload() && (image->info.HasStencil() || !DownloadImageMemory(id))) {@coderabbitai[bot] on GitHub · 2026-11-25 19:41 UTC · original
Analysis chain
Script executed:
Length of output: 9055
Script executed:
Length of output: 31866
Script executed:
Length of output: 11466
Script executed:
Length of output: 27506
Script executed:
Length of output: 3003
@Nawid3333Thanks for the guard and test. I need to correct my original finding.ResolveTexturereplaces the stencil association ID with the depth owner.PrepareBindingsthen binds the owner before it discovers the next image.ReleaseIdleImagesalready skips bound images. The image-heap path also pins the owner.The test checks the new guard directly, but the draw path does not retain the association ID as I claimed. I withdraw the finding.
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.
@Nawid3333 on GitHub · 2026-11-25 20:07 UTC · original
On
src/graphics/host_gpu/renderer/cache/textureCache.cppline 257 (outdated):Fixed in
e2c82ade0: afterm_scheduler.Wait(tick),ReleaseIdleImagesnow also callsm_scheduler.WaitPriorityOperations(tick)before it destroys the backings, asBufferCache::RunGarbageCollectordoes. The pressure test now queues a 200 ms priority operation ahead of the download and reads guest memory right after the new image is created. Without the wait it fails withan image was released before its GPU write reached guest memory(5 of 5 runs); with the wait it passes (5 of 5).@ -213,0 +245,4 @@TrackImage(id);image->ResolveMaybeCpuHash(image->HashGuestEdges());}if (image->SafeToDownload() && (image->info.HasStencil() || !DownloadImageMemory(id))) {@coderabbitai[bot] on GitHub · 2026-11-25 20:08 UTC · original · edited 2026-11-25 20:35 UTC
Resolve maybe-CPU-dirty state before the download check during allocation recovery.
SafeToDownload()returns false whenIsCpuDirty()is true, and that includes the maybe-dirty state. A CPU write that touches the tracker page of a GPU-written image, but not the image itself, sets this state (textureCache.cpp:2104-2112). InReleaseIdleImages, such an image fails the check at line 244. The download is skipped, andFreeImagediscards the GPU-written contents. The guest bytes are then stale. A later recreation can upload those stale bytes.This CPU write does not overlap the image. The guest-edge hash can therefore match the stored hash, which means the image is not CPU-dirty and can be downloaded safely.
Before the eligibility check, resolve the maybe-CPU state for each GPU-modified candidate. After resolution, download the image when it is safe to download. Keep the existing skip for images that remain CPU-dirty, and keep the existing retain-on-failure behavior.
✅ Addressed in commit
9e27d26@ -2395,0 +2454,4 @@const VkMemoryRequirements requirements{free - margin, 1, 1u << type};const VmaAllocationCreateInfo create{.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT};if (VmaAllocation filler{}; vmaAllocateMemory(graphics.allocator, &requirements, &create,&filler, nullptr) == VK_SUCCESS) {@coderabbitai[bot] on GitHub · 2026-11-25 20:08 UTC · original · edited 2026-11-25 20:34 UTC
Report missing allocation pressure instead of a failed eviction.
The fill helper ignores a failed dedicated allocation. At lines 2453-2456, the filler is kept only on
VK_SUCCESS, and a failure continues the loop without an error. If both dedicated fills fail, the replacement image can fit in the remaining headroom. The test then creates it without eviction and reports "the new image did not take the memory of the idle one." That message blames eviction for a state where pressure was never created.A device can reject the dedicated allocation. The Vulkan maximum allocation size is implementation-defined, and the physical heap can have less free memory than the synthetic limit at line 2412 reports.
The test must check this precondition. If the fill does not establish the pressure that the eviction check needs, it must report that pressure was not established, not a failed eviction. Choose the mechanism in the test design.
✅ Addressed in commit
9e27d26@coderabbitai[bot] on GitHub · 2026-11-25 20:08 UTC · original · reviewed
Actionable comments posted: 2
bd923a70-be1b-41d6-af3a-5c11a11f1450Reviewing files that changed from the base of the PR and between e315b619dabe4e500ce9d7ccdc4d3edf67697750 and
e2c82ade02.src/graphics/host_gpu/renderer/cache/textureCache.cpptests/ShaderRecompilerComputeTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
@ -213,0 +245,4 @@TrackImage(id);image->ResolveMaybeCpuHash(image->HashGuestEdges());}if (image->SafeToDownload() && (image->info.HasStencil() || !DownloadImageMemory(id))) {@Nawid3333 on GitHub · 2026-11-25 20:08 UTC · original
Agreed.
ResolveTexturereplaces a stencil association with its depth owner (descriptors.cpp:646-649), and the owner is bound at :750 and :874 before the next texture is looked up. The depth target paths bind their image right after the lookup (depthRenderTarget.cpp:314, :340 and :342; descriptors.cpp:935).ReleaseIdleImagesskips bound and target images, so I dropped e315b619d again. The branch is now3bde87d24pluse2c82ade0.@ -213,0 +245,4 @@TrackImage(id);image->ResolveMaybeCpuHash(image->HashGuestEdges());}if (image->SafeToDownload() && (image->info.HasStencil() || !DownloadImageMemory(id))) {@coderabbitai[bot] on GitHub · 2026-11-25 20:09 UTC · original
@Nawid3333 Thanks for confirming.
Review thread resolved.
You are interacting with an AI system.
@ -2395,0 +2454,4 @@const VkMemoryRequirements requirements{free - margin, 1, 1u << type};const VmaAllocationCreateInfo create{.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT};if (VmaAllocation filler{}; vmaAllocateMemory(graphics.allocator, &requirements, &create,&filler, nullptr) == VK_SUCCESS) {@Nawid3333 on GitHub · 2026-11-25 20:33 UTC · original
Fixed in
9e27d264d: after the fill, the test checks that no heap the image can use (itsmemoryTypeBits) has room left for an image of its size, and otherwise fails withthe fill left room for another image, so the test cannot check a release. With the fill margin raised to four image sizes it fails there; with the normal fill it passes.@ -213,0 +245,4 @@TrackImage(id);image->ResolveMaybeCpuHash(image->HashGuestEdges());}if (image->SafeToDownload() && (image->info.HasStencil() || !DownloadImageMemory(id))) {@Nawid3333 on GitHub · 2026-11-25 20:35 UTC · original
Fixed in
9e27d264d: before the download check,ReleaseIdleImagesnow resolves a GPU-written candidate that is maybe CPU-dirty the wayRefreshImagedoes (TrackImage, thenResolveMaybeCpuHash(HashGuestEdges())), so an image whose own bytes the CPU write did not change is downloaded before it is released. The pressure test adds a small GPU-written image that a CPU write next to it on the same tracker page leaves maybe-dirty. Without the change it fails witha maybe-dirty image was released without its GPU write(5 of 5 runs); with it, it passes (5 of 5). The texture GC (RunGarbageCollector) uses the sameSafeToDownloadcheck and is unchanged here.View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.Merge
Merge the changes and update on Forgejo.