upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com>2026-12-01 16:32:49 +0200
committerDimitar Pavlov <360593571+azsekazvamdimitar@users.noreply.github.com>2026-12-01 16:40:36 +0200
commit8ebe7cc2e854b9467cd2d464307ece5cd4d2c2ac (patch)
treed22022848548d4209ecdbe4c2084dff701294081
parent098f7ff761cef6de2fab29464c50a3f262f23bef (diff)
d3d12/vulkan + make_game: ReBAR DMA readback, budgeted staged slabs, test fixes & CLI wiring
-rw-r--r--docs/design.md2
-rw-r--r--make_game.py13
-rw-r--r--runtime/shims/d3d12_title_buffer_windows.h80
-rw-r--r--runtime/shims/d3d12_vulkan_device.cpp235
-rw-r--r--runtime/test/arena_staging_test.cpp129
-rw-r--r--runtime/test/d3d12_existing_heap_test.cpp10
-rw-r--r--tools/rdna2spirv.py2
7 files changed, 438 insertions, 33 deletions
diff --git a/docs/design.md b/docs/design.md
index fe636200d..ba4abc67a 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -414,7 +414,7 @@ How the generated SPIR-V expects the runtime to work:
414| Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) | 414| Mixed flat and smooth f32 reads | A pixel shader may use `v_interp_mov_f32 p0` and `v_interp_p1/p2_f32` on the same input location. The translator declares it `PerVertexKHR`, takes vertex 0 for the MOV, and interpolates the smooth read with the triangle weights. The fallback modes without per-vertex inputs reject this combination. The synthetic `mixed_f32_varying.asm` fixture and CPU interpreter check both reads at two points of one triangle. [AMD RDNA 2 ISA, VINTRP instructions](https://www.amd.com/content/dam/amd/en/documents/radeon-tech-docs/instruction-set-architectures/rdna2-shader-instruction-set-architecture.pdf) |
415| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). | 415| Computed I/J barycentrics (SHADER-177) | `v_interp_p1/p2` weight the interpolation with the values their operand VGPRs hold at the two ops, not with the hardware's own pair. Vonsek's image evidence on a synthetic triangle (#1224): zeroed sources render P0 = (0,0) on all 4,096 pixels, and copies of the pair read in swapped order render (v,u) — both follow the two VINTRP equations in the RDNA2 ISA guide; the centre interpolation the single-lane model used to emit is wrong for both. When a write of the operand register reaches an interp site (earlier in its own basic block, or in any block a path runs through first — loops included; a write at the site itself, an interp whose destination is its own I/J register, happens after the operand is read), the attribute is read `PerVertexKHR` and both ops interpolate with the operand values loaded from `%vgpr`, which holds whatever the program computed: constants (snapped coordinates, 577 straight-line sites), copies and copy chains (575), arithmetic (8), multi-writer sequences (1,135). The p1 loads its I and keeps it for the p2, which loads its J fresh — the program often sets J up between the two ops (574 sites) — so the final value uses the I of the p1 with the J of the p2; the p1's own full-sum value is dead because nothing may read the partial between the ops. Pipodi's straight-line scan puts the upper bound at 213 PS (#1218 comment 7076614458; 2,290 v0/v1 sites plus one PS reading J through a copy, all branchy); the reaching-write analysis finds 207 with a write that can reach an interp, and 6 whose overwrites sit on paths that cannot (left pristine, `.spv` unchanged). The other 11,888 PS keep the interpolated-input read and a byte-identical `.spv`. Composes with the operand guards (row above, #1224): a pristine plain `v_mov` copy of the pair stays the guards' to model (centre interpolation, bit-identical `.spv`, including the corpus's one copy PS), an operand that is neither v0/v1 nor written stays the guards' role-naming refusal, and a computed site is exempt from `interp_pair_src` and modelled here — which relaxes exactly the guards' copy-based refusals whose operand a program write reaches: a twice-written register (`v_mov` then arithmetic — the load reads the value the later write left; value-proven by `test_copy_written_again_is_computed`), a copy of an already-overwritten v0/v1 (Vonsek's zero-before-copy row: hardware renders P0, which is exactly the loaded zeros), and a modified `v_mov_b32_dpp` source (any write of the operand is a `%vgpr` value; translation-only test). A pristine copy in the wrong role still refuses (no computed value to model). Over the corpus the relaxation is empty — every one of the 213 PS names v0/v1 (or the one qualified copy), so on main and on this branch alike the set translates 213/213 and passes `spirv-val` 213/213, and no shader changes class; the guards' refusals that relax are the synthetic ones the tests cover. Refused (naming the pattern): a computed pair whose p1 partial is rewritten or read between the ops (its hardware value P10·I would be observable), one whose ops are not in one basic block (the captured I would not dominate the p2), a dangling op without its partner, any computed pair under `--bary-fallback` or `--f16-interp-fallback` (neither has PerVertexKHR inputs; the latter's decoded-half read would otherwise drop the computed weights), and a computed 32-bit read of a 16-bit-flagged interpolant — every one empty over the corpus. Confirmed by `tests/semantic/test_interp_computed_ij.py` and `tests/semantic/test_interp_guards.py` (Vonsek's rows, the between-ops J, f16 pairs, the refusals, the relaxed classes) and the `ps_ij_computed` GPU test (RTX 5060 Ti: snapped quarter pair = 0.5, zeroed pair = P0 = 0, (i, j/2) halving the second weight with 0.0 max error over 4,096 pixels; the same fixture built on main is wrong on 4,096 of 4,096). |
416| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). The mask-word gather is emitted for every such data read. EXEC narrowing is a per-lane value in the translator's model, not SPIR-V control flow, and mask-data readers are kept out of lane-local `if (active)` runs, so lanes EXEC has off still execute the gather and contribute the mask bits they hold. The eager store above keeps compiler lowering from moving that subgroup op into an EXEC-selected arm (the MoltenVK failure mode). Narrowed-EXEC SGPR/VCC reads, an independent all-ones SGPR restore, and the composed vector-bitwise masks are covered in `tests/semantic/test_lane_masks_vector_bitwise.py`; `tests/semantic/test_wave_mask_eager.py` checks that no gather is conditional. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). | 416| Whole-wave masks | `tools/lane_masks.py` tracks per-lane mask bits through scalar registers, vector operations and saved EXEC spills. Whole-mask counts, first-set-lane queries, the leading-bit scans `s_flbit_i32_b32` / `s_flbit_i32` of `vcc_lo`/`exec_lo` (and `_hi`) and equality use subgroup operations (`tests/semantic/test_salu_flbit_lane_mask.py`; until then the flbit scans saw this lane's 0 / ~0). Whole-mask counts, first-set-lane queries and equality use subgroup operations. `cs_wavemask` checks all 64 lanes with a partially active EXEC mask. A physical 32-lane subgroup cannot directly exchange mask bits with the other half of a wave64, so `cs_wavemask` and the `cs_wave64_ballot` / `cs_wm_*` tests are exact only on 64-wide subgroups (AMD): on an RTX 4090 (subgroup 32) `s_bcnt1_i32_b64` of lanes 16–47 counts 16, one half (#101). `check.py` skips them where the GPU has no 64-wide compute subgroup. A mask copied into a VGPR with `v_mov_b32` goes through the normal EXEC-gated store, so inactive lanes keep the old VGPR (SHADER-21 part 2, #210); per-lane mask computations still store in all lanes, because whole-wave readers (`wave_mask`, `v_readfirstlane`) read every lane's bit. `cs_mask_vgpr_exec` checks it. A lane mask (EXEC/VCC or a mask-tracked SGPR) that a VALU op reads as a 32-bit value — `v_mov_b32` of it into a plain VGPR, or any VALU source where the mask is data rather than a mask operand — yields the whole wave's mask word, the same in every lane, not this lane's 0 / ~0 bit; until the fix it gave each lane its own bit (found by `tools/crosslane_fuzz.py`, #293). A mask that stays in or passes through a VGPR holds that word. `v_readfirstlane_b32` of one broadcasts the first active lane's copy — the only lane guaranteed fresh after an EXEC-gated `v_mov_b32` — as the word itself into a VGPR destination (VGPR writes are never mask-tracked, so no extraction); a mask-tracked SGPR or special destination gets this lane's bit of it, half-aware in wave64 (a stale word in a lane an EXEC-gated `v_mov_b32` skipped would otherwise leak the other half's bits, `cs_wavemask` lanes 48–63). The gathered mask is stored to a variable of its own before a reader uses it (`Gen.eager`, as DPP's ballot and shuffle are since SHADER-529): `v_mbcnt` writes a VGPR, so its result is selected on the lane's EXEC, and MoltenVK's SPIRV-Cross inlined the single-use gather into the taken arm of that ternary (`active ? popcount(simd_or(...) & below) + acc : old`), where a lane that is off never ran it and its bit was missing from every other lane's count. Confirmed on an Apple M5 (MoltenVK 1.4.2) with `tools/crosslane_fuzz.py --wave 32 --modes native --no-maskdata`: 4 of 100 programs of the default seed mismatched before, none after (SHADER-WAVEMASK-EAGER, `tests/semantic/test_wave_mask_eager.py`). Vector bitwise mask tracking (`VECTOR_BITWISE`) also includes `v_and_or_b32`, `v_xnor_b32` and `v_bfi_b32` when every source is a lane mask or `0`/`-1` (CPU-checked by `tests/test_lane_masks.py` and `tests/semantic/test_lane_masks_vector_bitwise.py`). The mask-word gather is emitted for every such data read. EXEC narrowing is a per-lane value in the translator's model, not SPIR-V control flow, and mask-data readers are kept out of lane-local `if (active)` runs, so lanes EXEC has off still execute the gather and contribute the mask bits they hold. The eager store above keeps compiler lowering from moving that subgroup op into an EXEC-selected arm (the MoltenVK failure mode). Narrowed-EXEC SGPR/VCC reads, an independent all-ones SGPR restore, and the composed vector-bitwise masks are covered in `tests/semantic/test_lane_masks_vector_bitwise.py`; `tests/semantic/test_wave_mask_eager.py` checks that no gather is conditional. Scalar number ops (`s_add_u32 s20, s10, K` after `v_cmp` wrote `s10`) read a mask operand as data the same way (#1043's `NUMBER_READERS`). |
417| Lane masks merged as data (`SHADER-WAVE-LOOP-EXEC-VOTE`, #2501) | When a CFG merge joins a register that is a per-lane mask on one incoming edge and ordinary scalar data on another (for example, a ballot/EXEC-vote loop iterating over set bits with `s_ff1_i32_b32` + `s_bitset0_b32`), `lane_masks.insert_data_merges` inserts an explicit `s_mask_to_data_b32` (`TO_DATA`) on the mask-carrying predecessor so the merge receives the gathered 32-bit/64-bit bitmask rather than each lane's single bit. Without it, a loop draining a lane-mask SGPR via bit-clears can spin on stale per-lane bits in wave64 emulation (observed in retail `lib_cs_03010`: 91–370 ms/call without `TO_DATA` vs < 2.5 ms/frame with it on RTX 3090). Confirmed by `tests/semantic/test_ballot_bit_loop.py` and the full semantic suite (`551 files, 6,680 tests`). | 417| Lane masks merged as data (`SHADER-WAVE-LOOP-EXEC-VOTE`, #2501) | When a CFG merge joins a register that is a per-lane mask on one incoming edge and ordinary scalar data on another (for example, a ballot/EXEC-vote loop iterating over set bits with `s_ff1_i32_b32` + `s_bitset0_b32`), `lane_masks.insert_data_merges` inserts an explicit `s_mask_to_data_b32` (`TO_DATA`) on the mask-carrying predecessor so the merge receives the gathered 32-bit/64-bit bitmask rather than each lane's single bit. Without it, a loop draining a lane-mask SGPR via bit-clears can spin on stale per-lane bits in wave64 emulation (observed in retail `lib_cs_03010`: 91–370 ms/call without `TO_DATA` vs < 2.5 ms/frame with it on RTX 3090). Confirmed by `tests/semantic/test_ballot_bit_loop.py` and the full semantic suite (`555 files, 6,727 tests`). |
418| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). | 418| Floating-point operations | Separate floating-point instructions carry `NoContraction` so the driver preserves their individual rounding. The instructions that fuse multiply-add (`v_fma_f32`, `v_fmac_f32`, `v_fmaak_f32`, `v_fmamk_f32`, `v_fma_mix*`) round **once** on RDNA2 (measured on gfx1150 by `tools/f32_fuzz.py --oracle hw`: 72 of 72 cancellation probes fused). SPIR-V has two ways to say that. `GLSL.std.450 Fma` is the default (`--fma glsl`), but the Vulkan SPIR-V environment gives it the precision "inherited from `OpFMul` followed by `OpFAdd`", so a driver may legally round twice; `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on Mesa RADV/ACO (Linux), `--fma glsl` splits a subset of the 7 f32 FMAs in `cs_fma_fused` depending on GPU, Mesa version, and shader execution modes (measured: 4 of 7 on RX 6800 / Mesa 26.2.6-arch3.1 and RX 7600 / Mesa 27.0.0-devel with `SignedZeroInfNanPreserve 32`, 5 of 7 on RX 6800 before float controls, and 7 of 7 on Radeon Pro V540 RDNA1 / Mesa 25.2.8), while `--fma khr` emits single-rounded `v_fma_f32` (8/8 exact). `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice. `tools/f32_fuzz.py` and `runtime/test/shaders/cs_fma_fused.asm` are the tests that notice — on an AMD Radeon RX 6800 (Mesa RADV 26.2.6-arch3.1, Linux), RADV/ACO actually splits 5 of the 7 f32 FMAs in `cs_fma_fused` under `--fma glsl` (folding/splitting against the live `v_mul_f32` product `a*a`) and emits single-rounded `v_fma_f32` (8/8 exact) under `--fma khr`. `--fma khr` emits `OpFmaKHR` (`SPV_KHR_fma`, capability `FMAKHR`; "correctly rounded"), which needs `VK_KHR_shader_fma` with `shaderFmaFloat32` on the device. The index then lists capability `FMAKHR`, extension `SPV_KHR_fma` and feature `shaderFmaFloat32` for exactly the shaders that use it, and the output of every shader without a fused multiply-add is byte-identical under both options. `khr` is not the default because a device without the extension would fail pipeline creation; a runtime that knows its device has `shaderFmaFloat32` should translate with `--fma khr`. A device that has neither can split `Fma`: the Intel UHD Graphics driver (Xe-LP, Windows 101.7088) does, `cs_fma_fused` words 0, 2, 3 and 5 coming out split, with no `VK_KHR_shader_fma` (SHADER-497). RADV (Mesa 26.3.1, RX 6700 XT) splits the same four words, measured in #3004's review, but it has `VK_KHR_shader_fma` since Mesa 26.2, so `--fma khr` covers it. For it, `--fma exact` (`Gen.fma_exact`, no extension; per multiply-add about 110 instructions more than `glsl`, plus 31 `NoContraction` decorations and 13 constants) builds the single rounding from `NoContraction` f32 operations, after Boldo and Melquiond (IEEE Transactions on Computers 57(4), 2008): Dekker's exact product with the factors split by masking their low 12 mantissa bits, a TwoSum of the addend and the product, the two error terms summed with round-to-odd, and one final rounding. Power-of-two scaling keeps every intermediate in the normal range: by 2^-64 when the product or the addend is at least 2^126, by 2^96 when both are tiny, and 2^64 traded between a factor below 2^-100 and one above 2^-20. Infinite or NaN operands, and a product beyond even the scaled range (the result is ±inf), take the plain `Fma`. Confirmed: `tests/semantic/test_fma_exact.py` runs the emitted instructions in the interpreter with its `Fma` split as on that driver and compares 700 random and 96 edge cases with an exact rational reference; a model of the same steps matched 399,989 of 399,989 cases with a normal or zero result, with f32 denormals kept and flushed; on the GPU, `cs_fma_fused` (and #2211's `cs_w32_fma_mix`) pass with `--fma exact` on that Intel UHD and on an RTX 3050 Laptop (617.42). Not exact: a result in the denormal range (scaled back with a second rounding) and denormal operands, which follow the driver's denormal mode as every f32 operation does here. The f16 forms (`v_fma_f16`, `v_fmac_f16`, `v_pk_fma_f16`) never use either: they are exact round-to-odd arithmetic built from `OpFMul`/`OpFAdd` with `NoContraction` (`Gen.fma_f16_odd`), so a fused f32 `Fma` would not change them (`v_fma_mixlo_f16`/`v_fma_mixhi_f16` under the toward-zero MODE are the exception: `fma_mix_odd` needs the exact product error `Fma(x, y, -p)`, which is only guaranteed with `OpFmaKHR`), and an f16 `OpFmaKHR` (`shaderFmaFloat16`) is not used. The f64 multiply-adds of `v_div_fmas_f64` (the plain `fma`, the pre-scaled one and the exact product error) are `GLSL.std.450 Fma` on doubles by default, and the Vulkan environment lets a driver round that twice too: NVIDIA's does on some GPUs when it folds an all-constant `Fma` while compiling the pipeline: `runtime/test/shaders/cs_div_fmas_f64.asm`, whose operands are literals, gives the split 0 instead of 2^-60 for `fma(a, a, c)` with a = 1 + 2^-30 and c = -(1 + 2^-29) on the RTX 4090 (621.24, Windows), RTX 3070 (621.01, Windows) and Quadro RTX 4000 (Turing, 615.71.09, Linux), and the fused result on an RTX 5060 Laptop (Blackwell, 621.24). `cs_div_fmas_f64_rt.asm` reads the same operands at run time from s4..s7 and is fused on the 4090, 3070 and 5060 (and on an RTX 4070, #4536); the f32 `cs_fma_fused` fuses 8/8 on the 4090. `--fma khr` emits them as `OpFmaKHR` on doubles, which needs `shaderFmaFloat64` (the index lists that feature, and `shaderFmaFloat32` only for a module with an f32 FMA; `vk_pipeline_check` checks each); on the RTX 4090 it gives the fused 2^-60. `--fma exact` has no f64 form and keeps `Fma`. Checked by `tests/semantic/test_fma_khr_f64.py` (emission, index features, `spirv-val`). |
419| `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). | 419| `NoContraction` cost on MoltenVK (SHADER-234) | MoltenVK's SPIRV-Cross turns each `NoContraction` `OpFAdd`, `OpFSub` and `OpFMul` into a call to a `[[clang::optnone]]` helper (`spvFAdd`, `spvFSub`, `spvFMul`), and Metal does not inline it. MoltenVK 1.4.2 and `main` up to at least `5189f8de` are affected. SPIRV-Cross `98cbb7c0` inlines the helpers from MSL 3.2 with bit-identical output, and MoltenVK on macOS 26 or newer compiles MSL 4.0. On an Apple M3 Max, a translated compute shader of `v_mul_f32`, `v_add_f32` and `v_sub_f32` in a loop took 7.6 to 15.7 times as long on the GPU with the optnone helpers as with `98cbb7c0`. With independent operations and no `NoContraction`, it took two thirds of the `98cbb7c0` time, which is the cost of the decoration itself ([measurement](https://github.com/ItsNotRexed/Leonida/issues/1380#issuecomment-7078722086)). The same `spvFMul` helper drops the sign of a -0 product (SHADER-182, #1376). |
420| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. | 420| `NoContraction` multiply on MoltenVK (SHADER-182) | On MoltenVK, a multiply whose exact product is a negative zero (`+0 × -1.5`, `-0 × 1.0`) returns +0 in f32, f16 and packed f16 (#1203). MoltenVK's SPIRV-Cross turns every `NoContraction` `OpFMul` into its `spvFMul` helper, which returns `fma(l, r, T(0))`. A -0 product plus +0 is +0. The f16 multiplies are `OpFMul` on `float` or `v2float`, so they take the same path. So does the product inside `fma_f16_odd`: `v_fma_f16`, `v_fmac_f16` and `v_pk_fma_f16` return +0 for a -0 product plus a -0 addend. SPIRV-Cross [300681bb](https://github.com/KhronosGroup/SPIRV-Cross/commit/300681bbcb8365a8d1eacdacdbdd0249bbf1d6b1) changes the addend to `T(-0.0)`. MoltenVK 1.4.2 has the old helper, and so does MoltenVK `main` at `5189f8de` (2026-10-13), which pins the parent commit `aa217aeb`. The translator does not change for this. `MVK_CONFIG_FAST_MATH_ENABLED=0` does not help, because the helper itself adds +0, and per #1203 neither does `SignedZeroInfNanPreserve` (#664). Measured on an Apple M3 Max (macOS 27.3): Metal keeps the sign for `a * b` and for `fma(a, b, -0.0)` with `MTLMathModeFast` and with `MTLMathModeSafe`, and loses it only with the +0 addend. With `valu_fuzz.py --family f16`, MoltenVK `5189f8de` as pinned matches 49/50 programs with `--seed 1 --wave 32`, 98/100 with `--seed 1 --emulate` and 98/100 with `--seed 4 --emulate`, and Homebrew MoltenVK 1.4.2 gives the same counts. Each mismatch is a -0 product read as +0. The same build with SPIRV-Cross `300681bb` matches 50/50, 100/100 and 100/100, as does KosmicKrisp (Mesa 26.3.1). For the FMA path, `--seed 330 --wave 32` with `--skip-op v_mul_f16 --skip-op v_pk_mul_f16` matches 49/50 with `aa217aeb` (a `v_fmac_f16` result) and 50/50 with `300681bb` and on KosmicKrisp. |
diff --git a/make_game.py b/make_game.py
index 4d857315e..20c0b35d4 100644
--- a/make_game.py
+++ b/make_game.py
@@ -2018,7 +2018,10 @@ FALLBACK_FLAGS = (("--no-float-controls", "no_float_controls"), ("--no-ftz32", "
2018 ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"), 2018 ("--texel-offset-fallback", "texel_offset_fallback"), ("--mesh-compute", "mesh_compute"),
2019 ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"), 2019 ("--f16-interp-fallback", "f16_interp_fallback"), ("--pc-tail-ubo", "pc_tail_ubo"),
2020 ("--compact-spirv", "compact_spirv"), ("--integer-dot-fallback", "integer_dot_fallback"), 2020 ("--compact-spirv", "compact_spirv"), ("--integer-dot-fallback", "integer_dot_fallback"),
2021 ("--mesh-serial-waves", "mesh_serial_waves"), ("--explicit-lod-bias", "explicit_lod_bias")) 2021 ("--mesh-serial-waves", "mesh_serial_waves"), ("--explicit-lod-bias", "explicit_lod_bias"),
2022 ("--compute-serial-waves", "compute_serial_waves"),
2023 ("--mesh-native-wave32", "mesh_native_wave32"),
2024 ("--spirv-opt", "spirv_opt"))
2022 2025
2023 2026
2024def fallback_flags(a) -> tuple[str, ...]: 2027def fallback_flags(a) -> tuple[str, ...]:
@@ -3688,6 +3691,14 @@ def main() -> int:
3688 "Only wave64 mesh shaders of more than 64 threads, a multiple of 64, with no LDS " 3691 "Only wave64 mesh shaders of more than 64 threads, a multiple of 64, with no LDS "
3689 "instruction, store or atomic take that form; the others, and every shader translated " 3692 "instruction, store or atomic take that form; the others, and every shader translated "
3690 "natively or with --mesh-compute, come out as before. Off by default") 3693 "natively or with --mesh-compute, come out as before. Off by default")
3694 ap.add_argument("--compute-serial-waves", action="store_true",
3695 help="with wave64 emulation, serialize multi-wave compute shaders in 64 invocations instead "
3696 "of side-by-side wave emulation (forwards --compute-serial-waves to rdna2spirv.py). Off by default")
3697 ap.add_argument("--mesh-native-wave32", action="store_true",
3698 help="forward --mesh-native-wave32 to rdna2spirv.py for eligible mesh shaders. Off by default")
3699 ap.add_argument("--spirv-opt", action="store_true",
3700 help="forward --spirv-opt to rdna2spirv.py (runs spirv-opt -O below 512 KiB and safe SSA passes "
3701 "at >= 512 KiB with automatic fallback on validation failure). Off by default")
3691 ap.add_argument("--native-mesh", action="store_true", 3702 ap.add_argument("--native-mesh", action="store_true",
3692 help="keep native mesh shaders on Intel's Windows Vulkan driver instead of turning on " 3703 help="keep native mesh shaders on Intel's Windows Vulkan driver instead of turning on "
3693 "--mesh-compute (for a driver that fixes BUILD-2202's crash)") 3704 "--mesh-compute (for a driver that fixes BUILD-2202's crash)")
diff --git a/runtime/shims/d3d12_title_buffer_windows.h b/runtime/shims/d3d12_title_buffer_windows.h
index 5c910285c..10bf79e8e 100644
--- a/runtime/shims/d3d12_title_buffer_windows.h
+++ b/runtime/shims/d3d12_title_buffer_windows.h
@@ -14,14 +14,16 @@
14#include <vulkan/vulkan.h> 14#include <vulkan/vulkan.h>
15 15
16#include "../src/arena_staging.h" 16#include "../src/arena_staging.h"
17#include "../src/memory_breakdown.h"
17 18
18namespace rt::d3d12 { 19namespace rt::d3d12 {
19 20
20// Storage for shader-addressed mirrors when the main arena has no usable offset. 21// Storage for shader-addressed mirrors when the main arena has no usable offset.
21// Sub-ranges freed via free() are coalesced for reuse; one empty standard 4 MiB block is kept as a spare and any 22// Sub-ranges freed via free() are coalesced for reuse; one empty standard block (4 MiB unstaged or 64 MiB staged) is
22// other empty block releases its Vulkan buffer and memory. When staged mode is enabled (for BAR-restricted GPUs with 23// kept as a spare and any other empty block releases its Vulkan buffer and memory. When staged mode is enabled (for
23// a staged DEVICE_LOCAL arena), blocks are 64 MiB pure DEVICE_LOCAL VRAM slabs paired with a HOST_VISIBLE staging 24// BAR-restricted GPUs with a staged DEVICE_LOCAL arena), blocks are 64 MiB pure DEVICE_LOCAL VRAM slabs paired with a
24// mirror and an exact byte-range dirty tracker, kept pooled until release(). 25// HOST_VISIBLE staging mirror and an exact byte-range dirty tracker; both VRAM and host staging bytes count against
26// `reserved_` and `cap`.
25class TitleBufferWindows { 27class TitleBufferWindows {
26 static constexpr VkDeviceSize kBlockSize = 4ull << 20; 28 static constexpr VkDeviceSize kBlockSize = 4ull << 20;
27 static constexpr VkDeviceSize kStagedBlockSize = 64ull << 20; 29 static constexpr VkDeviceSize kStagedBlockSize = 64ull << 20;
@@ -79,6 +81,7 @@ class TitleBufferWindows {
79 VkBuffer buffer{}; 81 VkBuffer buffer{};
80 VkBuffer staging_buffer{}; 82 VkBuffer staging_buffer{};
81 StagedSlot* staged{}; 83 StagedSlot* staged{};
84 bool host_cached{false};
82 }; 85 };
83 std::array<Published, kPublished> published_{}; 86 std::array<Published, kPublished> published_{};
84 std::atomic<std::size_t> published_count_{0}; 87 std::atomic<std::size_t> published_count_{0};
@@ -237,28 +240,31 @@ public:
237 }; 240 };
238 auto drop_unfitting_spare = [&] { 241 auto drop_unfitting_spare = [&] {
239 for (auto it = blocks_.begin(); it != blocks_.end(); ++it) { 242 for (auto it = blocks_.begin(); it != blocks_.end(); ++it) {
240 if (!it->staged && it->live == 0 && bytes > it->capacity) { 243 if (it->live == 0 && bytes > it->capacity) {
241 destroy_block(d, it); 244 destroy_block(d, it);
242 return true; 245 return true;
243 } 246 }
244 } 247 }
245 return false; 248 return false;
246 }; 249 };
250 const bool make_staged = staged_ && !device_local;
251 const VkDeviceSize min_budget = make_staged ? (bytes <= UINT64_MAX / 2 ? bytes * 2 : UINT64_MAX) : bytes;
247 VkDeviceSize remaining_cap = reserved_ < cap ? cap - reserved_ : 0; 252 VkDeviceSize remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
248 if (bytes > remaining_cap) { 253 if (min_budget > remaining_cap) {
249 if (drop_unfitting_spare()) remaining_cap = reserved_ < cap ? cap - reserved_ : 0; 254 if (drop_unfitting_spare()) remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
250 if (bytes > remaining_cap) { 255 if (min_budget > remaining_cap) {
251 if (at_cap) *at_cap = true; 256 if (at_cap) *at_cap = true;
252 return false; 257 return false;
253 } 258 }
254 } 259 }
255 const bool make_staged = staged_ && !device_local;
256 const VkDeviceSize slab_size = make_staged ? kStagedBlockSize : kBlockSize; 260 const VkDeviceSize slab_size = make_staged ? kStagedBlockSize : kBlockSize;
261 const VkDeviceSize max_single = make_staged ? remaining_cap / 2 : remaining_cap;
257 Block b{}; 262 Block b{};
258 b.capacity = std::max(bytes, std::min(slab_size, remaining_cap)); 263 b.capacity = std::max(bytes, std::min(slab_size, max_single));
259 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 264 VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
260 info.size = b.capacity; 265 info.size = b.capacity;
261 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; 266 info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
267 VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
262 if (make_staged) { 268 if (make_staged) {
263 info.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | 269 info.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
264 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | 270 VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
@@ -285,23 +291,32 @@ public:
285 void* host{}; 291 void* host{};
286 VkResult bound = VK_ERROR_OUT_OF_DEVICE_MEMORY, mapped_result = VK_ERROR_MEMORY_MAP_FAILED; 292 VkResult bound = VK_ERROR_OUT_OF_DEVICE_MEMORY, mapped_result = VK_ERROR_MEMORY_MAP_FAILED;
287 bool block_staged = false; 293 bool block_staged = false;
294 bool block_host_cached = false;
295 VkDeviceSize staging_reserved = 0;
288 if (make_staged && !local_refused_) { 296 if (make_staged && !local_refused_) {
289 VkMemoryPropertyFlags vram_chosen = 0; 297 VkMemoryPropertyFlags vram_chosen = 0;
290 VkDeviceMemory vram_mem = d.allocate(req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, &vram_chosen, true); 298 VkDeviceMemory vram_mem = VK_NULL_HANDLE;
299 {
300 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows);
301 vram_mem = d.allocate(req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, &vram_chosen, true);
302 }
291 VkBuffer staging_buf = VK_NULL_HANDLE; 303 VkBuffer staging_buf = VK_NULL_HANDLE;
292 VkDeviceMemory staging_mem = VK_NULL_HANDLE; 304 VkDeviceMemory staging_mem = VK_NULL_HANDLE;
305 VkMemoryRequirements sreq{};
293 if (vram_mem && (vram_chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { 306 if (vram_mem && (vram_chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) {
294 VkBufferCreateInfo sinfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; 307 VkBufferCreateInfo sinfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
295 sinfo.size = b.capacity; 308 sinfo.size = b.capacity;
296 sinfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; 309 sinfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
297 d.share(sinfo); 310 d.share(sinfo);
298 if (vk.vkCreateBuffer(d.info.device, &sinfo, nullptr, &staging_buf) == VK_SUCCESS) { 311 if (vk.vkCreateBuffer(d.info.device, &sinfo, nullptr, &staging_buf) == VK_SUCCESS) {
299 VkMemoryRequirements sreq{};
300 vk.vkGetBufferMemoryRequirements(d.info.device, staging_buf, &sreq); 312 vk.vkGetBufferMemoryRequirements(d.info.device, staging_buf, &sreq);
301 sreq.memoryTypeBits = system_memory_types(d, sreq.memoryTypeBits, /*cached=*/true); 313 if (req.size <= remaining_cap && sreq.size <= remaining_cap - req.size) {
302 staging_mem = d.allocate(sreq, 314 sreq.memoryTypeBits = system_memory_types(d, sreq.memoryTypeBits, /*cached=*/true);
303 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, 315 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
304 VK_MEMORY_PROPERTY_HOST_CACHED_BIT, nullptr, false); 316 staging_mem = d.allocate(
317 sreq, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
318 VK_MEMORY_PROPERTY_HOST_CACHED_BIT, nullptr, false);
319 }
305 } 320 }
306 } 321 }
307 if (vram_mem && staging_buf && staging_mem && 322 if (vram_mem && staging_buf && staging_mem &&
@@ -314,6 +329,8 @@ public:
314 bound = VK_SUCCESS; 329 bound = VK_SUCCESS;
315 mapped_result = VK_SUCCESS; 330 mapped_result = VK_SUCCESS;
316 block_staged = true; 331 block_staged = true;
332 block_host_cached = true;
333 staging_reserved = sreq.size;
317 } else { 334 } else {
318 if (staging_buf) vk.vkDestroyBuffer(d.info.device, staging_buf, nullptr); 335 if (staging_buf) vk.vkDestroyBuffer(d.info.device, staging_buf, nullptr);
319 if (staging_mem) vk.vkFreeMemory(d.info.device, staging_mem, nullptr); 336 if (staging_mem) vk.vkFreeMemory(d.info.device, staging_mem, nullptr);
@@ -355,6 +372,7 @@ public:
355 "this and later blocks are in host memory\n", 372 "this and later blocks are in host memory\n",
356 static_cast<unsigned long long>(req.size >> 10)); 373 static_cast<unsigned long long>(req.size >> 10));
357 } 374 }
375 if (b.memory) block_host_cached = (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0;
358 if (!b.memory) note_block_failure("vkAllocateMemory (DeviceState::allocate)", bound, req.size); 376 if (!b.memory) note_block_failure("vkAllocateMemory (DeviceState::allocate)", bound, req.size);
359 else if ((bound = vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0)) != VK_SUCCESS) 377 else if ((bound = vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0)) != VK_SUCCESS)
360 note_block_failure("vkBindBufferMemory", bound, req.size); 378 note_block_failure("vkBindBufferMemory", bound, req.size);
@@ -370,7 +388,7 @@ public:
370 if constexpr (requires { d.vsharp_offsets_signed(); }) signed_offsets = d.vsharp_offsets_signed(); 388 if constexpr (requires { d.vsharp_offsets_signed(); }) signed_offsets = d.vsharp_offsets_signed();
371 if (shader_reachable(b.address, b.capacity, d.arena.address, signed_offsets)) { 389 if (shader_reachable(b.address, b.capacity, d.arena.address, signed_offsets)) {
372 b.mapped = static_cast<std::uint8_t*>(host); 390 b.mapped = static_cast<std::uint8_t*>(host);
373 b.reserved_bytes = req.size; 391 b.reserved_bytes = req.size + staging_reserved;
374 b.free_ranges.emplace(0, b.capacity); 392 b.free_ranges.emplace(0, b.capacity);
375 if (block_staged) { 393 if (block_staged) {
376 b.staged = std::make_unique<StagedSlot>(); 394 b.staged = std::make_unique<StagedSlot>();
@@ -382,12 +400,13 @@ public:
382 published_[n].buffer = b.buffer; 400 published_[n].buffer = b.buffer;
383 published_[n].staging_buffer = b.staging_buffer; 401 published_[n].staging_buffer = b.staging_buffer;
384 published_[n].staged = b.staged.get(); 402 published_[n].staged = b.staged.get();
403 published_[n].host_cached = block_host_cached;
385 published_[n].address.store(b.address, std::memory_order_relaxed); 404 published_[n].address.store(b.address, std::memory_order_relaxed);
386 published_count_.store(n + 1, std::memory_order_release); 405 published_count_.store(n + 1, std::memory_order_release);
387 } 406 }
388 layout_generation_.fetch_add(1, std::memory_order_release); 407 layout_generation_.fetch_add(1, std::memory_order_release);
389 blocks_.push_back(std::move(b)); 408 blocks_.push_back(std::move(b));
390 reserved_ += req.size; 409 reserved_ += blocks_.back().reserved_bytes;
391 if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1))) 410 if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1)))
392 std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena%s: %zu blocks, " 411 std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena%s: %zu blocks, "
393 "new block %llu KiB at shader VA 0x%llx\n", 412 "new block %llu KiB at shader VA 0x%llx\n",
@@ -446,7 +465,8 @@ public:
446 b.free_ranges.emplace(merged_begin, merged_end - merged_begin); 465 b.free_ranges.emplace(merged_begin, merged_end - merged_begin);
447 if (b.live > 0) --b.live; 466 if (b.live > 0) --b.live;
448 if (b.live == 0) { 467 if (b.live == 0) {
449 if (b.staged || (b.capacity == kBlockSize && empty_blocks() == 1)) { 468 const VkDeviceSize std_cap = b.staged ? kStagedBlockSize : kBlockSize;
469 if (b.capacity == std_cap && empty_blocks() == 1) {
450 b.free_ranges.clear(); 470 b.free_ranges.clear();
451 b.free_ranges.emplace(0, b.capacity); 471 b.free_ranges.emplace(0, b.capacity);
452 b.used = 0; 472 b.used = 0;
@@ -562,6 +582,28 @@ public:
562 } 582 }
563 } 583 }
564 584
585 // If [ptr, ptr+len) lies in an uncached (e.g. ReBAR WC BAR1) non-staged block, returns true with its VkBuffer
586 // and byte offset so callers can DMA-read it into a HOST_CACHED scratch buffer instead of doing slow WC reads.
587 bool find_uncached_buffer(const std::uint8_t* ptr, std::size_t len, VkBuffer& out_buffer,
588 VkDeviceSize& out_offset) const {
589 if (staged_ || !ptr || !len) return false;
590 const auto p = reinterpret_cast<std::uintptr_t>(ptr);
591 const std::size_t n = published_count_.load(std::memory_order_acquire);
592 for (std::size_t i = 0; i < n; ++i) {
593 const Published& b = published_[i];
594 if (b.host_cached || b.staged || !b.mapped || !b.buffer || !b.address.load(std::memory_order_acquire))
595 continue;
596 const auto lo = reinterpret_cast<std::uintptr_t>(b.mapped);
597 const auto hi = lo + static_cast<std::uintptr_t>(b.capacity);
598 if (p >= lo && p < hi && len <= hi - p) {
599 out_buffer = b.buffer;
600 out_offset = static_cast<VkDeviceSize>(p - lo);
601 return true;
602 }
603 }
604 return false;
605 }
606
565 // Synchronously reads back GPU-written ranges from each staged block's VRAM buffer into its staging mirror 607 // Synchronously reads back GPU-written ranges from each staged block's VRAM buffer into its staging mirror
566 // in a single batched submission. 608 // in a single batched submission.
567 template<class Context> 609 template<class Context>
diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp
index 553c90e6f..a1ebe70b4 100644
--- a/runtime/shims/d3d12_vulkan_device.cpp
+++ b/runtime/shims/d3d12_vulkan_device.cpp
@@ -462,8 +462,35 @@ public:
462 // 462 //
463 // `only` (a retired window's copy, when it is freed): that copy alone goes back, where no live copy changed the 463 // `only` (a retired window's copy, when it is freed): that copy alone goes back, where no live copy changed the
464 // bytes; the live copies' own results wait for their submissions' batches. 464 // bytes; the live copies' own results wait for their submissions' batches.
465 struct ReadbackLookup {
466 struct Entry {
467 std::uintptr_t src_lo = 0;
468 std::uintptr_t src_hi = 0;
469 const std::uint8_t* cached = nullptr;
470 };
471 const Entry* entries = nullptr;
472 std::size_t count = 0;
473 const std::uint8_t* map(const std::uint8_t* ptr, std::size_t len) const {
474 if (!entries || !count || !ptr || !len) return ptr;
475 const auto p = reinterpret_cast<std::uintptr_t>(ptr);
476 std::size_t lo = 0, hi = count;
477 while (lo < hi) {
478 const std::size_t mid = lo + (hi - lo) / 2;
479 if (entries[mid].src_lo <= p)
480 lo = mid + 1;
481 else
482 hi = mid;
483 }
484 if (lo == 0) return ptr;
485 const Entry& e = entries[lo - 1];
486 if (p >= e.src_lo && p < e.src_hi && len <= e.src_hi - p) return e.cached + (p - e.src_lo);
487 return ptr;
488 }
489 };
490
465 std::size_t write_back(const std::pair<std::uintptr_t, std::uintptr_t>* ranges, std::size_t count, 491 std::size_t write_back(const std::pair<std::uintptr_t, std::uintptr_t>* ranges, std::size_t count,
466 std::size_t* reached = nullptr, const std::uint8_t* only = nullptr) { 492 std::size_t* reached = nullptr, const std::uint8_t* only = nullptr,
493 const ReadbackLookup* readback = nullptr) {
467 if (reached) *reached = 0; 494 if (reached) *reached = 0;
468 std::uintptr_t lo = last_, hi = first_; // the pages the ranges cover 495 std::uintptr_t lo = last_, hi = first_; // the pages the ranges cover
469 for (std::size_t r = 0; r < count; ++r) { 496 for (std::size_t r = 0; r < count; ++r) {
@@ -562,7 +589,8 @@ public:
562 if (t->retired != (pass == 1) || (only && pass == 1 && t->shadow != only)) continue; 589 if (t->retired != (pass == 1) || (only && pass == 1 && t->shadow != only)) continue;
563 const std::uintptr_t x = std::max(c, t->begin), y = std::min(e, t->end); 590 const std::uintptr_t x = std::max(c, t->begin), y = std::min(e, t->end);
564 if (x >= y) continue; 591 if (x >= y) continue;
565 const std::uint8_t* copy = t->shadow + (x - t->begin); 592 const std::uint8_t* raw_copy = t->shadow + (x - t->begin);
593 const std::uint8_t* copy = readback ? readback->map(raw_copy, y - x) : raw_copy;
566 const void* now = saved ? static_cast<const void*>(before + (x - c)) 594 const void* now = saved ? static_cast<const void*>(before + (x - c))
567 : reinterpret_cast<const void*>(x); 595 : reinterpret_cast<const void*>(x);
568 if (std::memcmp(now, copy, y - x) == 0) continue; 596 if (std::memcmp(now, copy, y - x) == 0) continue;
@@ -603,9 +631,13 @@ public:
603 if (o == t) continue; 631 if (o == t) continue;
604 const std::uintptr_t lo = std::max(i, o->begin); 632 const std::uintptr_t lo = std::max(i, o->begin);
605 const std::uintptr_t hi = std::min(j, o->end); 633 const std::uintptr_t hi = std::min(j, o->end);
634 const std::uint8_t* o_read =
635 readback && lo < hi
636 ? readback->map(o->shadow + (lo - o->begin), hi - lo)
637 : (o->shadow + (lo - o->begin));
606 std::uintptr_t run_start = hi; 638 std::uintptr_t run_start = hi;
607 for (std::uintptr_t v = lo; v < hi; ++v) { 639 for (std::uintptr_t v = lo; v < hi; ++v) {
608 if (o->shadow[v - o->begin] == before[v - c]) { 640 if (o_read[v - lo] == before[v - c]) {
609 o->shadow[v - o->begin] = copy[v - x]; 641 o->shadow[v - o->begin] = copy[v - x];
610 if (dirty_fn_ && run_start == hi) run_start = v; 642 if (dirty_fn_ && run_start == hi) run_start = v;
611 } else if (dirty_fn_ && run_start < v) { 643 } else if (dirty_fn_ && run_start < v) {
@@ -4304,13 +4336,18 @@ struct DeviceState {
4304 if (!s.has_target(mapped)) continue; 4336 if (!s.has_target(mapped)) continue;
4305 const std::pair<std::uintptr_t, std::uintptr_t> range{static_cast<std::uintptr_t>(start), 4337 const std::pair<std::uintptr_t, std::uintptr_t> range{static_cast<std::uintptr_t>(start),
4306 static_cast<std::uintptr_t>(start + size)}; 4338 static_cast<std::uintptr_t>(start + size)};
4339 ShadowPages::ReadbackLookup rebar_lookup{};
4307 if (arena.staged) { 4340 if (arena.staged) {
4308 std::vector<VkBufferCopy> readbacks; 4341 std::vector<VkBufferCopy> readbacks;
4309 std::map<std::size_t, std::vector<VkBufferCopy>> ext_readbacks; 4342 std::map<std::size_t, std::vector<VkBufferCopy>> ext_readbacks;
4310 collect_staged_shadow_readbacks(s, &range, 1, mapped, readbacks, ext_readbacks); 4343 collect_staged_shadow_readbacks(s, &range, 1, mapped, readbacks, ext_readbacks);
4311 sync_retired_readbacks_to_host(readbacks, ext_readbacks); 4344 sync_retired_readbacks_to_host(readbacks, ext_readbacks);
4345 } else {
4346 prepare_rebar_readbacks(
4347 [&](const auto& add) { s.for_each_target_range(&range, 1, mapped, add); }, rebar_lookup);
4312 } 4348 }
4313 title_write_back_total += s.write_back(&range, 1, nullptr, mapped); 4349 title_write_back_total +=
4350 s.write_back(&range, 1, nullptr, mapped, rebar_lookup.count ? &rebar_lookup : nullptr);
4314 s.remove_target(mapped); 4351 s.remove_target(mapped);
4315 if (!s.targets()) shadows.erase(it); 4352 if (!s.targets()) shadows.erase(it);
4316 return; 4353 return;
@@ -4559,12 +4596,29 @@ struct DeviceState {
4559 } 4596 }
4560 } 4597 }
4561 4598
4599 static VkDeviceSize external_window_cap(bool staged) {
4600 static const VkDeviceSize env_cap = []() -> VkDeviceSize {
4601 char text[32] = {};
4602 const DWORD n = GetEnvironmentVariableA("LEONIDA_EXTERNAL_WINDOWS_MB", text, sizeof(text));
4603 if (n > 0 && n < sizeof(text)) {
4604 const unsigned long long mb = std::strtoull(text, nullptr, 10);
4605 if (mb > 0) return VkDeviceSize(mb) << 20;
4606 }
4607 return 0;
4608 }();
4609 if (env_cap) return env_cap;
4610 // Staged mode counts both VRAM and host staging mirror in reserved_; 4 GiB total = up to 2 GiB VRAM + 2 GiB
4611 // sysmem mirror. Unstaged mode caps at 2 GiB.
4612 return staged ? (4096ull << 20) : (2048ull << 20);
4613 }
4614
4562 bool external_windows_allocate(VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped, 4615 bool external_windows_allocate(VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped,
4563 VkBuffer* out_buffer = nullptr, VkDeviceSize* out_buffer_offset = nullptr, 4616 VkBuffer* out_buffer = nullptr, VkDeviceSize* out_buffer_offset = nullptr,
4564 VkDeviceAddress* out_address = nullptr) { 4617 VkDeviceAddress* out_address = nullptr) {
4565 std::lock_guard lock(external_windows_mutex); 4618 std::lock_guard lock(external_windows_mutex);
4566 drain_deferred_external_frees_locked(); 4619 drain_deferred_external_frees_locked();
4567 if (!external_windows.allocate(*this, bytes, offset, mapped, false, UINT64_MAX, nullptr, out_buffer, 4620 if (!external_windows.allocate(*this, bytes, offset, mapped, false,
4621 external_window_cap(external_windows.staged()), nullptr, out_buffer,
4568 out_buffer_offset, out_address)) 4622 out_buffer_offset, out_address))
4569 return false; 4623 return false;
4570 external_window_made.store(true, std::memory_order_release); 4624 external_window_made.store(true, std::memory_order_release);
@@ -4607,6 +4661,159 @@ struct DeviceState {
4607 } 4661 }
4608 }); 4662 });
4609 } 4663 }
4664
4665 // Grow-only HOST_VISIBLE | HOST_CACHED scratch buffer for DMA readback from uncached ReBAR (WC BAR1) arena
4666 // and external window buffers during ShadowPages::write_back. Guarded by shadow_mutex.
4667 struct RebarReadbackScratch {
4668 VkBuffer buffer = VK_NULL_HANDLE;
4669 VkDeviceMemory memory = VK_NULL_HANDLE;
4670 std::uint8_t* mapped = nullptr;
4671 VkDeviceSize capacity = 0;
4672 bool coherent = true;
4673 std::vector<ShadowPages::ReadbackLookup::Entry> entries;
4674 } rebar_readback;
4675
4676 void destroy_rebar_readback() {
4677 if (!context) return;
4678 auto& vk = context->vk;
4679 if (rebar_readback.mapped && rebar_readback.memory) {
4680 vk.vkUnmapMemory(info.device, rebar_readback.memory);
4681 rebar_readback.mapped = nullptr;
4682 }
4683 if (rebar_readback.buffer) {
4684 vk.vkDestroyBuffer(info.device, rebar_readback.buffer, nullptr);
4685 rebar_readback.buffer = VK_NULL_HANDLE;
4686 }
4687 if (rebar_readback.memory) {
4688 vk.vkFreeMemory(info.device, rebar_readback.memory, nullptr);
4689 rebar_readback.memory = VK_NULL_HANDLE;
4690 }
4691 rebar_readback.capacity = 0;
4692 rebar_readback.entries.clear();
4693 }
4694
4695 bool ensure_rebar_readback(VkDeviceSize need) {
4696 if (need <= rebar_readback.capacity && rebar_readback.buffer && rebar_readback.mapped) return true;
4697 if (!context) return false;
4698 VkDeviceSize cap = std::max<VkDeviceSize>(rebar_readback.capacity ? rebar_readback.capacity * 2 : (16ull << 20),
4699 (need + 65535ull) & ~65535ull);
4700 auto& vk = context->vk;
4701 VkBufferCreateInfo binfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
4702 binfo.size = cap;
4703 binfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
4704 share(binfo);
4705 VkBuffer buf = VK_NULL_HANDLE;
4706 if (vk.vkCreateBuffer(info.device, &binfo, nullptr, &buf) != VK_SUCCESS) return false;
4707 VkMemoryRequirements req{};
4708 vk.vkGetBufferMemoryRequirements(info.device, buf, &req);
4709 VkMemoryPropertyFlags chosen = 0;
4710 VkDeviceMemory mem = VK_NULL_HANDLE;
4711 {
4712 leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
4713 mem = allocate(req,
4714 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
4715 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
4716 0, &chosen, false);
4717 }
4718 void* ptr = nullptr;
4719 if (!mem || vk.vkBindBufferMemory(info.device, buf, mem, 0) != VK_SUCCESS ||
4720 vk.vkMapMemory(info.device, mem, 0, VK_WHOLE_SIZE, 0, &ptr) != VK_SUCCESS) {
4721 if (buf) vk.vkDestroyBuffer(info.device, buf, nullptr);
4722 if (mem) vk.vkFreeMemory(info.device, mem, nullptr);
4723 return false;
4724 }
4725 destroy_rebar_readback();
4726 rebar_readback.buffer = buf;
4727 rebar_readback.memory = mem;
4728 rebar_readback.mapped = static_cast<std::uint8_t*>(ptr);
4729 rebar_readback.capacity = cap;
4730 rebar_readback.coherent = (chosen & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) != 0;
4731 return true;
4732 }
4733
4734 bool arena_uncached_rebar() const {
4735 if (arena.staged || !arena.buffer || !arena.mapped || !arena.size) return false;
4736 if (arena.memory_type >= memory.memoryTypeCount) return false;
4737 const VkMemoryPropertyFlags flags = memory.memoryTypes[arena.memory_type].propertyFlags;
4738 return (flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == 0;
4739 }
4740
4741 template <class Emit>
4742 bool prepare_rebar_readbacks(Emit&& emit, ShadowPages::ReadbackLookup& out) {
4743 out = {};
4744 if (arena.staged || !context) return false;
4745 const bool arena_wc = arena_uncached_rebar();
4746 const auto arena_lo = reinterpret_cast<std::uintptr_t>(arena.mapped);
4747 const auto arena_hi = arena_lo + static_cast<std::uintptr_t>(arena.size);
4748 struct Req {
4749 VkBuffer buf;
4750 VkDeviceSize src_off;
4751 std::uintptr_t src_ptr;
4752 VkDeviceSize len;
4753 };
4754 std::vector<Req> reqs;
4755 emit([&](const std::uint8_t* ptr, std::size_t len) {
4756 if (!ptr || !len) return;
4757 const auto p = reinterpret_cast<std::uintptr_t>(ptr);
4758 if (arena_wc && p >= arena_lo && p < arena_hi && len <= arena_hi - p) {
4759 reqs.push_back({arena.buffer, static_cast<VkDeviceSize>(p - arena_lo), p, static_cast<VkDeviceSize>(len)});
4760 return;
4761 }
4762 VkBuffer ext_buf = VK_NULL_HANDLE;
4763 VkDeviceSize ext_off = 0;
4764 if (external_windows.find_uncached_buffer(ptr, len, ext_buf, ext_off))
4765 reqs.push_back({ext_buf, ext_off, p, static_cast<VkDeviceSize>(len)});
4766 });
4767 if (reqs.empty()) return false;
4768 std::sort(reqs.begin(), reqs.end(), [](const Req& a, const Req& b) {
4769 if (a.buf != b.buf) return a.buf < b.buf;
4770 if (a.src_off != b.src_off) return a.src_off < b.src_off;
4771 return a.len > b.len;
4772 });
4773 // Merge overlapping/adjacent ranges per VkBuffer.
4774 std::vector<Req> merged;
4775 merged.reserve(reqs.size());
4776 for (const Req& r : reqs) {
4777 if (!merged.empty() && merged.back().buf == r.buf &&
4778 r.src_off <= merged.back().src_off + merged.back().len) {
4779 const VkDeviceSize end = std::max(merged.back().src_off + merged.back().len, r.src_off + r.len);
4780 merged.back().len = end - merged.back().src_off;
4781 } else {
4782 merged.push_back(r);
4783 }
4784 }
4785 VkDeviceSize total = 0;
4786 for (const Req& r : merged) total = ((total + 63ull) & ~63ull) + r.len;
4787 if (!ensure_rebar_readback(total)) return false;
4788 std::vector<std::vector<VkBufferCopy>> per_buf_copies;
4789 std::vector<VkBuffer> bufs;
4790 rebar_readback.entries.clear();
4791 rebar_readback.entries.reserve(merged.size());
4792 VkDeviceSize dst_off = 0;
4793 for (const Req& r : merged) {
4794 dst_off = (dst_off + 63ull) & ~63ull;
4795 if (bufs.empty() || bufs.back() != r.buf) {
4796 bufs.push_back(r.buf);
4797 per_buf_copies.emplace_back();
4798 }
4799 per_buf_copies.back().push_back({r.src_off, dst_off, r.len});
4800 rebar_readback.entries.push_back(
4801 {r.src_ptr, r.src_ptr + static_cast<std::uintptr_t>(r.len), rebar_readback.mapped + dst_off});
4802 dst_off += r.len;
4803 }
4804 std::vector<leonida::VulkanContext::BufferCopyBatch> batches;
4805 batches.reserve(bufs.size());
4806 for (std::size_t i = 0; i < bufs.size(); ++i)
4807 batches.push_back({bufs[i], rebar_readback.buffer, per_buf_copies[i]});
4808 if (!context->copy_buffers_sync(batches, info.queue, info.queue_family)) {
4809 rebar_readback.entries.clear();
4810 return false;
4811 }
4812 std::sort(rebar_readback.entries.begin(), rebar_readback.entries.end(),
4813 [](const auto& a, const auto& b) { return a.src_lo < b.src_lo; });
4814 out = {rebar_readback.entries.data(), rebar_readback.entries.size()};
4815 return true;
4816 }
4610 std::vector<TitleWindow> title_windows; 4817 std::vector<TitleWindow> title_windows;
4611 std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex 4818 std::atomic<std::size_t> title_window_count{0}; // title_windows.size(), read without the mutex
4612 std::uint64_t title_window_bytes = 0; 4819 std::uint64_t title_window_bytes = 0;
@@ -5253,6 +5460,7 @@ struct DeviceState {
5253 // Each shadow takes all the ranges over it in one call, in address order (batches can overlap), and 5460 // Each shadow takes all the ranges over it in one call, in address order (batches can overlap), and
5254 // decides which of its pages are held once for all of them (ShadowPages::write_back). 5461 // decides which of its pages are held once for all of them (ShadowPages::write_back).
5255 std::vector<std::pair<std::uintptr_t, std::uintptr_t>> over; 5462 std::vector<std::pair<std::uintptr_t, std::uintptr_t>> over;
5463 ShadowPages::ReadbackLookup rebar_lookup{};
5256 if (arena.staged) { 5464 if (arena.staged) {
5257 std::vector<VkBufferCopy> readbacks; 5465 std::vector<VkBufferCopy> readbacks;
5258 std::map<std::size_t, std::vector<VkBufferCopy>> ext_readbacks; 5466 std::map<std::size_t, std::vector<VkBufferCopy>> ext_readbacks;
@@ -5266,6 +5474,19 @@ struct DeviceState {
5266 ext_readbacks); 5474 ext_readbacks);
5267 } 5475 }
5268 sync_retired_readbacks_to_host(readbacks, ext_readbacks); 5476 sync_retired_readbacks_to_host(readbacks, ext_readbacks);
5477 } else {
5478 prepare_rebar_readbacks(
5479 [&](const auto& add) {
5480 for (const ShadowPagesPtr& s : shadows) {
5481 over.clear();
5482 for (const auto& [begin, end] : finished)
5483 if (end > s->first() && begin < s->last())
5484 over.push_back(
5485 {static_cast<std::uintptr_t>(begin), static_cast<std::uintptr_t>(end)});
5486 if (!over.empty()) s->for_each_target_range(over.data(), over.size(), nullptr, add);
5487 }
5488 },
5489 rebar_lookup);
5269 } 5490 }
5270 for (const ShadowPagesPtr& s : shadows) { 5491 for (const ShadowPagesPtr& s : shadows) {
5271 over.clear(); 5492 over.clear();
@@ -5274,7 +5495,8 @@ struct DeviceState {
5274 over.push_back({static_cast<std::uintptr_t>(begin), static_cast<std::uintptr_t>(end)}); 5495 over.push_back({static_cast<std::uintptr_t>(begin), static_cast<std::uintptr_t>(end)});
5275 if (over.empty()) continue; 5496 if (over.empty()) continue;
5276 std::size_t reached = 0; 5497 std::size_t reached = 0;
5277 written += s->write_back(over.data(), over.size(), &reached); 5498 written += s->write_back(over.data(), over.size(), &reached, nullptr,
5499 rebar_lookup.count ? &rebar_lookup : nullptr);
5278 ranges += reached; 5500 ranges += reached;
5279 } 5501 }
5280 } 5502 }
@@ -24125,6 +24347,7 @@ public:
24125 state_.report_arena(); 24347 state_.report_arena();
24126 state_.destroy_address_guard(); 24348 state_.destroy_address_guard();
24127 if (state_.context) state_.destroy_page_mirror(); 24349 if (state_.context) state_.destroy_page_mirror();
24350 state_.destroy_rebar_readback();
24128 if (state_.context && state_.arena.buffer) { 24351 if (state_.context && state_.arena.buffer) {
24129 state_.context->set_arena_upload(nullptr, nullptr); 24352 state_.context->set_arena_upload(nullptr, nullptr);
24130 leonida::fsdraw::forget_arena(&state_); 24353 leonida::fsdraw::forget_arena(&state_);
diff --git a/runtime/test/arena_staging_test.cpp b/runtime/test/arena_staging_test.cpp
index e0a3ac5fd..2df2c66f0 100644
--- a/runtime/test/arena_staging_test.cpp
+++ b/runtime/test/arena_staging_test.cpp
@@ -3,6 +3,7 @@
3// coalescing, requeue, persistent mapped ranges, and readback subtraction. 3// coalescing, requeue, persistent mapped ranges, and readback subtraction.
4// No game data. 4// No game data.
5#include "../src/arena_staging.h" 5#include "../src/arena_staging.h"
6#include "../shims/d3d12_title_buffer_windows.h"
6 7
7#include <cstdio> 8#include <cstdio>
8#include <vector> 9#include <vector>
@@ -273,6 +274,133 @@ int test_compaction_under_many_small_marks() {
273 return 0; 274 return 0;
274} 275}
275 276
277int test_staged_slab_budget_and_reclamation() {
278 using leonida::memory_breakdown::Consumer;
279 struct MockVk {
280 std::vector<std::uint64_t> buf_sizes;
281 std::vector<std::vector<std::uint8_t>> mem_storage;
282 std::size_t live_buffers = 0;
283 std::size_t live_memories = 0;
284
285 VkResult vkCreateBuffer(VkDevice, const VkBufferCreateInfo* info, const VkAllocationCallbacks*,
286 VkBuffer* out) {
287 buf_sizes.push_back(info->size);
288 *out = reinterpret_cast<VkBuffer>(static_cast<std::uintptr_t>(buf_sizes.size()));
289 ++live_buffers;
290 return VK_SUCCESS;
291 }
292 void vkDestroyBuffer(VkDevice, VkBuffer b, const VkAllocationCallbacks*) {
293 if (b && live_buffers) --live_buffers;
294 }
295 void vkGetBufferMemoryRequirements(VkDevice, VkBuffer b, VkMemoryRequirements* req) {
296 const auto idx = reinterpret_cast<std::uintptr_t>(b) - 1;
297 req->size = buf_sizes[idx];
298 req->alignment = 64;
299 req->memoryTypeBits = 0x3u; // bit 0 = VRAM, bit 1 = host cached
300 }
301 VkResult vkBindBufferMemory(VkDevice, VkBuffer, VkDeviceMemory, VkDeviceSize) { return VK_SUCCESS; }
302 VkResult vkMapMemory(VkDevice, VkDeviceMemory m, VkDeviceSize, VkDeviceSize, VkMemoryMapFlags, void** out) {
303 const auto idx = reinterpret_cast<std::uintptr_t>(m) - 1;
304 *out = mem_storage[idx].data();
305 return VK_SUCCESS;
306 }
307 void vkUnmapMemory(VkDevice, VkDeviceMemory) {}
308 void vkFreeMemory(VkDevice, VkDeviceMemory m, const VkAllocationCallbacks*) {
309 if (m && live_memories) --live_memories;
310 }
311 static VkDeviceAddress get_bda(VkDevice, const VkBufferDeviceAddressInfo* info) {
312 const auto idx = reinterpret_cast<std::uintptr_t>(info->buffer);
313 return 0x100000000ull + idx * (128ull << 20);
314 }
315 VkDeviceAddress (*vkGetBufferDeviceAddress)(VkDevice, const VkBufferDeviceAddressInfo*) = &get_bda;
316 };
317 struct MockContext {
318 MockVk vk;
319 };
320 struct MockDevice {
321 MockContext ctx;
322 MockContext* context = &ctx;
323 struct {
324 VkDevice device = nullptr;
325 } info;
326 struct {
327 VkDeviceAddress address = 0x100000000ull;
328 } arena;
329 VkPhysicalDeviceMemoryProperties memory{};
330 std::size_t vram_owner_hits = 0;
331 std::size_t staging_owner_hits = 0;
332
333 MockDevice() {
334 memory.memoryTypeCount = 2;
335 memory.memoryHeapCount = 2;
336 memory.memoryHeaps[0] = {24ull << 30, VK_MEMORY_HEAP_DEVICE_LOCAL_BIT};
337 memory.memoryHeaps[1] = {64ull << 30, 0};
338 memory.memoryTypes[0] = {VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0};
339 memory.memoryTypes[1] = {VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
340 VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
341 1};
342 }
343 void share(VkBufferCreateInfo&) const {}
344 bool vsharp_offsets_signed() const { return false; }
345 VkDeviceMemory allocate(const VkMemoryRequirements& req, VkMemoryPropertyFlags required,
346 VkMemoryPropertyFlags /*preferred*/, VkMemoryPropertyFlags* chosen,
347 bool /*device_local*/) {
348 if (required & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
349 if (leonida::memory_breakdown::current_owner() == Consumer::windows) ++vram_owner_hits;
350 if (chosen) *chosen = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
351 ctx.vk.mem_storage.emplace_back(1); // VRAM doesn't need host backing
352 } else {
353 if (leonida::memory_breakdown::current_owner() == Consumer::staging) ++staging_owner_hits;
354 if (chosen)
355 *chosen = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
356 VK_MEMORY_PROPERTY_HOST_CACHED_BIT;
357 ctx.vk.mem_storage.emplace_back(64);
358 }
359 ++ctx.vk.live_memories;
360 return reinterpret_cast<VkDeviceMemory>(static_cast<std::uintptr_t>(ctx.vk.mem_storage.size()));
361 }
362 void invalidate_backed_table() {}
363 };
364
365 MockDevice dev;
366 rt::d3d12::TitleBufferWindows pool;
367 pool.set_staged(true);
368 // Cap = 256 MiB total -> fits at most TWO 64 MiB staged slabs (2 * (64 MiB VRAM + 64 MiB staging) = 256 MiB).
369 constexpr VkDeviceSize kCap = 256ull << 20;
370 VkDeviceSize off1 = 0, off2 = 0, off3 = 0;
371 std::uint8_t *m1 = nullptr, *m2 = nullptr, *m3 = nullptr;
372 bool at_cap = false;
373
374 // 1st staged slab (64 MiB VRAM + 64 MiB staging = 128 MiB reserved).
375 CHECK(pool.allocate(dev, 40ull << 20, off1, m1, false, kCap, &at_cap));
376 CHECK(!at_cap);
377 CHECK(pool.reserved() == (128ull << 20));
378 CHECK(dev.vram_owner_hits == 1 && dev.staging_owner_hits == 1);
379
380 // 2nd staged slab (40 MiB doesn't fit in 1st slab's remaining 24 MiB -> new 64 MiB slab -> 256 MiB reserved).
381 CHECK(pool.allocate(dev, 40ull << 20, off2, m2, false, kCap, &at_cap));
382 CHECK(!at_cap);
383 CHECK(pool.reserved() == (256ull << 20));
384 CHECK(dev.vram_owner_hits == 2 && dev.staging_owner_hits == 2);
385
386 // 3rd allocation exceeds the 256 MiB cap (both VRAM + host mirror accounted for) -> refused with at_cap.
387 CHECK(!pool.allocate(dev, 40ull << 20, off3, m3, false, kCap, &at_cap));
388 CHECK(at_cap);
389
390 // Freeing off1 leaves 1 empty 64 MiB spare (kept -> 256 MiB reserved); freeing off2 makes 2 empty slabs, so the
391 // 2nd is destroyed, leaving 1 spare (128 MiB reserved, 2 buffers + 2 memories live).
392 CHECK(pool.free(dev, off1, 40ull << 20));
393 CHECK(pool.reserved() == (256ull << 20));
394 CHECK(pool.free(dev, off2, 40ull << 20));
395 CHECK(pool.reserved() == (128ull << 20));
396 CHECK(dev.ctx.vk.live_buffers == 2 && dev.ctx.vk.live_memories == 2);
397
398 pool.release(dev);
399 CHECK(pool.reserved() == 0);
400 CHECK(dev.ctx.vk.live_buffers == 0 && dev.ctx.vk.live_memories == 0);
401 return 0;
402}
403
276} // namespace 404} // namespace
277 405
278int main() { 406int main() {
@@ -281,6 +409,7 @@ int main() {
281 if (test_exact_byte_dirty_coalescing()) return 1; 409 if (test_exact_byte_dirty_coalescing()) return 1;
282 if (test_mapped_ranges_and_readback_subtract()) return 1; 410 if (test_mapped_ranges_and_readback_subtract()) return 1;
283 if (test_compaction_under_many_small_marks()) return 1; 411 if (test_compaction_under_many_small_marks()) return 1;
412 if (test_staged_slab_budget_and_reclamation()) return 1;
284 std::printf("arena_staging_test: OK\n"); 413 std::printf("arena_staging_test: OK\n");
285 return 0; 414 return 0;
286} 415}
diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp
index 9708598ee..d35c10c15 100644
--- a/runtime/test/d3d12_existing_heap_test.cpp
+++ b/runtime/test/d3d12_existing_heap_test.cpp
@@ -3694,17 +3694,17 @@ int check_shadow_adopts_geometry_guard(ID3D12Device* device) {
3694 if (reader.init(device, size)) return 1; 3694 if (reader.init(device, size)) return 1;
3695 // First submission copies the initial bytes and adopts kProtected on the geometry_writes-guarded tile. 3695 // First submission copies the initial bytes and adopts kProtected on the geometry_writes-guarded tile.
3696 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); 3696 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3697 // Second clean submission skips the committed tile (only the reserved second half is queried: 1 query, not 2). 3697 // Second clean submission skips both the committed tile (kProtected) and the reserved tail (kZero).
3698 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); 3698 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3699 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1); 3699 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 0);
3700 // A write to the shared tile faults through geometry_writes + ShadowPages::reopen_range(), re-arms via 3700 // A write to the shared tile faults through geometry_writes + ShadowPages::reopen_range(), re-arms via
3701 // geometry_writes ahead of refresh_shadows(), and reaches the GPU on the next submission. 3701 // geometry_writes ahead of refresh_shadows(), and reaches the GPU on the next submission.
3702 for (SIZE_T i = 0x1000; i < 0x2000; ++i) want[i] = pages[i] = pattern_byte(i, 199); 3702 for (SIZE_T i = 0x1000; i < 0x2000; ++i) want[i] = pages[i] = pattern_byte(i, 199);
3703 EXPECT(leonida::geometry_writes::arm(tile, *cell)); 3703 EXPECT(leonida::geometry_writes::arm(tile, *cell));
3704 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); 3704 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3705 // After re-adopting kProtected, the following clean submission again skips the committed tile. 3705 // After re-adopting kProtected, the following clean submission again skips both halves.
3706 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); 3706 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3707 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1); 3707 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 0);
3708 // Marking the tile hot reopens it without a write fault and notifies title_memory_map::changed(): 3708 // Marking the tile hot reopens it without a write fault and notifies title_memory_map::changed():
3709 // adopted ShadowPages must requery and copy writes made while hot. 3709 // adopted ShadowPages must requery and copy writes made while hot.
3710 leonida::geometry_writes::set_hot(tile, true); 3710 leonida::geometry_writes::set_hot(tile, true);
@@ -3719,7 +3719,7 @@ int check_shadow_adopts_geometry_guard(ID3D12Device* device) {
3719 EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY); 3719 EXPECT((protection_of(pages) & 0xff) == PAGE_READONLY);
3720 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); 3720 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3721 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1); 3721 EXPECT(reader.read(buffer.p, got) == 0 && first_difference(got, want) == -1);
3722 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 1); 3722 EXPECT(rt::d3d12::title_shadow_refresh_queries(device) == 0);
3723 } 3723 }
3724 // ShadowPages destruction reopened the adopted tile and called note_external_reopen(), clearing Cell::restore[]. 3724 // ShadowPages destruction reopened the adopted tile and called note_external_reopen(), clearing Cell::restore[].
3725 EXPECT((protection_of(pages) & 0xff) == PAGE_READWRITE); 3725 EXPECT((protection_of(pages) & 0xff) == PAGE_READWRITE);
diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py
index 80e323f2c..404faeed9 100644
--- a/tools/rdna2spirv.py
+++ b/tools/rdna2spirv.py
@@ -24174,7 +24174,7 @@ def main():
24174 ap.add_argument("--compact-spirv", action="store_true", 24174 ap.add_argument("--compact-spirv", action="store_true",
24175 help="remove redundant local loads, repeated values and dead instructions with spirv-opt") 24175 help="remove redundant local loads, repeated values and dead instructions with spirv-opt")
24176 ap.add_argument("--spirv-opt", action="store_true", 24176 ap.add_argument("--spirv-opt", action="store_true",
24177 help="run spirv-opt (-O below 750 KiB, safe SSA pass set at >= 750 KiB) with automatic fallback " 24177 help="run spirv-opt (-O below 512 KiB, safe SSA pass set at >= 512 KiB) with automatic fallback "
24178 "to unoptimized SPIR-V if spirv-opt or spirv-val rejects the optimized module") 24178 "to unoptimized SPIR-V if spirv-opt or spirv-val rejects the optimized module")
24179 ap.add_argument("--opt", action="store_true", 24179 ap.add_argument("--opt", action="store_true",
24180 help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load " 24180 help="run basic-block SPIR-V peephole optimization (tools/spirv_opt.py: register store-to-load "