shader: route oversized read-only raw buffers through direct addressing #978
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!978
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/978/head"
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?
@MehmetCambaz on GitHub · 2026-10-02 15:32 UTC · original
MehmetCambaz:fix/direct-bda-oversized-raw-loads→main· +680 −18 · 9 files · 1 commits · closed without mergingSummary
Kyty exits when a shader binds a raw buffer descriptor whose range does not fit in one Vulkan storage-buffer view. The usual trigger is the RDNA2 maximal-range idiom, a constant
NUM_RECORDS = -1(0xFFFFFFFF). With aSTRIDEof 2 or more over a guest mapping of 4 GiB or more,NativeStorageBufferstops withstorage buffer range is unsupported.This PR reads a buffer resource through the BDA page table instead of a storage view when its
NUM_RECORDSis a compile-time constant above0x7FFFFFFFand every access through it is a raw load.OOB_SELECTbounds,ADD_TID), reusing the code of GPU-selected descriptor loads.The PR also fixes the BDA page lookup. Today
get_bda_pointermaps some addresses outside both guest memory regions onto other pages' page-table entries, so such an address can read another page's data. This also affects existing GLOBAL/FLAT and GPU-selected loads.The change is deliberately read-only. A resource with any store, atomic, formatted or typed access keeps its storage view and today's behavior. Writable direct windows need GPU write reporting first.
Current-main rebase
This branch has been rebased onto current
upstream/mainatdc3cd2d2c9d537156894871a91ff22b30ec3a1a8. The implementation was reconciled with the current GPU-selected descriptor, indirect scalar-buffer, and native 64-bit addressing infrastructure. No code from open PRs #931 or #976 was incorporated.Problem
For the storage-view path,
RenderExecutor::FindBufferssizes a buffer withShaderBufferResource::GetSize():NUM_RECORDSbytes whenSTRIDEis 0;STRIDE × NUM_RECORDSbytes otherwise.It then clamps that size to the contiguous guest mapping at the base (
ClampRangeSize).NativeStorageBufferbinds the result as one view and exits if it exceedsmaxStorageBufferRange.NUM_RECORDS = 0xFFFFFFFF0xFFFFFFFFbytes atSTRIDE0 or 1; about 16 GiB atSTRIDE4maxStorageBufferRangeuint32_t, so at most0xFFFFFFFF; Vulkan only requires 2^27For a
NUM_RECORDS = -1descriptor with aSTRIDEof 2 or more, any mapping of 4 GiB or more gives a clamped range of at least 2^32 bytes. No device can bind that, even though a shader can address at most 2^32 bytes of it. Devices that report a smaller limit exit the same way with smaller mappings.0x80000000is the smallestNUM_RECORDSat which aSTRIDEof 2 declares 2^32 bytes. The stride usually isn't known at compile time, because dword 1 also carries the base address.An observation from the test system (RTX 4070, driver 610.47), which reports
maxStorageBufferRange = 0xFFFFFFFF: compute-shader stores through views of 2 GiB or more were silently dropped, with no validation message, while the same stores through views of up to0x7FFFFFFFbytes landed. The fix does not depend on this.Root cause
Oversized raw descriptors. Resource tracking gives every host-trackable buffer V# a storage view, whatever its declared range. Only V#s whose dwords are not host-trackable, the GPU-selected
ResourceKind::IndirectBuffercase, are evaluated in the shader and read through the BDA page table. A constant maximal-range descriptor is host-trackable, so it always gets a view, and that view's size is exactly what does not fit.BDA lookup of non-guest addresses. Guest memory is two regions, and
GuestRange::Validaccepts only ranges inside one of them:[0, LOWER_ADDRESS_SIZE), which is 1 TiB;[kExtendedMemoryBase, kExtendedMemoryBase + kExtendedMemorySize), which runs from 8 TiB to 8.5 TiB.The BDA page table is dense over both, in 16 KiB pages: the first 2^26 entries cover the lower address space and the next 2^25 cover extended memory.
get_bda_pointer(DefineGetBdaPointer) rebases only addresses at or abovekExtendedMemoryBase, truncates the page index to 32 bits, and never checks that the address is guest memory. As a result:[LOWER_ADDRESS_SIZE, kExtendedMemoryBase)is not rebased.LOWER_ADDRESS_SIZE + xindexes the entry ofkExtendedMemoryBase + xforx< 512 GiB, and runs past the end of the table beyond that.2^46 + (kExtendedMemoryBase − LOWER_ADDRESS_SIZE) + yindexes the lower-space page ofy.If the aliased page is cached, the load returns its data. If not, the lookup records a page fault for the aliased page, and the host caches that unrelated page. GLOBAL/FLAT loads, GPU-selected buffer loads and BVH node reads all use this lookup.
Implementation
Resource routing (
ResourceTracking)AllowsDirectAddressingmarks a buffer access eligible when all of the following hold:NUM_RECORDSoperand resolves to an immediate aboveMaxStorageViewRecords(0x7FFFFFFF);BUFFER_LOAD_*orS_BUFFER_LOAD);ResolveDirectAddressingruns after collection. It marks a resource direct only if every access through it is eligible, settingMemoryInfo::direct_address,BufferResource::direct_addressand the program'suses_dma. A resource is therefore either entirely view-bound or entirely direct.CompileProgramkeeps the V# operands of direct handles, as it already does for GPU-selected handles. Other bound handles still have their operands zeroed.Host binding (
descriptors.cpp)FindBuffersbounds every buffer range to 2^32 bytes, the most a 32-bit offset can reach. View-bound resources are unaffected, because a range that large already exits.For a direct resource,
NativeStorageBufferobtains the window from the buffer cache without the written flag and binds the null buffer. The window's pages are registered in the BDA page table, and its CPU-dirty pages are uploaded, before the dispatch. Nothing is marked GPU-modified and no image is invalidated, as for a read-only view of the same range. The reads need no new barriers: the global memory barriers the renderer already places around dispatches cover BDA accesses.Shader-side addressing (
spirvEmitterMemory.cpp)V# evaluation.
DescriptorComponentsis the V# evaluationLoadIndirectBufferused to do inline: base,STRIDE, swizzle, index stride,ADD_TID,SOFFSET, and the bounds of eachOOB_SELECTmode. It now takes the access width, so byte and 16-bit accesses are bounds-checked at their own size.LoadIndirectBufferpasses 4 bytes and is otherwise unchanged.Vector loads.
EmitLoadMemorysends direct accesses toDirectLoad, which handles byte, 16-bit, dword and dword x2–x4 loads:LoadBda, including a 16-bit load that spans two dwords;MemoryInfo::coherent) are emitted asVolatile.Scalar loads.
EmitReadConstBuffersends directS_BUFFER_LOADs toDirectScalarLoad, which reads the dword the ScalarBuffer view would. Base and offset have their two low bits ignored, and the dword must lie within(STRIDE == 0 ? 1 : STRIDE) × NUM_RECORDSbytes.Safeguards:
PrepareMemoryResourceAccessexits if a direct access ever reaches the view path;AnalyzeProgramRequirementsenables the subgroup invocation id thatADD_TIDneeds.BDA address validation (
DefineGetBdaPointer)get_bda_pointernow decides whether the address lies in the lower address space or in extended memory, the same windowsGuestRange::Validaccepts, before using its page index.Why only loads
The view path takes ownership of a written resource coarsely:
ObtainBufferwith the written flag adds the whole bound range to the GPU-modified ranges, andNativeStorageBufferinvalidates every image overlapping it.For a direct window that range can be 4 GiB, while the shader may write only a few pages. Every untouched page would become GPU-owned and be downloaded on later CPU access or unmap. Every image in the window would be invalidated, including render targets the shader never touched.
An earlier writable version of this change showed both effects: render targets inside the window were reloaded from stale buffer contents, and unmapping a written 4 GiB window crashed in the synchronous download path in 7 of 8 full test-suite runs.
Correct writes need the GPU to report the pages direct stores actually wrote. Atomics would also need a BDA atomic path, and formatted or typed accesses need format conversion.
Before / after
Historical before/after results from the original
e317465dbase and the pre-rebase branch. InBdaRejectsAddressesOutsideGuestRanges, the test's page table maps three guest pages to sentinel data:0x88776655and0xa1a2a3a4atkExtendedMemoryBase + 0and+ 4;0x44332211as the last dword of the lower address space;0xb1b2b3b4at0x1_1000_0000.mainNUM_RECORDS = -1,STRIDE4, 4 GiB mapping (DirectAddressOversizedRawAccess)storage buffer range is unsupported0x11223344(GLC dword),0x33(byte),0x5eed1234at+0x80000100,0x70b0f00dat+0xFFFFFFF0,0x11223344(S_BUFFER_LOAD)LOWER_ADDRESS_SIZE + 4(hole)0xa1a2a3a4, the dword atkExtendedMemoryBase + 400x4701_1000_0000(past extended memory)0xb1b2b3b4, the dword at0x1_1000_00000LOWER_ADDRESS_SIZE − 2(crosses into the hole)0x66554433; the upper half comes fromkExtendedMemoryBase0x000044332^64 − 2(wraps the address space)0x00004433here)0In the same test both builds agree on the remaining cases: the valid extended and lower-space dwords read
0xa1a2a3a4and0xb1b2b3b4, and an unmapped guest page reads0.Tests
New tests in
shader_recompiler_compute_tests(also selectable with--direct-address-only):DirectAddressOversizedRawAccessCommandProcessor,FindBuffers,NativeStorageBufferand the buffer cache. A 4 GiB read-only window, plus a one-page written output using the same idiom, which keeps its storage view. Data is read back from guest memory. Fails onmain.BdaRejectsAddressesOutsideGuestRangesmain.DirectAddressRawLoadsVolatilein the SPIR-V.DirectAddressExtendedMemoryLoadsDirectAddressBoundsNUM_RECORDS = 0x80000010: an in-bounds dword, a dword x2 with an out-of-bounds second dword, an out-of-bounds dword, the last valid byte, and 16-bit loads inside and across the bound.DirectAddressScalarLoadS_BUFFER_LOADwithSOFFSETplus an immediate, and through a base whose two low bits are set.Every case except the first runs its SPIR-V on the GPU against a page table the test builds itself.
On
main,DirectAddressRawLoadsfails only its SPIR-V requirement, because the resource is still a storage view there. It documents the routing rather than a data bug.resource_tracking_tests:0xFFFFFFFFand0x80000000loads become direct and are registered as read-only;0x7FFFFFFFand a runtimeNUM_RECORDSkeep the view;Current rebased validation
Validation was rerun on the rebased head
a919940a9b6a936b2ae8cf148c6b7c24485d3d86:resource_tracking_tests.exe— pass.shader_recompiler_compute_tests.exe --direct-address-only— pass.shader_recompiler_compute_tests.exe --indirect-buffer-only— pass.VK_LAYER_KHRONOS_validationproduced no validation messages.git diff --check upstream/main...HEAD— pass.The earlier full-suite, CTest-wide, and Tetris Forever results were run before this rebase and are retained as historical evidence only; they are not claimed as current-head validation.
Scope and limitations
NUM_RECORDS. A runtimeNUM_RECORDS, or a constant at or below0x7FFFFFFFeven with a largeSTRIDE, keeps the view path.Related work
-1descriptor is not one of them, so it keeps the view path and the exit there. This PR covers that case and uses none of #690's code.LoadIndirectBuffer, and #931 also editsDefineGetBdaPointer. #931'sBdaPageIndexkeeps the unchecked packing described above. Whichever PR lands second needs a mechanical rebase.AI usage
AI assistance was used for investigation, rebase support, and testing. The contributor reviewed the final diff and current-head validation results before updating this PR.
@coderabbitai[bot] on GitHub · 2026-10-02 15:38 UTC · original · edited 2026-10-05 18:30 UTC
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
📝 Walkthrough
Walkthrough
The recompiler marks eligible oversized raw reads for direct guest addressing. The SPIR-V backend emits bounded direct-address loads and validates guest address ranges. The host materializes the requested guest-memory range, capped at 4 GiB. New tests cover routing, load widths, bounds, invalid addresses, and end-to-end reads across a 4 GiB mapping.
Suggested reviewers:
nmzikPriority: ➖ Normal
Change: Bug fix
Merge Risk: 🔵 Low · up to
a9199Scalar buffer reads that request coherent access through a direct-address buffer lose their volatile semantics. This is a small, bounded issue that is straightforward to fix before or soon after merge.
Security Architecture Review
Security architecture risk: 🔵 Low · up to
a9199Oversized reads gain a new execution path with explicit address checks and no added write authority. No introduced security defect was established, but concurrent-update and recovery behavior remains partly unverified.
Retained concerns
No architecture-level concerns identified.
Security review details
Security Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❓ 1
❌ Failed checks (1 inconclusive)
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 25.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 31 functions across 8 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.@coderabbitai[bot] on GitHub · 2026-10-02 15:38 UTC · original · edited 2026-10-05 18:29 UTC
On
src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppline 928 (outdated):🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Pass
coherenttoLoadBdainDirectScalarLoad.DirectLoadforwardsctx.Memory(inst).coherent.DirectScalarLoaduses the default valuefalse. A GLC scalar buffer read on a direct-address resource therefore loses the volatile access semantics that the storage-view path applies throughPrepareStorageBufferResourceAccess.Proposed fix
📝 Committable suggestion
@coderabbitai[bot] on GitHub · 2026-10-02 15:38 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
4647ebac-8847-4494-9530-348e5aafba0a📥 Commits
Reviewing files that changed from the base of the PR and between
e317465d8aand 7a81c02d71f040b8391dcd63a1caf3f9afcda4fa.📒 Files selected for processing (9)
src/graphics/host_gpu/renderer/pipeline/descriptors.cppsrc/graphics/shader/recompiler/ShaderRecompiler.cppsrc/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cppsrc/graphics/shader/recompiler/ir/ShaderIR.hsrc/graphics/shader/recompiler/ir/passes/ResourceTracking.cpptests/ResourceTrackingTests.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.
@MehmetCambaz on GitHub · 2026-10-05 18:19 UTC · original
On
src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppline 928 (outdated):Thanks for flagging this. I traced the current memory-info path after rebasing onto main.
S_BUFFER_LOADis classified asResourceKind::ScalarBuffer, whileMemoryInfo::coherentis populated for the applicable non-atomicResourceKind::Bufferaccesses. As a result, a coherent request cannot currently reachDirectScalarLoadthrough this scalar path. The direct vector path does forward its reachable coherent state toLoadBda, where it emits the corresponding volatile access. I therefore left the scalar path unchanged.@ -941,0 +981,4 @@// GPU-selected scalar buffer load.uint32_t DirectScalarLoad(ValueEmitContext& ctx, const IR::Inst& inst) {return LoadIndirectScalarBuffer(ctx, inst);}@coderabbitai[bot] on GitHub · 2026-10-05 18:23 UTC · original
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Pass
coherentthroughDirectScalarLoad.DirectLoadforwardsctx.Memory(inst).coherenttoLoadBda.DirectScalarLoadcallsLoadIndirectScalarBuffer, which callsLoadBdaDwordwith the defaultcoherent = false. A GLC scalar buffer read on a direct-address resource therefore loses volatile semantics. The storage-view path keeps them throughPrepareStorageBufferResourceAccess.Add a
coherentparameter toLoadIndirectScalarBuffer. Passctx.Memory(inst).coherentfromDirectScalarLoad. Leave theIndirectBuffercaller on the default.Proposed fix
@coderabbitai[bot] on GitHub · 2026-10-05 18:23 UTC · original · reviewed
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
06043368-8015-4dd9-8708-4a9992c89d59📥 Commits
Reviewing files that changed from the base of the PR and between 7a81c02d71f040b8391dcd63a1caf3f9afcda4fa and
a919940a9b.📒 Files selected for processing (9)
src/graphics/host_gpu/renderer/pipeline/descriptors.cppsrc/graphics/shader/recompiler/ShaderRecompiler.cppsrc/graphics/shader/recompiler/backend/spirv/SpirvEmitter.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppsrc/graphics/shader/recompiler/backend/spirv/spirvEmitterMemoryHelpers.cppsrc/graphics/shader/recompiler/ir/ShaderIR.hsrc/graphics/shader/recompiler/ir/passes/ResourceTracking.cpptests/ResourceTrackingTests.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.
@coderabbitai[bot] on GitHub · 2026-10-05 18:30 UTC · original
On
src/graphics/shader/recompiler/backend/spirv/spirvEmitterMemory.cppline 928 (outdated):🧩 Analysis chain
🏁 Script executed:
Length of output: 14171
@MehmetCambazThanks for the clarification. The current code supports your explanation.In
src/graphics/shader/recompiler/frontend/translate/Memory.cpp, Line 93 classifies scalar buffer loads asResourceKind::ScalarBuffer. Lines 132–133 setMemoryInfo::coherentonly for non-atomicResourceKind::Bufferaccesses with GLC or DLC.Therefore,
DirectScalarLoadcannot receivecoherent == truethrough this path.DirectLoadalready forwards the reachable coherent state. My finding does not apply, so I withdraw it. No scalar-path change is needed.✏️ Learnings added
✅ Review thread resolved.
You are interacting with an AI system.
Pull request closed