Skip to content

GPU: prevent overflow and enforce workload bounds in indirect execution - #40

Closed
aycow wants to merge 5 commits into
Marvisak:mainfrom
aycow:fix/indirect-workload-validation
Closed

aycow wants to merge 5 commits into
Marvisak:mainfrom
aycow:fix/indirect-workload-validation

Conversation

@aycow

@aycow aycow commented Nov 23, 2026 •

Copy link
Copy Markdown

What

The sanitizer introduced in 8c26061 multiplied compute dimensions in 32-bit arithmetic before capping the result. It capped the charged cost while leaving oversized grids in the argument buffer. Its budget counter also added rejected costs, so it could wrap and admit work after the limit was reached.

The original shader left [2048, 2048, 1024] intact after the 2^32 product wrapped to zero. It also retained [1025, 1024, 1] above the 2^20 group limit. The synthetic tests run the sanitizer and inspect the resulting arguments and budget. They never execute the oversized dispatches.

  • Check the D3D12 axis limits and the compute group limit before multiplying. Preserve valid grids and empty excessive dispatches.
  • Use a Shader Model 5.1 compare-exchange loop so rejected work leaves the budget available. Reset the budget under the submission lock. The branch incorporates main at 35b054e, including its 2^27 budget and the single-pass dispatch mapping.

Review changes

  • Argument and count shadows start in COMMON but may already have been used for shader or other buffer accesses by the time indirect execution runs. A prelude selects enhanced buffer barriers at the start of each native submission, including when GPU timing submits lists individually. The barriers order previous accesses, validation, indirect reads, and later uses. An argument and count that share a native resource are synchronized together. On the legacy path, only the argument resource transitions from UAV to INDIRECT_ARGUMENT around execution and returns to COMMON afterward, including on early exit. A distinct count can promote from COMMON. The fallback preserves explicit title barriers between UAV or COPY_DEST and INDIRECT_ARGUMENT for existing buffer shadows by handing them off through COMMON. A write earlier in the same native submission still requires a handoff. Buffers decay at submission boundaries.
  • Title validation and host shadow resolution use the same span through the last argument. Two 12-byte dispatch records with a 16-byte stride need 28 bytes. The old check required 32. Zero records take zero bytes, and alignment, minimum stride, dispatch size, and shader addressing are still checked.

Tested

Check on 22b9ed1 Enhanced Forced legacy
AMD Radeon Graphics, D3D12 debug layer 14 passed 14 passed
AMD Radeon Graphics, debug layer and full GPU-based validation 14 passed 14 passed
Microsoft WARP, D3D12 debug layer 14 passed 14 passed
Microsoft WARP, debug layer and full GPU-based validation 14 passed 14 passed

The app-local Microsoft Agility SDK 1.620.2 enabled the debug layer. The validation run checked device configuration for active GPU-based validation with resource-state tracking and failed on D3D12 InfoQueue errors. The matrix covers CPU-generated counts, shared argument/count resources, same-submission UAV and copy producers, and repeated executions across submission boundaries. With the legacy handoff deliberately omitted, a same-list negative control reported the count buffer still in COPY_DEST or UAV when ExecuteIndirect required INDIRECT_ARGUMENT. Restoring the handoff passed on AMD and WARP.

Run cargo test -p victory-gpu --features diagnostics indirect -- --nocapture --test-threads=1 with an active debug runtime. Set VICTORY_D3D12_DEBUG=1 and VICTORY_TEST_D3D12_VALIDATE=1, and add VICTORY_D3D12_GBV=1 for full validation. Use VICTORY_TEST_LEGACY_INDIRECT=1 to force legacy barriers and VICTORY_D3D12_WARP=1 for WARP. Workspace tests passed (240 passed, 3 ignored), as did cargo check --workspace --all-targets. The prior diagnostics Clippy, policy and diff checks passed on this same commit.

The bounds tests reject a buffer one byte short and execute a final record at a nonzero offset with no trailing padding. A separate native D3D12 probe used explicit COPY_DEST-to-INDIRECT_ARGUMENT transitions, verified the count and recorded shader invocations. On AMD Radeon Graphics (PCI 1002:1114, driver 32.0.22042.1), a zero count still executed the first dispatch. A two-record call also executed only its first dispatch, even without a count buffer. The native probe matched 44 of 88 expectations on AMD and all 88 on WARP and NVIDIA RTX 5070 Laptop with full GPU-based validation, with no debug errors. The AMD result also reproduced with the inbox runtime. This establishes reproduction outside VIctory on the tested adapter and driver. The cause within the driver or runtime remains undetermined.

DaviTostes independently tested the exact head on Arch Linux with an RX 9060 XT, RADV 26.3.1, Wine 11.22, vkd3d-proton 3.1 and native Microsoft d3dcompiler_47. All 13 indirect tests included by that build passed. The victory_gpu suite was 50 passed and two failed for the separately reported pipeline-library and mapped-memory cases. On the preceding a2ab63d revision, Wine’s built-in compiler rejected RWByteAddressBuffer.Load before the tests could exercise the indirect path. Exact-head Proton run · Compiler control

A separate composition with #178 at f435ad1 exercises its DXC fallback. In-process Windows SDK 26100 DXC returned unsigned bytecode even with its companion dxil.dll in the compiler folder. The review patch uses the existing DXIL validator to sign that output. On Windows, all 14 cases passed on AMD and WARP with enhanced and forced legacy barriers, under both FXC and forced DXC, with full GPU-based validation. The composition is available for the #178 review. Compiler proposal · Test branch · Signer patch

Scope

The sanitizer still scans MaxCommandCount for counted calls. Reading the actual GPU count before charging records is a separate follow-up. PR #24 covers the distinct DispatchMeshX entry point. The title watchdog and world rendering remain unverified.

This contribution was AI-assisted with OpenAI Codex.

Comment thread crates/victory-gpu/src/indirect.rs Outdated
l.SetComputeRootUnorderedAccessView(2, budget.GetGPUVirtualAddress());
l.Dispatch(records.div_ceil(THREADS_PER_GROUP), 1, 1);
l.ResourceBarrier(&[uav_barrier()]);
for buffer in [Some(buffer), count].into_iter().flatten() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to track the count buffer's real state, or switch it from COMMON.

Before the indirect call, a barrier switches the count buffer to the state the call needs. The barrier says the buffer starts in the UAV state but the count buffer usually starts in COMMON instead because nothing in the list wrote to it as a UAV first. I'd first this before merging but verify yourself too.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for flagging the state assumption. A shadow may already have GPU reads or writes, and it does not decay between lists submitted together. The revision selects enhanced barriers at the start of each native submission, orders the producer and indirect accesses, and leaves buffers available for their next use. A shared argument/count resource is handled once. CPU, UAV and copy producers, resubmission, and split timing submissions passed on AMD and WARP. The debug layer was unavailable here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok good, one problem with enhanced barriers. Comment is below

/// may include other memory or padding beyond the title's buffer.
fn indirect_address(buffer: This, offset: u64, len: u64) -> Option<u64> {
let (base, size) = crate::resource::buffer_bytes(buffer)?;
if !offset.is_multiple_of(4) || offset.checked_add(len)? > size {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new size check assumes the last record in the argument buffer is a full stride long however.. it's often the buffer ends right after the last record's actual data.

I'd check against the start of the last record plus the argument size. I think byte_len already uses that rule

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching the trailing stride. The title bounds check and shadow lookup now use the same last-record span. The regression returned 32 bytes before and now accepts 28 while rejecting 27. The native test executes the final record at a nonzero offset with zero trailing padding on AMD and WARP. I also recorded the separate AMD two-dispatch observation in the PR description.

Comment thread crates/victory-gpu/src/indirect.rs Outdated
let Some(len) = byte_len(kind, stride, records) else {
return false;
};
if len == 0 || !offset.is_multiple_of(4) || !enhanced_barriers() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the GPU setup doesn't support enhanced barriers, this will fail.

Keep the old barrier code as a fallback when enhanced barriers are missing for our older GPUs

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. Commit a2ab63d restores the legacy UAV and INDIRECT_ARGUMENT transitions when enhanced barriers or command list 7 are unavailable. It also restores the buffers if pipeline preparation drops the call. The forced legacy path passed 13 focused tests on AMD and WARP, and the enhanced path passed all 14 on each.

@aycow
aycow requested a review from raffclar November 24, 2026 00:34
Comment thread crates/victory-gpu/src/indirect.rs Outdated
uav_barrier(l);
// Older hosts use the existing COMMON promotion/UAV convention
// for shadow buffers. The sanitizer leaves arguments in UAV.
for buffer in [Some(buffer), separate_count].into_iter().flatten() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove separate_count from both legacy loops, so only buffer is switched. I think your machine is missing the original barrier fault; a wrong starting state is only reported by the D3D12 debug layer and your machine didn't have it (DXGI_ERROR_SDK_COMPONENT_MISSING) based on your PR description.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The argument buffer really is in the UAV state because the clamp shader just wrote it

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for catching this. In 22b9ed1, the legacy transitions apply only to the argument resource, including when it also contains the count. A separate count can promote from COMMON. For a UAV or copy write in the same native submission, the fallback now preserves the title's explicit handoff through COMMON. Decay only occurs after a native submission.

AMD and WARP each passed 14 focused tests in both enhanced and forced legacy modes, including the CPU count, UAV and copy producers, shared resources, and resubmission. D3D12 debug-layer and GPU-based validation are still outstanding. The Graphics Tools install hit CBS_E_SOURCE_MISSING, and the strict probe confirmed the layer was not active.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for pointing out the missing validation. I reran 22b9ed1 on AMD and WARP with Agility SDK 1.620.2. All 14 focused tests passed on each adapter in both enhanced and forced legacy modes, with the D3D12 debug layer and full GPU-based state tracking active.

I also omitted the legacy handoff in a same-list control. On both adapters, validation reported the separate count still in COPY_DEST or UAV when ExecuteIndirect required INDIRECT_ARGUMENT. Restoring the handoff cleared both errors. The separate CPU count can promote from COMMON, and the clamp-written argument resource retains its own transition.

The AMD zero-count dispatch also reproduces in a standalone native D3D12 test with explicit states and no validation errors. WARP and NVIDIA observed zero dispatches. The PR description has the adapter, driver and test details.

@DaviTostes

Copy link
Copy Markdown

Tested a2ab63d under Wine 11.22 on Arch Linux x86_64 (AMD RX 9060 XT, RADV 26.3.1), Windows build with cargo xwin ... --target x86_64-pc-windows-msvc. Two environments, and the PR is fine in both — the first run's failures were a compiler gap:

  1. vkd3d-proton 3.1 + Wine's builtin d3dcompiler_47: 39 passed, 13 failed. All 13 are assert!(bound(...)) in indirect::tests::* (the 12 new tests plus argument_clamp_builds), because Wine's compiler rejects the clamp shader (E5005: Method 'Load' is not defined on type 'RWByteAddressBuffer'), clamp() returns None, and bound returns false.
  2. Same vkd3d-proton, with a native Microsoft d3dcompiler_47.dll on the DLL search path (WINEDLLOVERRIDES=d3dcompiler_47=n): 50 passed, 2 failed. The 12 new indirect tests and argument_clamp_builds all pass. The two remaining failures are environment-only:
  3. Cross-check on Wine's built-in D3D12 (fresh prefix, no vkd3d-proton): 52/52 pass, including Wine/vkd3d: deferred uploads are skipped because VirtualQuery() reports mapped memory as MEM_FREE #128's test.

So the new indirect tests do run and pass against a real D3D12 implementation here; under Proton the native d3dcompiler_47 is the missing piece. Note that the test module adds 12 tests and is a strong addition — it exercised the bounds/barrier paths end to end.

No game data used. AI-assisted (DeepSeek V4.1 Flash coding agent).

@DaviTostes

Copy link
Copy Markdown

Re-checked the new head 22b9ed1 ("preserve legacy indirect count buffer handoffs") under Wine 11.22 + vkd3d-proton 3.1 (AMD RX 9060 XT, RADV 26.3.1), Windows build with a native Microsoft d3dcompiler_47: pass, no regression.

No game data used.

@aycow

aycow commented Nov 24, 2026

Copy link
Copy Markdown
Author

@ifBars merge?

@ghost ghost mentioned this pull request Nov 24, 2026
@Marvisak Marvisak closed this Nov 24, 2026
edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
The tester tree (upstream main ffe310e plus its PRs, update 8; see its
INTEGRATION.md) ran 11-25 minutes in the world on an RTX 5070 without a
device removal. Where both sides carry the same PR (the wave64 stack
#223/#233/#320 with #439 and #180, #454, #336, #259, #331 and others), the
tester tree's newer head is taken; our own work and the PRs only we
merged are kept.

Conflicts, file by file:

- descriptor/host.rs: the tester layout (`spare`, the guard slot after the
  dynamic slots, `free_table`, the capped sampler heap). A capped view
  heap keeps `capped_reserve()` dynamic slots, now 2^18 by default (the
  tester measurement, and our 91fed158), still `VICTORY_DYNAMIC_SLOTS` in
  diagnostics builds; uncapped hosts keep our 2^19. Our slot statistics
  (TAKEN/PEAK/SHORT), the bindless plan cache (`CommittedRegions`,
  `timed_valid_title_address`, `timed_find`, `title_bounds`) and the
  revision triple are kept beside the tester's `guard_slot`.
- Buffer states: the tester tree's buffer-state tracker (#334: every list
  moves host copies of title memory between GENERIC_READ and
  UNORDERED_ACCESS and back to common before it closes) and depth twins
  (#469) are taken. #40's enhanced/legacy indirect barriers (the indirect
  prelude, `use_indirect_buffers`, the title buffer handoff mirrored in
  `host_barrier`) cannot share buffers with that tracker and are dropped;
  #40's argument checks (`byte_len`, exact spans, overflow-safe clamp
  shader, aligned counts) stay. `indirect::bound` and #282's
  `rectangles` go through `buffer_state`, and `indirect::execute` (#334)
  replaces `done`. #178's DXC fallback compiles both of our passes.
  Our segments (#387: `close` ends the segment, `close_native` closes a
  native list) carry the tracker: each native list returns its buffers
  to common and its twins to their depth targets, and each prelude also
  holds our texture uploads.
- shadow.rs: our write flow (`queue_write`, one `snapshot` after the
  batch's refreshes, `finish_writes`, the unchanged-page cache) with
  #261's copy-back that also gives the snapshot the title's bytes; its
  tests run through our flow.
- pipeline/make.rs: #275's per-frame budget and per-pipeline wake pair,
  with our compute waits (a dispatch waits for its pipeline, up to 20 s).
- pipeline/library.rs: the tester version (#347, #275's saver thread);
  our concurrent-write test kept. shader_cache.rs: our byte-returning
  cache API with #358's "translated, only not kept".
- draw.rs: #493's root SRV tables; where no table can stand in, our
  drop of a draw whose root view is unset or outside title buffers. Our
  refusal of a table offset past the capped heap stays.
- resource.rs: `HostTexture` has both our `staged` generation and the
  depth twin.
- Shaders: the tester's lower.rs for the wave64 stack, #160's image
  sampling (it covers our #73 and #136 sample forms) and #453/#587; kept
  from our side: #136's preference for an image or buffer use of a
  descriptor read as data and its `s_buffer_` arm, #422's nearest-even
  narrowing (also for #169's d16 loads and #453's interpolation), #452's
  spin-wait limit, #391's LDS limit, #302's spilled root arguments (now in
  `NativeProgram::translation_ir`), #136's PSV0 interpolation beside the
  tester's row harmonisation. split_tests.rs, lane_read_loop_tests.rs and
  docs/wave64-on-wave32.md are the tester versions (the same PRs at newer
  heads).
- Tests: #483's heap guard dwords filled in our GPU tests of #200
  (v_div_scale) and #437 (scalar loads from a raw view), which read
  through the guard slot otherwise; #334's debug-layer test passes an
  offset to our `indirect::bound`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
edsuuu referenced this pull request in edsuuu/VI-BR-PORT Nov 24, 2026
…ame wait bundle

Taken from the bundle: 64 MB stacks for pipeline workers (#1129), no
blending on integer render targets (#1152), root signature flag fallback
(#626), read-only depth read states (#485, on our stored rtvs/dsv and
bind_targets), enhanced texture barrier translation (#642, on our
recording_list so continuation segments get it), indirect mesh dispatch
(#24), the frame wait taking its tick before it sleeps (#174), and the
make.rs unit tests (#1203).

Kept from our side:
- pipeline/make.rs: early() starts every compute pipeline at creation
  (b4e8419); the per-pipeline wake pair, per-frame budget, wait_compute
  and copystat counters. The bundle's the_wait_budget_is_spent_once_per_frame
  test is dropped (written for its fixed BUDGET; our FrameBudget tests
  cover it); a_pipeline_is_made_once now holds the tests' serial lock.
- indirect.rs: our whole file (#40's overflow-safe clamp, DXC fallback for
  Wine, rectangle pass). #1279's structured-buffer clamp and its readback
  test (written for the old bound/done API) are left out.
- draw.rs: NOT_MADE counter, user_dword, typed table nulls
  (table_view_props, mirror_for_draw); the depth test calls readable()
  directly since our tables() needs a host pipeline.
- frame.rs: our `_tick` (the diagnostics log already names it).
- list.rs: execute_indirect's DISPATCH_SINGLE mapping in one place; our
  tests beside the bundle's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
justlovett0 added a commit to justlovett0/VIctory that referenced this pull request Nov 24, 2026
…OMPARE_PARALLEL

VICTORY_PERMLANE=0 refuses v_permlane16/x16 as before (default on).
VICTORY_CARD_COMPARE_PARALLEL=0 uses the original one-thread-per-piece
CARD_COMPARE_SERIAL (default on = parallel group reduction). The COPY queue
already has VICTORY_RELAY_COPY_QUEUE. Verified intertwined: geometry/models/
lighting load properly, 230-240ms; fetch wait 86->6ms, copy-back 186->34ms,
GPU 172->140ms; refusals 21->9 (permlane hash a929109552ce1e84 now translates).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants